@aiquants/daily-report 0.23.0 → 0.24.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 +32 -0
- package/dist/server.d.mts +10 -8
- package/dist/server.d.ts +10 -8
- package/dist/server.js +4 -4
- package/dist/server.mjs +4 -4
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,38 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@aiquants/daily-report` are documented here.
|
|
4
4
|
|
|
5
|
+
## 0.24.0 (2026-10-03)
|
|
6
|
+
|
|
7
|
+
共有 SSE リーダーを `@aiquants/sse` の `createSharedSource` へ載せ替え、接続の直後に足されたエントリが配られないことのある順序の誤りを直す。
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- **共有リーダーを `createSharedSource` へ載せ替え**: `DailyReportSseReader` の参照カウント・状態機械と、状態の遷移を 50 ms 周期で待つ 2 本のループを、
|
|
12
|
+
`@aiquants/sse` の `createSharedSource` (`lingerMs: 0`・`replay: "none"`) へ置き換える。最初の購読者で専用のブロッキングクライアントと `xRead` のループ (run) を
|
|
13
|
+
1 本起動し、最後の解除で即時に止める。停止の最中の購読は次の run が受け持つ。再開位置は購読者へエントリが届いたときだけ進み、停止させた run が読んで
|
|
14
|
+
配れなかったエントリは次の run が読み直す。run の失敗 (クライアントの生成失敗・`xRead` の例外・予期しない切断) は全購読者を切り離して各自の `onError` を呼び、
|
|
15
|
+
次の購読で新しい run を起動する。
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- **`DailyReportSseReader.ready()`**: 読み取り位置が具体 ID に固定された時点で解決する Promise を返す (以後にストリームへ足されたエントリは今の購読者全員へ届く)。
|
|
20
|
+
プロセスの最初の run の前と `destroy()` の後だけストリームの末尾を 1 回読み (run の起動と共有)、以後は即時に解決する。末尾を読めないときも `"$"` の縮退のまま
|
|
21
|
+
解決し、拒否しない。
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
- **接続の直後のエントリの取りこぼし**: プロセス最初の購読では、共有リーダーが位置をストリームの末尾へ非同期に固定する前に `connected` が届いていたため、
|
|
26
|
+
それを見て足されたエントリが固定前の末尾に入り、どの接続にも配られなかった。カーソルの無い接続は `ready()` を待ってから最新 ID を読んで `connected` を書き、
|
|
27
|
+
カーソル経路は `connected` を先に書いたまま catch-up の読取りを `ready()` の後へ回す (catch-up と位置の固定の間に足されたエントリも落とさない)。
|
|
28
|
+
`destroy()` の前に始まった末尾の読取りは、その後の位置を書き換えない。
|
|
29
|
+
|
|
30
|
+
### Breaking
|
|
31
|
+
|
|
32
|
+
- **`subscribe` の `onError` が必須に**: `DailyReportSseReader.subscribe(onEntry, onError)` の `onError` は省略できない。run の失敗は内部の `"error"` イベントでは
|
|
33
|
+
なく各購読者の `onError` へだけ届き、呼ばれた時点で購読は解除済みなので、呼び出し側は接続を閉じてクライアントに開き直させる (同梱の SSE ハンドラはそうしている)。
|
|
34
|
+
購読者が残っていても失敗した run は再起動せず、次の購読が新しい run を起動する。購読より前に読んだエントリは再生しない。`destroy()` は全購読者を通知なしで
|
|
35
|
+
外して run を止め、読み取り位置を初期化する (実行中の `subscribe` は例外になる)。リーダーを自前で差し替えるホストは `ready()` も実装する。
|
|
36
|
+
|
|
5
37
|
## 0.23.0 (2026-10-03)
|
|
6
38
|
|
|
7
39
|
List / DetailList のキーボード操作と画像添付のサムネイル (`?thumbnail=tile`) を加え、両ビューの選択・フォーカス・行の幾何と添付配信の契約を仕上げる。どれも README の該当の節が今の契約を記す。
|
package/dist/server.d.mts
CHANGED
|
@@ -1590,18 +1590,20 @@ type DailyReportSseReaderConfig = {
|
|
|
1590
1590
|
};
|
|
1591
1591
|
declare class DailyReportSseReader {
|
|
1592
1592
|
private readonly config;
|
|
1593
|
-
private
|
|
1594
|
-
private _state;
|
|
1595
|
-
private _refCount;
|
|
1593
|
+
private _source;
|
|
1596
1594
|
private _lastId;
|
|
1597
|
-
private
|
|
1595
|
+
private _positioning;
|
|
1596
|
+
private _generation;
|
|
1598
1597
|
private readonly _logger;
|
|
1599
1598
|
constructor(config: DailyReportSseReaderConfig);
|
|
1600
|
-
|
|
1599
|
+
ready(): Promise<void>;
|
|
1600
|
+
subscribe(onEntry: (entry: StreamEntry) => void, onError: (err: Error) => void): () => void;
|
|
1601
1601
|
destroy(): Promise<void>;
|
|
1602
|
-
private
|
|
1603
|
-
private
|
|
1604
|
-
private
|
|
1602
|
+
private _readTail;
|
|
1603
|
+
private _createSource;
|
|
1604
|
+
private _start;
|
|
1605
|
+
private _readLoop;
|
|
1606
|
+
private _invalidateCaches;
|
|
1605
1607
|
}
|
|
1606
1608
|
type LoaderArgs = {
|
|
1607
1609
|
request: Request;
|
package/dist/server.d.ts
CHANGED
|
@@ -1590,18 +1590,20 @@ type DailyReportSseReaderConfig = {
|
|
|
1590
1590
|
};
|
|
1591
1591
|
declare class DailyReportSseReader {
|
|
1592
1592
|
private readonly config;
|
|
1593
|
-
private
|
|
1594
|
-
private _state;
|
|
1595
|
-
private _refCount;
|
|
1593
|
+
private _source;
|
|
1596
1594
|
private _lastId;
|
|
1597
|
-
private
|
|
1595
|
+
private _positioning;
|
|
1596
|
+
private _generation;
|
|
1598
1597
|
private readonly _logger;
|
|
1599
1598
|
constructor(config: DailyReportSseReaderConfig);
|
|
1600
|
-
|
|
1599
|
+
ready(): Promise<void>;
|
|
1600
|
+
subscribe(onEntry: (entry: StreamEntry) => void, onError: (err: Error) => void): () => void;
|
|
1601
1601
|
destroy(): Promise<void>;
|
|
1602
|
-
private
|
|
1603
|
-
private
|
|
1604
|
-
private
|
|
1602
|
+
private _readTail;
|
|
1603
|
+
private _createSource;
|
|
1604
|
+
private _start;
|
|
1605
|
+
private _readLoop;
|
|
1606
|
+
private _invalidateCaches;
|
|
1605
1607
|
}
|
|
1606
1608
|
type LoaderArgs = {
|
|
1607
1609
|
request: Request;
|
package/dist/server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Tt=Object.defineProperty;var Dn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var _n=Object.prototype.hasOwnProperty;var Jt=e=>{throw TypeError(e)};var In=(e,t)=>{for(var r in t)Tt(e,r,{get:t[r],enumerable:!0})},En=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of wn(t))!_n.call(e,a)&&a!==r&&Tt(e,a,{get:()=>t[a],enumerable:!(n=Dn(t,a))||n.enumerable});return e};var Cn=e=>En(Tt({},"__esModule",{value:!0}),e);var Kt=(e,t,r)=>t.has(e)||Jt("Cannot "+r);var Ve=(e,t,r)=>(Kt(e,t,"read from private field"),r?r.call(e):t.get(e)),At=(e,t,r)=>t.has(e)?Jt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Dt=(e,t,r,n)=>(Kt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Ja={};In(Ja,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>$t,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>Ut,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>Vt,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>zt,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>yt,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>qt,DailyReportSseReader:()=>$e,DailyReportViewerScope:()=>ye,SqlResultCache:()=>ke,createDailyReportHandlers:()=>ht,createDailyReportServer:()=>Wa,createDailyReportService:()=>ft,createEpochStore:()=>nt,createSharpThumbnailRenderer:()=>an,defineDailyReportSchema:()=>Kr,generateETag:()=>Be,isStreamIdLte:()=>De,jsonResponseWithETag:()=>pe,predictSharpThumbnailWorkingSetBytes:()=>nn,transformJsonArray:()=>Jr});module.exports=Cn(Ja);var nt=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{}}}),ke=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.invalidate=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,a=this.buckets.get(n);if(!a)return;let l=t.ttlMsOverride??this.config.defaultTtlMs;if(l-(a.expireAt-Date.now())<l*r||this.inFlight.has(n))return;let c;c=(async()=>{let T=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===c&&this.buckets.set(n,{records:s,expireAt:Date.now()+l,epoch:T}),s})(),this.inFlight.set(n,c),c.catch(()=>{}).finally(()=>{this.inFlight.get(n)===c&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:a}=t,l=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&l&&l.expireAt>Date.now())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||l.epoch===c)return this.maybeRefreshAhead(t),a?l.records.map(T=>structuredClone(T)):l.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),a?l.records.map(c=>structuredClone(c)):l.records;if(!n&&this.inFlight.has(r)){let c=await this.inFlight.get(r);return a?c.map(T=>structuredClone(T)):c}let p;p=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let T=await t.fetcher();if(n||this.inFlight.get(r)===p){let s=Date.now()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:T,expireAt:s,epoch:c}),this.buckets.size>500&&this.cleanExpired()}return T})(),n||this.inFlight.set(r,p);try{let c=await p;return a?c.map(T=>structuredClone(T)):c}finally{this.inFlight.get(r)===p&&this.inFlight.delete(r)}};this.flush=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=Date.now();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var jr=require("@aiquants/sse"),we=require("@aiquants/sse/server");var xn=/^\d{4}-\d{2}-\d{2}$/,vn=/^\d{4}\/\d{2}\/\d{2}$/,Qt=e=>e<10?`0${e}`:`${e}`,Xt=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Qt(e.getMonth()+1),n=Qt(e.getDate());return`${t}-${r}-${n}`};var ue=e=>{if(e==null)return null;if(e instanceof Date)return Xt(e);let t=e.trim();if(t==="")return null;if(xn.test(t))return t;if(vn.test(t))return t.replaceAll("/","-");let r=new Date(t);return Xt(r)};var wt=e=>{let t=2166136261,r=-624069552;for(let n of e){let a=n.reportHubId;t^=a&255,t=Math.imul(t,16777619),t^=a>>>8&255,t=Math.imul(t,16777619),t^=a>>>16&255,t=Math.imul(t,16777619),t^=a>>>24&255,t=Math.imul(t,16777619),r^=a>>>24&255,r=Math.imul(r,16777619),r^=a>>>16&255,r=Math.imul(r,16777619),r^=a>>>8&255,r=Math.imul(r,16777619),r^=a&255,r=Math.imul(r,16777619);let l=n.businessDate;if(l===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let p=0;p<l.length;p++){let c=l.charCodeAt(p);t^=c&255,t=Math.imul(t,16777619),r^=c&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},at=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,Zt=e=>{for(let t=1;t<e.length;t++)if(at(e[t-1],e[t])>0)return!1;return!0};var er=(e,t)=>{let r=e.findIndex(n=>at({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var me=(e,t,r=console)=>{let n=a=>typeof a=="string"?[`${t} ${a}`]:[t,a];return{debug:(a,...l)=>{e<=0&&r.debug(...n(a),...l)},info:(a,...l)=>{e<=1&&r.info(...n(a),...l)},warn:(a,...l)=>{e<=2&&r.warn(...n(a),...l)},error:(a,...l)=>{e<=3&&r.error(...n(a),...l)}}};var f=require("zod");var tr=15e3,rr="lastEventId",Mn=/^\d{1,15}-\d{1,15}$/,nr=e=>Mn.test(e),Ln=f.z.object({name:f.z.string().nullish(),affiliation:f.z.string().nullish()}),Pn=f.z.object({name:f.z.string().nullish(),text:f.z.string().nullish(),color:f.z.string().nullish()}),kn=f.z.object({id:f.z.number(),name:f.z.string().nullish(),color:f.z.string().nullish()}),ar=f.z.object({id:f.z.number(),userId:f.z.string().nullish(),userName:f.z.string().nullish(),content:f.z.string().nullish(),createdAt:f.z.string().nullish(),isMine:f.z.boolean()}),Nn=f.z.object({id:f.z.string(),fileName:f.z.string(),fileType:f.z.string().nullable(),fileSize:f.z.number().nullable(),createdAt:f.z.string().nullable(),state:f.z.enum(["present","absent","unknown"]),hasThumbnail:f.z.boolean().default(!1)}),_t=f.z.object({reportHubId:f.z.number(),date:f.z.string().nullish(),createdAt:f.z.string().nullish(),author:f.z.string().nullish(),userId:f.z.string().nullish(),sourceType:f.z.string().nullish(),employeeName:f.z.string().nullish(),updatedBy:f.z.string().nullish(),updatedAt:f.z.string().nullish(),category:f.z.string().nullish(),creationCategory:f.z.string().nullish(),visitTimeFrom:f.z.string().nullish(),visitTimeTo:f.z.string().nullish(),customerName:f.z.string().nullish(),interviewers:f.z.array(Ln),subject:f.z.string().nullish(),content:f.z.string().nullish(),externalComments:f.z.array(Pn),isRead:f.z.boolean(),isStarred:f.z.boolean(),labels:f.z.array(kn),postedComments:f.z.array(ar),attachments:f.z.array(Nn).default([])}),On=f.z.object({type:f.z.literal("connected")}),it=f.z.object({type:f.z.literal("status-update"),reportHubId:f.z.number(),statusType:f.z.enum(["star","read"]),value:f.z.boolean(),clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),It=f.z.string().optional(),Et=f.z.object({type:f.z.literal("comment-add"),reportHubId:f.z.number(),comment:ar,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional(),sourceType:It}),Ct=f.z.object({type:f.z.literal("comment-delete"),reportHubId:f.z.number(),commentId:f.z.number(),clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional(),sourceType:It}),xt=f.z.object({type:f.z.literal("report-create"),reportHubId:f.z.number(),report:_t,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),vt=f.z.object({type:f.z.literal("report-update"),reportHubId:f.z.number(),report:_t,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),Mt=f.z.object({type:f.z.literal("report-publish"),reportHubId:f.z.number(),report:_t,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),Lt=f.z.object({type:f.z.literal("report-delete"),reportHubId:f.z.number(),clientTempId:f.z.string(),sourceType:It}),ir=f.z.discriminatedUnion("type",[On,it,Et,Ct,xt,vt,Mt,Lt]);var Pt=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),or=e=>Object.hasOwn(Pt,e);var Bn="download",Un="thumbnail",$n="1";var sr=e=>{let t=e.getAll(Un),r=e.getAll(Bn);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&or(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===$n?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var lr=(e,t)=>(r,n)=>{let a=n?"markAttachmentPresent":"markAttachmentMissing";e[a](r).catch(l=>{t.error(`${a} failed attachment=${r} message=${l instanceof Error?l.message:"unknown"}`)})};var ot=6e4/1e3,st=5e3/1e3,ur=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},cr=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Fn=/^[\x20-\x7E]+$/,qn=/^[\w.+-]+\/[\w.+-]+/,kt=e=>e&&Fn.test(e)&&qn.test(e)?e:null,dr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),mr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),lt=e=>{switch(e){case"not_found":case"denied":case"invalid_path":return 404;case"too_large":return 413;default:return 502}},pr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable"},Ne="Attachment request failed";var Yn=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Oe=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Yn(r)}`),ut=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var yr=32*1024*1024,Vn=60,zn=4,jn=120,Gn=2,Wn=8*1024*1024,he=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw Oe(e,`an integer >= ${r}`,t)},Ie=(e,t,r,n)=>t===void 0?n:he(e,t,r),Jn=[["attachmentThumbnailRenderer",["readAttachment","attachmentIdCodec"]],["readAttachment",["attachmentIdCodec"]],["attachmentIdCodec",["readAttachment"]],["attachmentMaxBytes",["readAttachment"]],["attachmentRateLimitPerMinute",["readAttachment"]],["attachmentConcurrency",["readAttachment"]],["attachmentThumbnailRateLimitPerMinute",["attachmentThumbnailRenderer"]],["attachmentThumbnailConcurrency",["attachmentThumbnailRenderer"]],["attachmentThumbnailCacheBytes",["attachmentThumbnailRenderer"]]],Nt=e=>{for(let[t,r]of Jn){if(e[t]===void 0)continue;let n=r.find(a=>e[a]===void 0);if(n!==void 0)throw ut(n,`injected when ${t} is given`)}},hr=(e,t)=>(Nt({attachmentIdCodec:t.idCodec,readAttachment:t.readAttachment,attachmentThumbnailRenderer:t.thumbnailRenderer,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes}),Object.freeze({originalRateLimitPerMinute:Ie("attachmentRateLimitPerMinute",e.attachmentRateLimitPerMinute,1,Vn),originalConcurrency:Ie("attachmentConcurrency",e.attachmentConcurrency,1,zn),thumbnailRateLimitPerMinute:Ie("attachmentThumbnailRateLimitPerMinute",e.attachmentThumbnailRateLimitPerMinute,1,jn),thumbnailConcurrency:Ie("attachmentThumbnailConcurrency",e.attachmentThumbnailConcurrency,1,Gn),thumbnailCacheBytes:Ie("attachmentThumbnailCacheBytes",e.attachmentThumbnailCacheBytes,0,Wn)}));var ct=e=>{let t=he("limit",e.limit,1),r=e.queue===null?null:{max:he("queue.max",e.queue.max,0),maxPerOwner:he("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:he("queue.maxWaitMs",e.queue.maxWaitMs,1)},n=0,a=[],l=new Map,p=(s,g)=>{let m=(l.get(s)??0)+g;m<=0?l.delete(s):l.set(s,m)},c=()=>{for(;n<t;){let s=a.shift();if(!s)return;p(s.owner,-1),n+=1,s.grant(T())}},T=()=>{let s=!1;return()=>{s||(s=!0,n-=1,c())}};return{acquire:(s,g)=>{if(g.aborted)return Promise.resolve(null);if(n<t)return n+=1,Promise.resolve(T());if(r===null||a.length>=r.max||(l.get(s)??0)>=r.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:m}=r,_=A=>{let E=()=>{let S=a.indexOf(Q);S<0||(a.splice(S,1),p(s,-1),H(),A(null))},J=setTimeout(E,m);J.unref?.();let H=()=>{clearTimeout(J),g.removeEventListener("abort",E)},Q={owner:s,grant:S=>{H(),A(S)}};a.push(Q),p(s,1),g.addEventListener("abort",E,{once:!0})};return new Promise(_)}}};var Kn=1024,ze=e=>{he("limitPerMinute",e,1);let t=new Map,r=(p,c)=>{c<=p.lastRefillMs||(p.tokens=Math.min(e,p.tokens+(c-p.lastRefillMs)*e/6e4),p.lastRefillMs=c)},n=(p,c)=>{let T=t.get(p);T&&t.delete(p);let s=T??{tokens:e,lastRefillMs:c,deniedSinceAdmission:0};r(s,c),t.set(p,s);for(let g of t.keys()){if(t.size<=Kn)break;t.delete(g)}return s},a=p=>{if(p.tokens<1)return null;p.tokens-=1;let c=Math.max(0,p.deniedSinceAdmission-1);return p.deniedSinceAdmission=0,{allowed:!0,suppressedDenials:c}},l=p=>(p.deniedSinceAdmission+=1,{allowed:!1,firstDenial:p.deniedSinceAdmission===1});return{consume:(p,c)=>{let T=n(p,c);return a(T)??l(T)},refund:(p,c,T)=>{let s=t.get(p);s&&(r(s,c),s.tokens=Math.min(e,s.tokens+T))}}};var Qn=12e4,Xn=(e,t,r)=>{let n=setTimeout(t,r);n.unref?.();let a=()=>{clearTimeout(n),t()},l=!1;return new ReadableStream({pull(p){if(l){p.close(),a();return}l=!0,p.enqueue(e)},cancel(){a()}})},fr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:l}=e,p=t.attachmentDelivery,c=ze(e.rateLimitPerMinute),T=ct({limit:e.concurrency,queue:null});return async s=>{let{request:g,delivery:m,attachmentId:_,internalUserId:A,readAttachment:E,cookie:J,fail:H}=s,Q=p.maxBytes,S=c.consume(A,Date.now());if(!S.allowed)return S.firstDenial&&a.warn(`429 attachment=${_} viewer=${A} reason=rate_limit`),H(429,"Too many requests",{"Retry-After":String(ot)});S.suppressedDenials>0&&a.warn(`rate_limit_suppressed count=${S.suppressedDenials} viewer=${A}`);let L=await n(g),V=await t.getAttachmentForUser(L,_,A);if(!V)return a.warn(`404 attachment=${_} viewer=${A} reason=not_visible`),H(404,"Attachment not found");if(V.fileSize!=null&&V.fileSize>Q)return a.warn(`413 attachment=${_} viewer=${A} reason=db_size`),H(413,"Attachment too large");let F=await T.acquire(A,g.signal);if(!F)return g.signal.aborted?(a.info(`503 attachment=${_} viewer=${A} reason=aborted`),H(503,"Attachment request aborted")):(a.warn(`503 attachment=${_} viewer=${A} reason=concurrency`),H(503,"Too many concurrent downloads",{"Retry-After":String(st)}));let R=!1;try{let M=g.method==="HEAD",I=await E(V.filePath,{maxBytes:Q,head:M,principal:r(A),signal:g.signal});if(g.signal.aborted)return a.info(`503 attachment=${_} viewer=${A} reason=aborted`),H(503,"Attachment request aborted");if(!I.ok){let v=lt(I.reason);return I.reason==="not_found"&&l(_,!1),a.warn(`${v} attachment=${_} viewer=${A} reason=${I.reason} code=${I.code??"-"}`),H(v,pr[v])}if(I.bytes.byteLength>Q)return a.error(`500 attachment=${_} viewer=${A} reason=port_contract code=over_max_bytes`),H(500,Ne);let P=kt(V.fileType)??kt(I.contentType),b=P!==null&&cr.has(P),x=b?P:"application/octet-stream",q=b&&m.kind!=="download"?"inline":"attachment",O=I.size??I.bytes.byteLength,Y=new Headers({"Content-Type":x,"Content-Length":String(O),"Content-Disposition":`${q}; filename="${mr(V.fileName)}"; filename*=UTF-8''${dr(V.fileName)}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return J&&Y.append("Set-Cookie",J),l(_,!0),a.info(`200 attachment=${_} viewer=${A} type=${x} disposition=${q} bytes=${O}`),M?new Response(null,{status:200,headers:Y}):(R=!0,new Response(Xn(I.bytes,F,Qn),{status:200,headers:Y}))}finally{R||F()}}};var Re=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),wi=Re.queueWaitMs+Re.readMs+Re.renderMs+Re.transferMarginMs;var br=require("crypto"),Be=e=>{let t=JSON.stringify(e);return`"${(0,br.createHash)("sha256").update(t).digest("hex")}"`};var Zn=new Set([194,198,202,206]),ea=64,ta=2,gr=8,Rr=28,Ae=12,Ot=8,ra=20,Sr=Ae+Ot+10,na=2,Se=(e,t)=>e[t]<<8|e[t+1],Ue=(e,t,r)=>{let n=0;for(let a=r-1;a>=0;a-=1)n=n*256+e[t+a];return n},fe=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},aa=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Bt=e=>{if(e[0]!==255||e[1]!==216)return null;let t=null,r=2;for(;r<e.byteLength;){if(e[r]!==255)return null;for(;r<e.byteLength&&e[r]===255;)r+=1;if(r>=e.byteLength)return null;let n=e[r];if(r+=1,n===0||n===216||n===217)return null;if(n===1||n>=208&&n<=215)continue;if(r+2>e.byteLength)return null;let a=Se(e,r),l=r+2,p=r+a;if(a<2||p>e.byteLength)return null;if(aa(n)){if(t!==null||a<8)return null;let c=Se(e,l+1),T=Se(e,l+3),s=e[l+5];if(T===0||c===0||s===0||a!==8+3*s)return null;let g=[];for(let m=0;m<s;m+=1){let _=e[l+7+3*m],A=_>>4,E=_&15;if(A<1||A>4||E<1||E>4)return null;g.push({horizontal:A,vertical:E})}t={width:T,height:c,components:g,progressive:Zn.has(n)}}else if(n===218){if(t===null||a<3)return null;let c=e[l];return c<1||c>4||a!==6+2*c?null:{width:t.width,height:t.height,components:t.components,multiScan:t.progressive||c<t.components.length}}r=p}return null},Tr=e=>{if(!e.multiScan)return 0;let t=Math.max(...e.components.map(a=>a.horizontal)),r=Math.max(...e.components.map(a=>a.vertical)),n=0;for(let{horizontal:a,vertical:l}of e.components){let p=Math.ceil(e.width*a/(t*gr)),c=Math.ceil(e.height*l/(r*gr));n+=Math.ceil(p/a)*a*Math.ceil(c/l)*l}return n*ea*ta},Ar=e=>{if(e.byteLength<24||Se(e,8)!==0||Se(e,10)!==13||!fe(e,12,"IHDR"))return null;let t=Se(e,16)*65536+Se(e,18),r=Se(e,20)*65536+Se(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},ia=e=>{if(fe(e,Ae,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ue(e,26,2)&16383,r=Ue(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(fe(e,Ae,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ue(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return fe(e,Ae,"VP8X")?e.byteLength<Sr?null:{width:Ue(e,24,3)+1,height:Ue(e,27,3)+1}:null},Dr=e=>{if(Ar(e)===null||e.byteLength<=Rr)return null;switch(e[Rr]){case 0:return!1;case 1:return!0;default:return null}},wr=e=>{if(fe(e,Ae,"VP8 "))return"lossy";if(fe(e,Ae,"VP8L"))return"lossless";if(!fe(e,Ae,"VP8X")||e.byteLength<Sr)return null;if((e[ra]&na)!==0)return"animated";let t=!1;for(let r=Ae;r+Ot<=e.byteLength;){if(fe(e,r,"VP8L"))return"lossless";if(fe(e,r,"VP8 "))return t?"lossy-alpha":"lossy";fe(e,r,"ALPH")&&(t=!0);let n=Ue(e,r+4,4);r+=Ot+n+n%2}return null},_r={png:Ar,jpeg:Bt,webp:ia};var oa=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Ut=Object.freeze(["image/webp","image/jpeg","image/png"]),sa={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},la=new Set(Ut),ua=e=>typeof e=="string"&&la.has(e),$t=1024*1024,ca=256,dt=(e,t)=>e.fileType===null||!oa.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,da=[137,80,78,71,13,10,26,10],ma=[255,216,255],pa=[[71,73,70,56,55,97],[71,73,70,56,57,97]],ya=[82,73,70,70],ha=[87,69,66,80],je=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,a]of t.entries())if(e[r+n]!==a)return!1;return!0},Ht=e=>{if(je(e,da,0))return"png";if(je(e,ma,0))return"jpeg";for(let t of pa)if(je(e,t,0))return"gif";return je(e,ya,0)&&je(e,ha,8)?"webp":null},Ir=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Be([t])}},Er=(e,t)=>{if(!ua(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>$t)return"too_large";let r=sa[e.contentType];if(Ht(e.bytes)!==r)return"signature";let n=_r[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Cr=e=>{he("maxBytes",e.maxBytes,0),he("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=a=>{let l=t.get(a);l&&(t.delete(a),r-=l.weight)};return{get:a=>{let l=t.get(a);if(l)return t.delete(a),t.set(a,l),l.entry},set:(a,l)=>{n(a);let p=(l.kind==="thumbnail"?l.bytes.byteLength:0)+ca;if(p>e.maxBytes||e.maxEntries===0)return;let c=l.kind==="thumbnail"?{kind:"thumbnail",bytes:l.bytes.slice(),contentType:l.contentType}:l;t.set(a,{entry:c,weight:p}),r+=p;for(let T of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(T)}}}};var xr=()=>{let e=new Map;return{join:(t,r,n)=>{let a=()=>{let T=new AbortController,s=()=>{e.get(t)?.controller===T&&e.delete(t)},m={promise:n(T.signal).finally(s),controller:T,waiters:0};return e.set(t,m),m},l=e.get(t)??a();l.waiters+=1;let p=()=>{l.waiters-=1,!(l.waiters>0)&&(l.controller.abort(),e.get(t)===l&&e.delete(t))};r.aborted?p():r.addEventListener("abort",p,{once:!0});let c=()=>{r.removeEventListener("abort",p)};return l.promise.finally(c)}}};var Ft=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:a,onStuck:l}=e,p=Date.now(),c=new AbortController,T=!1,s,g,m=(F,R)=>{let M=setTimeout(F,R);return M.unref?.(),M},_=()=>{l(Date.now()-p)},A=F=>{s=m(()=>{T=!0,F({timedOut:!0}),g=m(_,t),c.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},E=new Promise(A),J=AbortSignal.any([r,c.signal]),H=F=>{F(n(J))},Q=new Promise(H),S=F=>{clearTimeout(s),clearTimeout(g),T&&a(Date.now()-p,F)},L=Q.then(()=>S(null),F=>S({error:F}));return{outcome:Promise.race([Q.then(F=>({timedOut:!1,value:F})),E]),settled:L}};var Ee={404:"Attachment not found",500:Ne,502:"Thumbnail unavailable",503:"Too many concurrent thumbnail requests"},vr=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:a,recordObjectState:l,logger:p}=e,c=(g,m)=>{if(g.fileSize===null||(m.kind==="exact"?m.bytes===g.fileSize:g.fileSize>m.maxBytes))return"verified";let A=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return p.warn(`size_mismatch expected=${g.fileSize} got=${A} attachment=${g.attachmentId} viewer=${g.owner} variant=thumbnail`),"unverified"},T=(g,m)=>(_,A)=>{let E=A===null?"":` message=${A.error instanceof Error?A.error.message:"unknown"}`;p.warn(`${g}_overrun ms=${_} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${E}`)},s=(g,m)=>_=>{p.warn(`${g}_stuck ms=${_} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(g,m)=>{let _=await t.acquire(g.owner,m);if(!_)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};let A=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let E=Ft({budgetMs:Re.readMs,flightSignal:m,call:I=>g.readAttachment(g.filePath,{maxBytes:n,head:!1,principal:a(g.owner),signal:I}),onOverrun:T("read",g),onStuck:s("read",g)}),J=await E.outcome;if(J.timedOut)return A=E.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let H=J.value;if(!H.ok&&H.reason!=="too_large")return H.reason==="not_found"&&l(g.attachmentId,!1),{kind:"failure",status:lt(H.reason)===404?404:502,reason:H.reason,code:H.code};if(H.ok&&H.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let Q=c(g,H.ok?{kind:"exact",bytes:H.bytes.byteLength}:{kind:"over",maxBytes:n}),S=I=>(Q==="verified"&&r.set(g.key,I),{...I,identity:Q});if(!H.ok)return S({kind:"unrenderable",reason:"too_large"});let L=Ht(H.bytes);if(L===null)return S({kind:"unrenderable",reason:"signature"});let V=Ft({budgetMs:Re.renderMs,flightSignal:m,call:I=>g.renderer.render(H.bytes,{format:L,maxWidth:g.box.maxWidth,maxHeight:g.box.maxHeight,signal:I}),onOverrun:T("render",g),onStuck:s("render",g)}),F=await V.outcome;if(F.timedOut)return A=V.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let R=F.value;if(!R.ok)return R.reason==="unsupported"?S({kind:"unrenderable",reason:"unsupported"}):R.reason==="failed"?{kind:"failure",status:502,reason:"render_failed"}:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};let M=Er(R,g.box);return M!==null?{kind:"failure",status:500,reason:"port_contract",code:M}:S({kind:"thumbnail",bytes:R.bytes,contentType:R.contentType})}finally{A===null?_():A.then(_)}}};var Pr=10,fa=1/Pr,Mr=1-fa,ba=1024,ga=64,Ra=8,Lr="private, no-cache",Sa="no-store",Ta=e=>{switch(e.status){case 404:case 502:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},kr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:l}=e,p=t.attachmentDelivery,c=ze(e.rateLimitPerMinute),T=ze(e.rateLimitPerMinute*Pr),s=ct({limit:e.concurrency,queue:{max:ga,maxPerOwner:Ra,maxWaitMs:Re.queueWaitMs}}),g=Cr({maxBytes:e.cacheBytes,maxEntries:ba}),m=xr(),_=vr({gate:s,cache:g,maxBytes:p.maxBytes,encodeUserId:r,recordObjectState:l,logger:a}),A=(S,L,V,F)=>{let R=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${F}`;if(L.kind==="failure")return a[Ta(L)](`${L.status} ${R} reason=${L.reason} code=${L.code??"-"}`),S.fail(L.status,Ee[L.status],L.status===503?{"Retry-After":String(st)}:{});let M=L.identity==="verified"?"":` identity=${L.identity}`;if(L.kind==="unrenderable")return a.info(`404 ${R} reason=${L.reason}${M}`),S.fail(404,Ee[404]);let I=L.identity==="verified"?{"Cache-Control":Lr,ETag:V}:{"Cache-Control":Sa},P=new Headers({"Content-Type":L.contentType,"Content-Length":String(L.bytes.byteLength),...I,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return S.cookie&&P.append("Set-Cookie",S.cookie),a.info(`200 ${R} type=${L.contentType} bytes=${L.bytes.byteLength}${M}`),new Response(L.bytes,{status:200,headers:P})},E=(S,L,V)=>(L.firstDenial&&a.warn(`429 attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail reason=${V}`),S.fail(429,"Too many requests",{"Retry-After":String(ot)})),J=(S,L,V)=>{L.suppressedDenials>0&&a.warn(`${V}_suppressed count=${L.suppressedDenials} viewer=${S.internalUserId} variant=thumbnail`)},H=S=>{let L=c.consume(S.internalUserId,Date.now());return L.allowed?(J(S,L,"rate_limit"),null):E(S,L,"rate_limit")},Q=(S,L)=>{if(!L)return H(S);let V=T.consume(S.internalUserId,Date.now());return V.allowed?(J(S,V,"revalidation_rate_limit"),null):E(S,V,"revalidation_rate_limit")};return async(S,L)=>{let{request:V,attachmentId:F,internalUserId:R,readAttachment:M,cookie:I,fail:P}=S,b=Pt[L],x=p.thumbnailRenderer;if(!x)return P(404,Ee[404]);let q=V.headers.get("If-None-Match"),O=q!==null,Y=Q(S,O);if(Y)return Y;let v=await n(V),$=await t.getAttachmentForUser(v,F,R),j=$!==null&&dt($,p.maxBytes)?Ir({rendererId:x.id,box:b,attachmentId:F,filePath:$.filePath,fileType:$.fileType,fileSize:$.fileSize}):null;if(j&&ur(q,j.etag)){let C=new Headers({"Cache-Control":Lr,ETag:j.etag});return I&&C.append("Set-Cookie",I),a.info(`304 attachment=${F} viewer=${R} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:C})}if(O){let C=H(S);if(C)return C}if(!$)return a.warn(`404 attachment=${F} viewer=${R} variant=thumbnail reason=not_visible`),P(404,Ee[404]);if(!j)return c.refund(R,Date.now(),Mr),a.info(`404 attachment=${F} viewer=${R} variant=thumbnail reason=not_eligible`),P(404,Ee[404]);let{key:z,etag:ee}=j,K=g.get(z);if(K)return c.refund(R,Date.now(),Mr),A(S,{...K,identity:"verified"},ee,"hit");let X=C=>_({key:z,attachmentId:F,filePath:$.filePath,fileSize:$.fileSize,box:b,owner:R,readAttachment:M,renderer:x},C),k;try{k=await m.join(z,V.signal,X)}catch(C){return a.error(`500 attachment=${F} viewer=${R} variant=thumbnail cache=miss reason=port_exception message=${C instanceof Error?C.message:"unknown"}`),P(500,Ee[500])}return A(S,k,ee,"miss")}};var Aa='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Nr=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:a,logger:l}=e,p=r.attachmentDelivery,c=hr(e.tuning,p),T={service:r,encodeUserId:n,resolveViewerScope:a,logger:l,recordObjectState:lr(r,l)},s=fr({...T,rateLimitPerMinute:c.originalRateLimitPerMinute,concurrency:c.originalConcurrency}),g=kr({...T,rateLimitPerMinute:c.thumbnailRateLimitPerMinute,concurrency:c.thumbnailConcurrency,cacheBytes:c.thumbnailCacheBytes});return async({request:m,params:_})=>{let A=null,E=(J,H,Q={})=>{let S=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...Q});return A&&S.append("Set-Cookie",A),new Response(JSON.stringify({error:{message:H}}),{status:J,headers:S})};try{let{user:J,cookie:H}=await t(m,{failureRedirect:null});if(A=H??null,!J)return E(401,"Unauthorized");let Q=sr(new URL(m.url).searchParams);if(Q.kind==="invalid")return E(400,"Invalid attachment request");if(Q.kind==="thumbnail"&&m.method!=="GET")return E(405,"Method not allowed",{Allow:"GET"});if(m.method!=="GET"&&m.method!=="HEAD")return E(405,"Method not allowed",{Allow:"GET, HEAD"});let{idCodec:S,readAttachment:L}=p;if(!(S&&L))return E(404,"Attachment not found");if(_.token===void 0)throw new Error(Aa);let V=S.decode(_.token);if(V===null||!Number.isSafeInteger(V)||V<=0)return E(400,"Invalid attachment token");let F=await r.getUserIdByExternalId(J.id);if(!F)return E(403,"Forbidden");let R={request:m,delivery:Q,attachmentId:V,internalUserId:F,readAttachment:L,cookie:A,fail:E};return Q.kind==="thumbnail"?await g(R,Q.variant):await s(R)}catch(J){if(J instanceof Response)throw J;return l.error(`500 attachment=? viewer=? reason=unexpected message=${J instanceof Error?J.message:"unknown"}`),E(500,Ne)}}};var Da=me(1,"[Response]"),pe=(e,t,r,n=200,a=Da)=>{let l=Be(r),p=e.headers.get("If-None-Match");a.info(`[jsonResponseWithETag] ETag: ${l}, If-None-Match: ${p}`);let c=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:l});return t&&c.append("Set-Cookie",t),e.method==="GET"&&n===200&&p===l?new Response(null,{status:304,headers:c}):new Response(JSON.stringify(r),{status:n,headers:c})};var Or=require("events");var De=(e,t)=>{let[r,n]=e.split("-").map(Number),[a,l]=t.split("-").map(Number);return r!==a?r<a:n<=l},$e=class{constructor(t){this.config=t;this._emitter=new Or.EventEmitter;this._state="idle";this._refCount=0;this._lastId="$";this._emitter.setMaxListeners(0),this._logger=t.logger??me(1,"[SSE Reader]")}subscribe(t,r){return this._emitter.on("entry",t),r&&this._emitter.on("error",r),this._refCount++,this._refCount===1&&this._startLoop(),()=>{this._emitter.removeListener("entry",t),r&&this._emitter.removeListener("error",r),this._refCount--,this._refCount<=0&&(this._refCount=0,this._stopLoop())}}async destroy(){this._refCount=0,await this._stopLoop(),this._emitter.removeAllListeners(),this._lastId="$"}async _startLoop(){for(;this._state==="stopping";)await new Promise(t=>setTimeout(t,50));if(this._state!=="running"&&this._refCount!==0){this._state="running";try{this._client=await this.config.redis?.createClient()}catch(t){this._state="idle",this._emitError(t instanceof Error?t:new Error("Failed to create Redis client for SSE reader"));return}if(!this._client){this._state="idle",this._emitError(new Error("Failed to create Redis client for SSE reader"));return}if(this._client.on("error",t=>{this._logger.error("Redis client error:",t)}),this._lastId==="$")try{let t=await this.config.redis?.getClient();if(t){let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});this._lastId=r.length>0?r[0].id:"0-0"}}catch(t){this._logger.warn("Failed to resolve stream tail anchor; falling back to $:",t)}try{for(;this._state==="running"&&this._client?.isOpen;){let t=await this._client.xRead([{key:this.config.streamKey,id:this._lastId}],{BLOCK:5e3,COUNT:100});if(t)for(let r of t)for(let n of r.messages){this._lastId=n.id;try{let a=n.message?.data?JSON.parse(n.message.data):null,l=a?.type;if((l==="report-create"||l==="report-delete"||l==="report-publish")&&this.config.cache.invalidatePrefix("daily-report:ids"),l==="comment-add"||l==="comment-delete"||l==="status-update"){let p=a?.reportHubId;typeof p=="number"&&(this.config.cache.invalidate(`daily-report:detail:${p}`),this.config.cache.invalidatePrefix(`daily-report:detail:${p}:user:`))}}catch{}this._emitter.emit("entry",{id:n.id,message:n.message})}}}catch(t){!(t?.constructor?.name==="ClientClosedError")&&this._state==="running"&&(this._logger.error("xRead loop error:",t),this._emitError(t instanceof Error?t:new Error(String(t))))}finally{if(this._client?.isOpen)try{await this._client.quit()}catch{}this._client=void 0,this._state="idle",this._refCount>0&&this._startLoop()}}}async _stopLoop(){if(this._state==="running"){if(this._state="stopping",this._client?.isOpen)try{await this._client.quit()}catch{}for(;this._state==="stopping";)await new Promise(t=>setTimeout(t,50))}}_emitError(t){this._emitter.listenerCount("error")>0?this._emitter.emit("error",t):this._logger.error("SSE reader error (no error listeners):",t)}};var We=require("drizzle-orm");var wa="",_a=64,Ia=e=>e.toLowerCase(),Ea=e=>e.trim().toLowerCase();function Br(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=Ea(r);n.length>0&&t.add(n)}return t}function be(e,t){return e===null?!0:t==null?!1:e.has(Ia(t))}function Ce(e){return e!==null&&e.size===0}function $r(e,t){if(t!==null)return t.size===0?We.sql`1 = 0`:(0,We.inArray)(We.sql`LOWER(${e})`,[...t])}var He,Fe,Ge=class Ge{constructor(t,r){At(this,He);At(this,Fe);Dt(this,He,t),Dt(this,Fe,r)}get visible(){return Ve(this,He)===null?null:new Set(Ve(this,He))}get commentable(){return Ve(this,Fe)===null?null:new Set(Ve(this,Fe))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Br(r?t.read:t),a=r?t.comment:void 0;if(a===void 0)return new Ge(n,n);let l=Br(a),p=new Set;for(let c of l??[])n.has(c)&&p.add(c);return new Ge(n,p)}static unrestricted(t){return new Ge(null,null)}};He=new WeakMap,Fe=new WeakMap;var ye=Ge;function Je(e){let t=Ur(e.visible),r=Ur(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Ur(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(wa);if(t.length<=_a)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 Ca=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},pt=30,Gr=4e3,xa="stream interrupted by server error",va=/^\d{4}-\d{2}-\d{2}$/,Ma=15e3,Hr=Symbol("ids-stream-heartbeat"),Fr=864e5,La={baseMs:2e3,jitterMs:8e3},qt=6e4,yt=1e3,qr=JSON.stringify({type:"connected"}),Yr="0-0",Pa=/^[0-9a-f]{1,16}$/,ka=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),a=n!==null&&Pa.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:a}:{invalid:!0};let l=Number.parseInt(t,10);return!Number.isSafeInteger(l)||String(l)!==t||l<=0?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:l},snapshot:a}:va.test(r)?{cursor:{businessDate:r,reportHubId:l},snapshot:a}:{invalid:!0}};async function*Vr(e,t,r,n){let a=t?er(e,t):0,l=!0;for(;;){let p=e.slice(a,a+(l?r:Gr));a+=p.length;let c=a>=e.length,T=p[p.length-1];if(yield{kind:"chunk",items:p,nextCursor:c||!T?null:{businessDate:T.businessDate,reportHubId:T.reportHubId},isLast:c,...l?{total:e.length}:{},...l?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...l&&n.restarted?{restarted:!0}:{}},l=!1,c)return}}var zr=(e,t,r,n)=>{let a=new TextEncoder,l=!1,p=null,c=new ReadableStream({async pull(s){if(l||r.signal.aborted){await t.return(void 0).catch(()=>{});try{s.close()}catch{}return}let g=null;try{p===null&&(p=t.next());let m=new Promise(J=>{g=setTimeout(()=>J(Hr),Ma)}),_=await Promise.race([p,m]);if(g!==null&&(clearTimeout(g),g=null),_===Hr){if(l||r.signal.aborted){await t.return(void 0).catch(()=>{});try{s.close()}catch{}return}s.enqueue(a.encode(`
|
|
2
|
-
`));return}p=null;let{value:A,done:E}=_;if(E){
|
|
3
|
-
`))}catch(m){if(g!==null&&clearTimeout(g),p=null,
|
|
4
|
-
`)),s.close()}catch{}}},cancel(){l=!0,t.return(void 0).catch(()=>{})}}),T=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&T.append("Set-Cookie",e),new Response(c,{status:200,headers:T})},Na=(e,t,r,n)=>{if(r===null&&n===null)return!0;let a=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return be(r,e.report.sourceType);case"comment-add":case"comment-delete":return be(n,a??"Internal");case"report-delete":return be(r,a)}},Oa=["externalComments","postedComments"],Ba=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||be(r,e.report.sourceType))return!1;let n=t.report;if(typeof n!="object"||n===null)return!1;let a=n;for(let l of Oa)a[l]=[];return!0};function ht(e){let{authenticate:t,service:r,encodeUserId:n,redis:a,sseReader:l,streamKey:p}=e,c=e.loginRedirectPath??"/auth/login",T=e.logger??me(3,"[DailyReportAPI]"),s=e.logger??me(3,"[DailyReportVisibility]"),g=e.logger??me(1,"[DailyReportSSE]"),m=e.logger??me(1,"[DailyReportAttachment]"),_=async(R,M="initial")=>{let I=e.resolveVisibleSourceTypes;if(!I)return ye.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let P=await I(R,{reason:M});return P==null?ye.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):ye.restrictTo(P)}catch(P){return s.error("resolveVisibleSourceTypes threw; failing closed (deny all)",P),ye.restrictTo([])}},A=async({request:R})=>{let{user:M,cookie:I}=await t(R,{failureRedirect:c}),P=new Headers;I&&P.append("Set-Cookie",I);let b=await r.getUserIdByExternalId(M.id),x=b?n(b):null;return{data:{user:M,userId:x},headers:P}},E={"business-date":async(R,M,I,P,b)=>{let x=ue(R.searchParams.get("businessDate")),q=R.searchParams.get("forceRefresh")==="true";if(!x)return pe(I,M,{error:{message:"Invalid business date"}},400);let O=await r.getDailyReportsByBusinessDateByExternalId(b,x,P.id,{forceRefresh:q});return pe(I,M,{businessDate:x,reports:O},200)},"ids-stream":async(R,M,I,P,b)=>{let x=ka(R);if("invalid"in x)return pe(I,M,{error:{message:"Invalid cursor"}},400);let q=R.searchParams.get("forceRefresh")==="true",O=!1,Y=null,v=null,$=new Promise((z,ee)=>{Y=z,v=ee});$.catch(()=>{});let ae=r.getDailyReportIdsByExternalId(b,P.id,{forceRefresh:q,onFetchStart:x.cursor?void 0:()=>{O=!0,r.readSseStreamAnchor().then(z=>r.getDailyReportIdsFirstPageByExternalId(b,P.id,pt).then(ee=>({items:ee,streamAnchor:z}))).then(z=>Y?.(z),z=>v?.(z))}});if(ae.catch(()=>{}),x.cursor){let{items:z,streamAnchor:ee}=await ae,K=wt(z),X=x.snapshot!==null&&x.snapshot===K;return zr(M,Vr(z,X?x.cursor:null,pt,{snapshot:K,restarted:!X,streamAnchor:ee}),I,T)}let j=(async function*(){let z=await Promise.race([ae.then(X=>({kind:"full",source:X}),X=>({kind:"full-error",error:X})),$.then(X=>({kind:"page",page:X}),()=>({kind:"page-error"}))]),ee=null,K=!1;if(z.kind==="full")ee=z.source;else if(z.kind==="page"){let{items:X,streamAnchor:k}=z.page;if(X.length<pt){yield{kind:"chunk",items:X,nextCursor:null,isLast:!0,total:X.length,streamAnchor:k};return}yield{kind:"chunk",items:X,nextCursor:null,isLast:!1,provisional:!0},K=!0}else if(z.kind==="full-error"&&O){let X=await $.catch(()=>null);X&&X.items.length>0&&(yield{kind:"chunk",items:X.items,nextCursor:null,isLast:!1,provisional:!0})}ee===null&&(ee=await ae),yield*Vr(ee.items,null,K?Gr:pt,{snapshot:wt(ee.items),streamAnchor:ee.streamAnchor})})();return zr(M,j,I,T)},report:async(R,M,I,P,b)=>{let x=R.searchParams.get("reportHubId"),q=R.searchParams.get("forceRefresh")==="true",O=x?Number.parseInt(x,10):NaN;if(!Number.isFinite(O)||O<=0)return pe(I,M,{error:{message:"Invalid reportHubId"}},400);let Y=await r.getDailyReportDetailByIdByExternalId(b,O,P.id,{snapshot:!0,forceRefresh:q});return Y?pe(I,M,{report:Y},200):pe(I,M,{error:{message:"Report not found"}},404)}},J=async({request:R,params:M})=>{let{user:I,cookie:P}=await t(R,{failureRedirect:null}),b=P??null;if(!I)return pe(R,b,{error:{message:"Unauthorized"}},401);if(R.method!=="GET")return pe(R,b,{error:{message:"Method not allowed"}},405);let x=M.endpoint??"",q=E[x];if(!q)return pe(R,b,{error:{message:"Unknown endpoint"}},404);let O=Date.now();try{let Y=new URL(R.url),v=await _(R);return await q(Y,b,R,I,v)}catch(Y){let v=Date.now()-O,$=Y instanceof Error?Y:new Error(String(Y));return T.error(`500 endpoint=${x} elapsed=${v}ms name=${$.name} code=${"code"in $?$.code:"N/A"} message=${$.message}`),T.error("Stack:",$.stack),pe(R,b,{error:{message:"Internal Server Error"}},500)}},H=async({request:R,params:M})=>{let{user:I,cookie:P}=await t(R,{failureRedirect:null}),b=(q,O)=>Ca(q,{...O,setCookie:P});if(!I)return b({error:"Unauthorized"},{status:401});let x=Date.now();try{if(M.endpoint!=="action")return b({error:"Unknown endpoint"},{status:404});let O=await r.getUserIdByExternalId(I.id);if(!O)return b({error:"User not found"},{status:404});let Y=await _(R),v=await R.formData(),$=v.get("intent"),ae=v.get("reportHubId"),j=ae?Number(ae):NaN,z=v.get("businessDate"),ee=Number(v.get("operationTimestamp")),K=v.get("clientTempId");if($==="clearCache")return e.enableDevCacheClear?(await r.clearCache(),b({status:"OK",intent:"clearCache"})):b({error:"Invalid intent"},{status:400});if(!K)return b({error:"clientTempId required"},{status:400});if($!=="create"&&(!j||Number.isNaN(j)))return b({error:"Invalid reportHubId"},{status:400});let X=async(k,C,te)=>{let de=v.get(C);if(de===null)return b({error:`${C} required`},{status:400});try{let ie=await te(de==="true");return b({status:"OK",intent:k,updatedStatus:{isStarred:ie.isStarred,isRead:ie.isRead},operationTimestamp:ee,reportHubId:String(j),clientTempId:K})}catch(ie){if(ie instanceof Error&&ie.message==="Not Found")return b({error:"Report not found"},{status:404});throw ie}};switch($){case"create":{if(!z)return b({error:"businessDate required"},{status:400});let k=await r.createDailyReport(O,z,K);return b({status:"OK",intent:"create",report:k,reportHubId:String(k.reportHubId),clientTempId:K})}case"update":{let k=v.get("title"),C=v.get("content");try{return await r.updateDailyReport(j,O,{title:k,content:C},K),b({status:"OK",intent:"update",reportHubId:String(j),clientTempId:K})}catch(te){if(te instanceof Error){if(te.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(te.message==="Not Found")return b({error:"Report not found"},{status:404})}throw te}}case"publish":try{let k=await r.publishDailyReport(j,O,K);return b({status:"OK",intent:"publish",reportHubId:String(j),clientTempId:K,report:k})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return b({error:"Report not found"},{status:404})}throw k}case"delete":try{return await r.deleteDailyReport(j,O,K),b({status:"OK",intent:"delete",reportHubId:String(j),clientTempId:K})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return b({error:"Report not found"},{status:404})}throw k}case"toggleStar":return await X("toggleStar","isStarred",k=>r.setStarStatus(Y,O,j,z,k,K));case"toggleRead":return await X("toggleRead","isRead",k=>r.setReadStatus(Y,O,j,z,k,K));case"addComment":{let k=v.get("content");if(!k)return b({error:"Content required"},{status:400});try{let C=await r.addComment(Y,O,j,k,z,K),te={...C,userId:C.userId};return b({status:"OK",intent:"addComment",newComment:te,reportHubId:String(j),clientTempId:K})}catch(C){if(C instanceof Error){if(C.message==="Not Found")return b({error:"Report not found"},{status:404});if(C.message.startsWith("Comments are restricted"))return b({error:"Comments are restricted for this report"},{status:403})}throw C}}case"deleteComment":{let k=Number(v.get("commentId"));if(!k||Number.isNaN(k))return b({error:"Invalid commentId"},{status:400});try{return await r.deleteComment(Y,O,j,k,z,K),b({status:"OK",reportHubId:String(j),deletedCommentId:String(k),clientTempId:K})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return b({error:"Comment not found"},{status:404})}throw C}}default:return b({error:"Invalid intent"},{status:400})}}catch(q){if(q instanceof Response)throw q;let O=Date.now()-x,Y=q instanceof Error?q:new Error(String(q));return T.error(`500 action elapsed=${O}ms name=${Y.name} message=${Y.message}`),T.error("Stack:",Y.stack),b({error:"Internal Server Error"},{status:500})}},Q=(R,M)=>{R.writeEvent({event:null,id:M,data:qr})},S=(R,M,I,P)=>{if(I.data)try{let b=JSON.parse(I.data),x=ir.safeParse(b);if(!x.success){g.error("SSE message validation failed:",x.error.format());return}let q=x.data,O=typeof b.recipientRawUserId=="number"?b.recipientRawUserId:void 0;if((q.type==="status-update"||O!==void 0)&&O!==P.internalUserId||!Na(q,b,P.visibleSet,P.commentableSet)){Q(R,M);return}let v=Ba(q,b,P.commentableSet),$;if("recipientRawUserId"in b){let{recipientRawUserId:ae,...j}=b;$=JSON.stringify(j)}else v?$=JSON.stringify(b):$=I.data;R.writeEvent({event:null,id:M,data:$})}catch(b){g.error(`[SSE:${P.internalUserId}] processEntry error:`,b)}},L=async(R,M)=>{let{request:I,internalUserId:P,cursor:b}=M,x=M.initialScope.visible,q=M.initialScope.commentable,O=0,Y=setInterval(()=>{let C=++O;_(I,"refresh").then(te=>{C===O&&(x=te.visible,q=te.commentable)})},qt);R.onClose(()=>clearInterval(Y));let v=b===null?Yr:b,$=b!==null&&a!==void 0,ae=[],j=null,z=C=>{De(C.id,v)||(v=C.id,S(R,C.id,C.message,{internalUserId:P,visibleSet:x,commentableSet:q}))},ee=async(C,te)=>{let[de]=await C.xRange(p,"-","+",{COUNT:1});return de!==void 0&&!De(de.id,te)},K=async(C,te)=>{if(await ee(C,te))return!1;let de=te;for(;;){let ie=await C.xRange(p,de,"+",{COUNT:yt}),ve=ie[0];if(ve!==void 0&&ve.id!==de&&await ee(C,de))return!1;for(let Xe of ie){if(j!==null&&De(j,Xe.id))return!0;z(Xe)}let Qe=ie.at(-1);if(ie.length<yt||Qe===void 0||R.isClosed())return!0;de=Qe.id}},X=l.subscribe(C=>{if(!$){z(C);return}De(C.id,v)||(j===null&&(j=C.id),ae.push(C))},C=>{g.error(`[SSE:${P}] Fan-Out reader error:`,C),R.close()});if(R.onClose(X),b===null)try{let C=await a?.getClient();if(C){let te=await C.xRevRange(p,"+","-",{COUNT:1});te.length>0&&!De(te[0].id,v)&&(v=te[0].id)}}catch{}if(R.writeEvent({event:null,id:v===Yr?null:v,data:qr}),(0,we.startSseHeartbeat)(R,{intervalMs:tr,retry:La,runtime:jr.systemSseRuntime}),b===null||a===void 0)return;let k=await a.getClient();if(k===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await K(k,b)){R.writeRetry(Fr),R.writeEvent({event:"resync-required",id:null,data:""}),R.close();return}$=!1;for(let C of ae.splice(0))z(C)},V=async({request:R,params:M})=>{let I,P=()=>{let x=new Headers;return I!==void 0&&x.append("Set-Cookie",I),x},b=x=>(0,we.terminalStreamResponse)(x,{data:"",retryMs:Fr,headers:P()});try{let x=await t(R,{failureRedirect:null});I=x.cookie;let{user:q}=x;if(!q)return b("auth-required");let O=await r.getUserIdByExternalId(q.id);if(!O)return b("forbidden");if(M.endpoint!=="updates")return new Response("Not Found",{status:404,headers:P()});let Y=(0,we.readLastEventId)(R,rr);if(Y!==null&&!nr(Y))return g.warn(`[SSE:${O}] malformed resume cursor; asking the client to resync`),b("resync-required");let v=await _(R);return(0,we.createSseResponse)({requestSignal:R.signal,headers:P(),onError:($,ae)=>g.error(`[SSE:${O}] ${ae} failed:`,$),produce:$=>L($,{request:R,internalUserId:O,cursor:Y,initialScope:v})})}catch(x){if(x instanceof Response)throw x;let q=x instanceof Error?x:new Error(String(x));return g.error(`500 sse name=${q.name} message=${q.message}`),new Response("Internal Server Error",{status:500,headers:P()})}},F=Nr({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:_,logger:m,tuning:e});return{index:{loader:A},api:{loader:J,action:H},sse:{loader:V},attachment:{loader:F}}}var Wr=require("@aiquants/mssql"),u=require("drizzle-orm");var xe=e=>(0,u.getColumns)(e),Ua=e=>{if(e!==void 0){if(typeof e!="object"||e===null)throw Oe("attachmentThumbnailRenderer","an object with id and render",e);if(e.render===void 0)throw ut("attachmentThumbnailRenderer.render","a function");if(typeof e.render!="function")throw Oe("attachmentThumbnailRenderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Oe("attachmentThumbnailRenderer.id","a non-blank string naming the rendering pipeline version",e.id);return e}},ce=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),a=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),l=String(r.getMonth()+1).padStart(2,"0"),p=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${a}-${l}-${p}`;let c=String(r.getHours()).padStart(2,"0"),T=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${a}-${l}-${p} ${c}:${T}:${s}`};function ft(e){let{db:t,tables:r,userTable:n,resolveUserId:a,encodeUserId:l,redis:p,cache:c,epochs:T}=e,{hub:s,internal:g,comment:m,label:_,hubLabel:A,userStatus:E}=r,J=e.externalSources??[],H=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],Q=H[0]??"\u4E0B\u66F8\u304D",S=e.logger??me(1,"[DailyReportService]");Nt({attachmentIdCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,attachmentThumbnailRenderer:e.attachmentThumbnailRenderer,attachmentMaxBytes:e.attachmentMaxBytes});let L=Object.freeze({idCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,thumbnailRenderer:Ua(e.attachmentThumbnailRenderer),maxBytes:Ie("attachmentMaxBytes",e.attachmentMaxBytes,1,yr)}),V=i=>(0,Wr.runWithTransactionRetry)(o=>t.transaction(d=>o(()=>i(d))),e.transactionRetry),F="daily-report:ids",R=e.idsTtlMs??18e4,M="daily-report:ids:epoch",I="daily-report:business-date:",P=e.businessDateTtlMs??3e5,b="daily-report:date-epoch:",x="daily-report:detail-epoch:",O=`${e.streamKey??"daily-report:sse-stream"}:v2`,Y=e.streamMaxLen??1e4,v=i=>T.incrementEpoch(i),$=i=>$r(s.sourceType,i),ae=(i,o)=>`${F}:user:${i}:st:${o}`,j=i=>`${F}:user:${i}:`,z=(i,o,d)=>`daily-report:date:${i}:user:${o}:st:${d}`,ee=(i,o)=>`daily-report:date:${i}:user:${o}:`,K=(i,o,d)=>`daily-report:detail:${i}:user:${o}:st:${d}`,X=(i,o)=>`daily-report:detail:${i}:user:${o}:`,k=async(i,o)=>{let d=await p?.getClient();if(!d){S.warn(`[SSE] Redis client unavailable (${o})`);return}let h=Date.now();try{await d.xAdd(O,"*",{data:JSON.stringify(i)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Y}});let D=Date.now()-h;D>1e3&&S.warn(`[SSE] Slow publish (${o}): ${D}ms`)}catch(D){S.error(`[SSE] Redis publish failed (${o}):`,D)}},C=async()=>{try{let i=await p?.getClient();if(i===void 0)return null;let[o]=await i.xRevRange(O,"+","-",{COUNT:1});return o===void 0?null:o.id}catch(i){return S.error("[DailyReportService] SSE stream anchor read failed",i),null}},te=i=>i==null||i===""?null:/^\d+$/.test(i)?l(Number(i)):i,de=()=>{let i={};for(let o of J)i[`ext_${o.sourceType}`]=xe(o.table);return i},ie=i=>{let o=i;for(let d of J)o=o.leftJoin(d.table,(0,u.and)((0,u.eq)(s.sourceType,d.sourceType),(0,u.eq)(s.sourceIdNum,d.idColumn)));return o},ve=(i,o,d)=>{let{hub:h,internal:D}=o,B=h.summary,w=[],N=null,U=null,Z=null,G=null,re=null,oe=null,Le=[],Te=J.find(W=>W.sourceType===h.sourceType),Pe=Te?o[`ext_${Te.sourceType}`]:void 0;if(Te&&Pe){let W=Te.mapRow(Pe);W.content!==void 0&&(B=W.content),W.employeeName!==void 0&&(oe=W.employeeName),W.category!==void 0&&(N=W.category),W.creationCategory!==void 0&&(U=W.creationCategory),W.visitTimeFrom!==void 0&&(Z=W.visitTimeFrom),W.visitTimeTo!==void 0&&(G=W.visitTimeTo),W.customerName!==void 0&&(re=W.customerName),W.interviewers!==void 0&&(w=W.interviewers),W.externalComments!==void 0&&(Le=W.externalComments)}else h.sourceType==="Internal"&&D&&(B=D.body);let ge=(o.labels??[]).map(W=>({id:W.id,name:W.name,color:W.color})),se=o.postedCommentRows??[],ne=be(i.commentable,h.sourceType),le=U?H.includes(U):!1,St=Me?.[0]??null;return le&&St&&!ge.some(W=>W.id===St)&&ge.push({id:St,name:Q,color:null}),{reportHubId:h.id,date:ce(h.businessDate,"YYYY-MM-DD"),author:o.creatorName??te(h.createdBy)??"",userId:h.userId?l(h.userId):"",sourceType:h.sourceType??"Internal",createdAt:ce(h.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:ce(h.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:te(h.updatedBy),employeeName:oe??o.creatorName??te(h.createdBy),category:N,creationCategory:U,visitTimeFrom:Z,visitTimeTo:G,customerName:re,interviewers:w,subject:h.title,content:B,externalComments:ne?Le:[],isRead:o.isRead??!1,isStarred:o.isStarred??!1,labels:ge,postedComments:se.filter(W=>ne||d!==void 0&&W.userId===d).map(W=>({...W,userId:l(W.userId),isMine:d?W.userId===d:!1})),attachments:o.attachments}},Qe=async(i,o)=>{let d=(0,u.aliasedTable)(A,"draft_label"),h=await _e();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(d,(0,u.and)((0,u.eq)(d.hubId,s.id),(0,u.inArray)(d.labelId,h))).where((0,u.and)((0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,o),(0,u.isNull)(s.userId),(0,u.isNull)(d.hubId)),$(i.visible))).orderBy((0,u.desc)(s.businessDate),(0,u.desc)(s.id))).map(B=>({...B,businessDate:ce(B.businessDate,"YYYY-MM-DD")}))},Xe=async(i,o,d)=>{let h=await qe(o);if(!h)return[];if(Ce(i.visible))return[];let D=(0,u.aliasedTable)(A,"draft_label"),B=await _e();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(d).from(s).leftJoin(D,(0,u.and)((0,u.eq)(D.hubId,s.id),(0,u.inArray)(D.labelId,B))).where((0,u.and)((0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,h),(0,u.isNull)(s.userId),(0,u.isNull)(D.hubId)),$(i.visible))).orderBy((0,u.desc)(s.businessDate),(0,u.desc)(s.id))).map(N=>({...N,businessDate:ce(N.businessDate,"YYYY-MM-DD")}))},on=async(i,o)=>{let d=await ie(t.select({hub:xe(s),internal:xe(g),creatorName:n.displayName,...de()}).from(s)).leftJoin(g,(0,u.eq)(s.id,g.hubId)).leftJoin(n,(0,u.eq)(s.userId,n.id)).where((0,u.and)((0,u.eq)(s.businessDate,u.sql`${o}`),(0,u.isNull)(s.deletedAt),$(i.visible))).orderBy((0,u.desc)(s.id)),h=await tt(d.map(D=>D.hub.id));return d.map(D=>ve(i,{...D,attachments:h.get(D.hub.id)??[]}))},sn=i=>`${I}${i}`,Ze=new Map,qe=async i=>{if(!e.disableUserIdCache&&Ze.has(i))return Ze.get(i)??null;let o=await a(i);return o!==null&&!e.disableUserIdCache&&Ze.set(i,o),o},ln=async(i,o,{forceRefresh:d=!1,snapshot:h=!1,ttlMsOverride:D,onFetchStart:B}={})=>{let w=await qe(o);if(!w)return{items:[],streamAnchor:null};if(Ce(i.visible))return{items:[],streamAnchor:await C()};let N=ae(w,Je(i)),[U]=await c.getOrFetch({cacheKey:N,fetcher:async()=>{let Z=await C(),G=await Qe(i,w);return Zt(G)?[{items:G,streamAnchor:Z}]:(S.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)"),[{items:[...G].sort(at),streamAnchor:Z}])},onFetchStart:B,forceRefresh:d,snapshot:h,ttlMsOverride:D??R,epochKey:M,refreshAheadRatio:.5});if(U===void 0)throw new Error("[DailyReportService] ids cache returned no record");return U},un=(i,o,{forceRefresh:d=!1,snapshot:h=!1,ttlMsOverride:D}={})=>{let B=ue(o);return B?Ce(i.visible)?Promise.resolve([]):c.getOrFetch({cacheKey:`${sn(B)}:st:${Je(i)}`,fetcher:()=>on(i,B),forceRefresh:d,snapshot:h,ttlMsOverride:D??P}):Promise.resolve([])},Me=null,et=async()=>(Me!==null||(Me=(await t.select({id:_.id}).from(_).where((0,u.inArray)(_.name,H)).orderBy(_.id)).map(o=>o.id)),Me),_e=async()=>{let i=await et();return i.length>0?i:[-1]},bt=async()=>{let i=await et();if(i.length===0)return null;let[o]=await t.select({id:_.id}).top(1).from(_).where((0,u.eq)(_.name,Q));return o?.id??i[0]},cn=(i,o)=>o!=null?"absent":i!=null?"present":"unknown",tt=async i=>{let o=new Map,d=r.attachment,h=L.idCodec;if(i.length===0||!d||!h)return o;let D=L.thumbnailRenderer!==void 0&&L.readAttachment!==void 0,B=await t.select({id:d.id,hubId:d.hubId,fileName:d.fileName,fileType:d.fileType,fileSize:d.fileSize,createdAt:d.createdAt,objectCheckedAt:d.objectCheckedAt,objectMissingAt:d.objectMissingAt}).from(d).where((0,u.inArray)(d.hubId,i)).orderBy((0,u.asc)(d.createdAt),(0,u.asc)(d.id));for(let w of B){let N=w.fileType?String(w.fileType):null,U=w.fileSize!=null?Number(w.fileSize):null,Z=cn(w.objectCheckedAt,w.objectMissingAt),G={id:h.encode(Number(w.id)),fileName:String(w.fileName),fileType:N,fileSize:U,createdAt:ce(w.createdAt,"YYYY-MM-DD HH:mm:ss"),state:Z,hasThumbnail:D&&Z!=="absent"&&dt({fileType:N,fileSize:U},L.maxBytes)},re=o.get(Number(w.hubId));re?re.push(G):o.set(Number(w.hubId),[G])}return o},dn=async(i,o,d)=>{let h=r.attachment;if(!h||Ce(i.visible))return null;let D=await _e(),B=(0,u.aliasedTable)(A,"draft_label");return(await t.select({fileName:h.fileName,filePath:h.filePath,fileType:h.fileType,fileSize:h.fileSize}).top(1).from(h).innerJoin(s,(0,u.eq)(s.id,h.hubId)).leftJoin(B,(0,u.and)((0,u.eq)(B.hubId,s.id),(0,u.inArray)(B.labelId,D))).where((0,u.and)((0,u.eq)(h.id,o),(0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,d),(0,u.isNull)(B.hubId)),$(i.visible))))[0]??null},mn=async i=>{let o=r.attachment;if(!o)return;let d=new Date;try{await t.update(o).set({objectCheckedAt:d,objectMissingAt:d,updatedAt:d}).where((0,u.eq)(o.id,i))}catch(h){S.error("markAttachmentMissing failed",h)}},pn=async i=>{let o=r.attachment;if(!o)return;let d=new Date;try{await t.update(o).set({objectCheckedAt:d,objectMissingAt:null,updatedAt:d}).where((0,u.eq)(o.id,i))}catch(h){S.error("markAttachmentPresent failed",h)}},yn=async(i,o,d,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:B}={})=>{let w=await qe(d);if(!w)return[];let N=ue(o);if(!N)return[];if(Ce(i.visible))return[];let U=z(N,w,Je(i));return c.getOrFetch({cacheKey:U,fetcher:async()=>{let Z=await _e(),G=(0,u.aliasedTable)(A,"draft_label"),re=await ie(t.select({hub:xe(s),internal:xe(g),isRead:E.isRead,isStarred:E.isStarred,creatorName:n.displayName,...de()}).from(s)).leftJoin(g,(0,u.eq)(s.id,g.hubId)).leftJoin(E,(0,u.and)((0,u.eq)(s.id,E.hubId),(0,u.eq)(E.userId,w))).leftJoin(G,(0,u.and)((0,u.eq)(G.hubId,s.id),(0,u.inArray)(G.labelId,Z))).leftJoin(n,(0,u.eq)(s.userId,n.id)).where((0,u.and)((0,u.eq)(s.businessDate,u.sql`${N}`),(0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,w),(0,u.isNull)(G.hubId)),$(i.visible))).orderBy((0,u.desc)(s.id));if(re.length===0)return[];let oe=re.map(ne=>ne.hub.id),Le=await t.select({hubId:A.hubId,id:_.id,name:_.name,color:_.color}).from(A).innerJoin(_,(0,u.eq)(A.labelId,_.id)).where((0,u.inArray)(A.hubId,oe)),Te=await t.select({hubId:m.hubId,id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,u.eq)(m.userId,n.id)).where((0,u.inArray)(m.hubId,oe)).orderBy((0,u.asc)(m.createdAt)),Pe=await tt(oe),ge=new Map,se=new Map;for(let ne of Le){let le=ge.get(ne.hubId);le||(le=[],ge.set(ne.hubId,le)),le.push({id:ne.id,name:ne.name,color:ne.color})}for(let ne of Te){let le=se.get(ne.hubId);le||(le=[],se.set(ne.hubId,le)),le.push({id:ne.id,content:ne.body,createdAt:ce(ne.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ne.userId,userName:ne.userName||""})}return re.map(ne=>{let le=ne.hub.id;return ve(i,{...ne,attachments:Pe.get(le)??[],labels:ge.get(le)||[],postedCommentRows:se.get(le)||[]},w)})},forceRefresh:h,snapshot:D,ttlMsOverride:B??P,epochKey:`${b}${N}`})},Ye=async(i,o,d,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:B}={})=>{if(Ce(i.visible))return null;let w=K(o,d,Je(i));return(await c.getOrFetch({cacheKey:w,fetcher:async()=>{let U=await _e(),Z=(0,u.aliasedTable)(A,"draft_label"),G=await ie(t.select({hub:xe(s),internal:xe(g),isRead:E.isRead,isStarred:E.isStarred,creatorName:n.displayName,...de()}).from(s)).leftJoin(g,(0,u.eq)(s.id,g.hubId)).leftJoin(E,(0,u.and)((0,u.eq)(s.id,E.hubId),(0,u.eq)(E.userId,d))).leftJoin(Z,(0,u.and)((0,u.eq)(Z.hubId,s.id),(0,u.inArray)(Z.labelId,U))).leftJoin(n,(0,u.eq)(s.userId,n.id)).where((0,u.and)((0,u.eq)(s.id,o),(0,u.isNull)(s.deletedAt),(0,u.or)((0,u.eq)(s.userId,d),(0,u.isNull)(Z.hubId)),$(i.visible)));if(G.length===0)return[];let re=G[0].hub.id,oe=await t.select({id:_.id,name:_.name,color:_.color}).from(A).innerJoin(_,(0,u.eq)(A.labelId,_.id)).where((0,u.eq)(A.hubId,re)),Le=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,u.eq)(m.userId,n.id)).where((0,u.eq)(m.hubId,re)).orderBy((0,u.asc)(m.createdAt)),Te=await tt([re]),Pe=oe.map(se=>({id:se.id,name:se.name,color:se.color})),ge=Le.map(se=>({id:se.id,content:se.body,createdAt:ce(se.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:se.userId,userName:se.userName||""}));return[ve(i,{...G[0],attachments:Te.get(re)??[],labels:Pe,postedCommentRows:ge},d)]},forceRefresh:h,snapshot:D,ttlMsOverride:B??P,epochKey:`${x}${o}`}))[0]??null},hn=async(i,o,d,h={})=>{let D=await qe(d);return D?Ye(i,o,D,h):null},fn=async(i,o)=>{let d=await _e(),h=(0,u.aliasedTable)(A,"draft_label"),[D]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(h,(0,u.and)((0,u.eq)(h.hubId,s.id),(0,u.inArray)(h.labelId,d))).where((0,u.and)((0,u.eq)(s.id,i),(0,u.or)((0,u.eq)(s.userId,o),(0,u.isNull)(h.hubId))));return D??null},gt=async(i,o,d)=>{let h=await fn(o,d);if(!h||h.deletedAt||!be(i.visible,h.sourceType))throw new Error("Not Found")},bn=async(i,o,d,h,D,B)=>{await gt(i,d,o);let w=await t.select().top(1).from(E).where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,o))),N;if(w.length>0?w[0].isStarred!==D?N=(await t.update(E).set({isStarred:D,updatedAt:new Date,updatedBy:String(o)}).output().where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,o))))[0]:N=w[0]:N=(await t.insert(E).output().values({hubId:d,userId:o,isStarred:D,isRead:!1,createdAt:new Date,createdBy:String(o),updatedAt:new Date,updatedBy:String(o)}))[0],h){let U=ue(h);U&&(c.invalidatePrefix(ee(U,o)),await v(`${b}${U}`))}return c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(X(d,o)),await v(`${x}${d}`),await k(it.parse({type:"status-update",reportHubId:d,recipientRawUserId:o,statusType:"star",value:D,clientTempId:B}),"setStarStatus"),N},gn=async(i,o,d,h,D,B)=>{await gt(i,d,o);let w=await t.select().top(1).from(E).where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,o))),N;if(w.length>0?w[0].isRead!==D?N=(await t.update(E).set({isRead:D,updatedAt:new Date,updatedBy:String(o)}).output().where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,o))))[0]:N=w[0]:N=(await t.insert(E).output().values({hubId:d,userId:o,isRead:D,isStarred:!1,createdAt:new Date,createdBy:String(o),updatedAt:new Date,updatedBy:String(o)}))[0],h){let U=ue(h);U&&(c.invalidatePrefix(ee(U,o)),await v(`${b}${U}`))}return c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(X(d,o)),await v(`${x}${d}`),await k(it.parse({type:"status-update",reportHubId:d,recipientRawUserId:o,statusType:"read",value:D,clientTempId:B}),"setReadStatus"),N},jt=async(i,o)=>{if(o===null)return;let d=await _e(),[h]=await t.select({hubId:A.hubId}).top(1).from(A).where((0,u.and)((0,u.eq)(A.hubId,i),(0,u.inArray)(A.labelId,d)));return h?o:void 0},Rn=async(i,o,d,h,D,B)=>{let[w]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where((0,u.eq)(s.id,d));if(!w||w.deletedAt)throw new Error("Not Found");if(await gt(i,d,o),!be(i.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 N=await jt(d,w.userId),[U]=await t.insert(m).output().values({hubId:d,userId:o,body:h,createdAt:new Date,createdBy:String(o),updatedAt:new Date,updatedBy:String(o)}),[Z]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,u.eq)(n.id,o)),G=Z?.displayName??"";if(D){let oe=ue(D);oe&&(c.invalidatePrefix(`daily-report:date:${oe}:user:`),await v(`${b}${oe}`))}c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(`daily-report:detail:${d}:user:`),await v(`${x}${d}`);let re={id:U.id,userId:l(U.userId),userName:G,content:U.body,createdAt:ce(U.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await k(Et.parse({type:"comment-add",reportHubId:d,comment:re,clientTempId:B,recipientRawUserId:N,sourceType:w.sourceType}),"addComment"),re},Sn=async(i,o)=>await i.select().top(1).from(m).where((0,u.eq)(m.id,o)),Tn=async(i,o,d,h,D,B)=>{let w=await Sn(t,h);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==d)throw new Error("Not Found");let[N]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where((0,u.eq)(s.id,w[0].hubId));if(!(N&&be(i.visible,N.sourceType)))throw new Error("Not Found");if(w[0].userId!==o)throw new Error("Unauthorized");let U=await jt(d,N.userId);if(await t.delete(m).where((0,u.eq)(m.id,h)),D){let Z=ue(D);Z&&(c.invalidatePrefix(`daily-report:date:${Z}:user:`),await v(`${b}${Z}`))}c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(`daily-report:detail:${d}:user:`),await v(`${x}${d}`),await k(Ct.parse({type:"comment-delete",reportHubId:d,commentId:h,clientTempId:B,recipientRawUserId:U,sourceType:N?.sourceType}),"deleteComment")},An=async(i,o,d)=>{S.info("createDailyReport called",{userId:i,businessDate:o});let[h]=await t.select({displayName:n.displayName}).from(n).where((0,u.eq)(n.id,i)),D=h?.displayName??l(i);try{let B=await V(async U=>{S.info("Starting transaction");let Z=`internal-temp-${Date.now()}-${Math.random()}`,[G]=await U.insert(s).output().values({sourceType:"Internal",sourceId:Z,businessDate:new Date(o),userId:i,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)});await U.update(s).set({sourceId:String(G.id)}).where((0,u.eq)(s.id,G.id)),S.info("Hub created",G),await U.insert(g).values({hubId:G.id,body:"",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)}),S.info("Internal created"),S.info("Calling getDraftLabelId");let re=await bt();S.info("draftLabelId",re);let oe=[];return re&&(await U.insert(A).values({hubId:G.id,labelId:re,createdAt:new Date,createdBy:String(i)}),oe.push({id:re,name:Q,color:null})),S.info("Label assigned"),{reportHubId:G.id,date:o,createdAt:ce(G.createdAt,"YYYY-MM-DD HH:mm:ss"),author:D,userId:l(i),sourceType:"Internal",employeeName:D,updatedBy:l(i),updatedAt:ce(G.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:G.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:oe,postedComments:[],attachments:[]}}),w=ue(o);w&&c.invalidatePrefix(ee(w,i)),c.invalidatePrefix(I),c.invalidatePrefix(j(i)),await v(M),w&&await v(`${b}${w}`);let N=await Ye(ye.unrestricted("post-write self read: the writer always sees the row they just wrote"),B.reportHubId,i,{forceRefresh:!0});if(N){let U=await et(),Z=N.labels.some(G=>U.includes(G.id));await k(xt.parse({type:"report-create",reportHubId:N.reportHubId,report:N,clientTempId:d,recipientRawUserId:Z?i:void 0}),"createDailyReport")}return N??B}catch(B){throw S.error("Error in createDailyReport",B),B}},rt=async(i,o)=>await i.select().top(1).from(s).where((0,u.eq)(s.id,o)),Rt=async(i,o,d)=>{await i.update(s).set(d).where((0,u.eq)(s.id,o))},Gt=async(i,o,d)=>{await i.update(g).set(d).where((0,u.eq)(g.hubId,o))},Wt=async(i,o,d)=>{await i.delete(A).where((0,u.and)((0,u.eq)(A.hubId,o),(0,u.eq)(A.labelId,d)))};return{streamKey:O,streamMaxLen:Y,attachmentDelivery:L,clearCache:async()=>{c.clearAll(),Ze.clear(),Me=null,T&&await v(M),S.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(i,o)=>{c.invalidatePrefix(I),c.invalidatePrefix(F),await v(M);for(let d of new Set(i))c.invalidatePrefix(`daily-report:detail:${d}:user:`),await v(`${x}${d}`);for(let d of new Set(o)){let h=ue(d);h&&await v(`${b}${h}`)}},getUserIdByExternalId:qe,getDailyReportIdsByExternalId:ln,getDailyReportIdsFirstPageByExternalId:Xe,readSseStreamAnchor:C,getDailyReportsByBusinessDate:un,getDailyReportsByBusinessDateByExternalId:yn,getDailyReportDetailById:Ye,getDailyReportDetailByIdByExternalId:hn,getDraftLabelId:bt,getAttachmentsByHubIds:tt,getAttachmentForUser:dn,markAttachmentMissing:mn,markAttachmentPresent:pn,setStarStatus:bn,setReadStatus:gn,addComment:Rn,deleteComment:Tn,createDailyReport:An,updateDailyReport:async(i,o,d,h)=>{let D=await rt(t,i);if(!D.length||D[0].deletedAt)throw new Error("Not Found");if(D[0].userId!==o)throw new Error("Unauthorized");await V(async N=>{d.title!==void 0&&await Rt(N,i,{title:d.title,updatedAt:new Date,updatedBy:String(o)}),d.content!==void 0&&await Gt(N,i,{body:d.content,updatedAt:new Date,updatedBy:String(o)})}),c.invalidate(`daily-report:detail:${i}`),c.invalidatePrefix(`daily-report:detail:${i}:user:`),c.invalidatePrefix(I),await v(`${x}${i}`);let B=ue(ce(D[0].businessDate,"YYYY-MM-DD"));B&&(c.invalidatePrefix(`daily-report:date:${B}:user:`),await v(`${b}${B}`));let w=await Ye(ye.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,o,{forceRefresh:!0});if(w){let N=await et(),U=w.labels.some(Z=>N.includes(Z.id));await k(vt.parse({type:"report-update",reportHubId:w.reportHubId,report:w,clientTempId:h,recipientRawUserId:U?o:void 0}),"updateDailyReport")}},publishDailyReport:async(i,o,d)=>{let h=await rt(t,i);if(!h.length)throw new Error("Not Found");if(h[0].userId!==o)throw new Error("Unauthorized");let D=await bt();if(!D)return null;if(await Wt(t,i,D),c.invalidatePrefix(`daily-report:detail:${i}:user:`),c.invalidatePrefix(I),c.invalidatePrefix(F),await v(M),h[0].businessDate){let N=ue(ce(h[0].businessDate,"YYYY-MM-DD"));N&&await v(`${b}${N}`)}let B=ue(ce(h[0].businessDate,"YYYY-MM-DD"));B&&c.invalidatePrefix(ee(B,o));let w=await Ye(ye.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,o,{forceRefresh:!0});return w&&await k(Mt.parse({type:"report-publish",reportHubId:w.reportHubId,report:w,clientTempId:d}),"publishDailyReport"),w??null},deleteDailyReport:async(i,o,d)=>{let h=await rt(t,i);if(!h.length||h[0].deletedAt)throw new Error("Not Found");if(h[0].userId!==o)throw new Error("Unauthorized");if(await Rt(t,i,{deletedAt:new Date,deletedBy:String(o),updatedAt:new Date,updatedBy:String(o)}),c.invalidatePrefix(`daily-report:detail:${i}:user:`),c.invalidatePrefix(I),c.invalidatePrefix(F),await v(M),h[0].businessDate){let D=ue(ce(h[0].businessDate,"YYYY-MM-DD"));D&&await v(`${b}${D}`)}await k(Lt.parse({type:"report-delete",reportHubId:i,clientTempId:d,sourceType:h[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:rt,updateDailyReportHub:Rt,updateDailyReportInternal:Gt,deleteDailyReportLabel:Wt}}var $a=me(1,"[DailyReportExternalSource]"),Jr=(e,t,r,n=$a)=>{if(!e)return[];try{let a=JSON.parse(e);return Array.isArray(a)?a.map(r).filter(l=>l!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(a){return n.warn(`Failed to parse ${t}:`,a),[]}};var Ke=require("drizzle-orm"),y=require("drizzle-orm/mssql-core");function Kr(e,t){let r=(0,y.mssqlSchema)(e),n=t.userTable,a=r.table("DailyReportHub",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,y.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,y.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,y.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(Ke.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,y.date)("business_date"),userId:(0,y.bigint)("user_id",{mode:"number"}),title:(0,y.nvarchar)("title",{length:200}),summary:(0,y.nvarchar)("summary",{length:"max"}),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,y.datetime2)("deleted_at"),deletedBy:(0,y.nvarchar)("deleted_by",{length:50})},m=>[(0,y.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,y.index)(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),(0,y.index)(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),(0,y.index)(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),(0,y.index)(`${e}_DailyReportHub_user_id_index`).on(m.userId),(0,y.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,Ke.desc)(m.businessDate),(0,Ke.desc)(m.id)),(0,y.index)(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),l=r.table("DailyReportInternal",{hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,y.nvarchar)("body",{length:"max"}),metadata:(0,y.nvarchar)("metadata",{length:"max"}),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),(0,y.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]})]),p=r.table("DailyReportComment",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,y.bigint)("user_id",{mode:"number"}).notNull(),body:(0,y.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,y.index)(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),c=r.table("DailyReportLabel",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,y.bigint)("user_id",{mode:"number"}),name:(0,y.nvarchar)("name",{length:50}).notNull(),color:(0,y.nvarchar)("color",{length:20}),sortOrder:(0,y.int)("sort_order"),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),T=r.table("DailyReportHub_Label",{hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,y.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),(0,y.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[c.id]})]),s=r.table("DailyReportUserStatus",{hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,y.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,y.bit)("is_read").default(!1).notNull(),isStarred:(0,y.bit)("is_starred").default(!1).notNull(),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),(0,y.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),g=r.table("DailyReportAttachment",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,y.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,y.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,y.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,y.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,y.nvarchar)("file_type",{length:100}),fileSize:(0,y.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,y.datetime2)("object_checked_at"),objectMissingAt:(0,y.datetime2)("object_missing_at"),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),(0,y.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),(0,y.index)(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:a,internal:l,comment:p,attachment:g,label:c,hubLabel:T,userStatus:s}}var Ha=5e7,Vt=2e8,Fa=1,zt=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),qa=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Qr=75,Xr=4,Zr="#ffffff",Ya=1,Va={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},za=[/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/],Yt=Object.freeze({ok:!1,reason:"failed"}),en=Object.freeze({ok:!1,reason:"unsupported"}),tn=(e,t)=>{switch(t){case"jpeg":{let r=Bt(e);return r===null?null:{layout:r.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Tr(r)}}case"png":{let r=Dr(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=wr(e);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},rn=(e,t)=>{let r=qa.get(t.depth);if(r===void 0)return null;let n=t.channels*r,a=zt,l=a.wholeImageBuffer[e.layout];return(l.kind==="none"?0:l.kind==="decoded-raster"?t.width*t.height*n:l.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*l.bytesPerPixel)+a.pipelineRows*t.width*n+a.fixedBytes},nn=(e,t,r)=>{let n=tn(e,t);return n===null?null:rn(n,r)},ja=e=>e!==null&&e<=Vt,Ga=e=>{let t=e instanceof Error?e.message:"";return za.some(r=>r.test(t))?"failed":"unsupported"},an=e=>{e.cache(!1),e.concurrency(Fa),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Va)});let t=async(n,a,l,p,c)=>{let T=tn(n,a);if(T===null)return en;try{let s=e(n,{limitInputPixels:Ha,animated:!1});if(!ja(rn(T,await s.metadata())))return en;if(c.aborted)return Yt;let g=await s.rotate().resize({width:l,height:p,fit:"inside",withoutEnlargement:!0}).flatten({background:Zr}).webp({quality:Qr,effort:Xr}).toBuffer();return{ok:!0,bytes:new Uint8Array(g),contentType:"image/webp"}}catch(s){return{ok:!1,reason:Ga(s)}}},r=async(n,{format:a,maxWidth:l,maxHeight:p,signal:c})=>{if(c.aborted)return Yt;let T=await t(n,a,l,p,c);return c.aborted?Yt:T};return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Qr}-e${Xr}/flatten-${Zr}/v${Ya}`,render:r}};function Wa(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=nt(e.redis),r=new ke({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=ft({...e,cache:r,epochs:t}),a=new $e({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),l=ht({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes,redis:e.redis,sseReader:a,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:a,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(p=>p.sourceType)])],...l}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,generateETag,isStreamIdLte,jsonResponseWithETag,predictSharpThumbnailWorkingSetBytes,transformJsonArray});
|
|
1
|
+
"use strict";var At=Object.defineProperty;var _n=Object.getOwnPropertyDescriptor;var In=Object.getOwnPropertyNames;var En=Object.prototype.hasOwnProperty;var Kt=e=>{throw TypeError(e)};var Cn=(e,t)=>{for(var r in t)At(e,r,{get:t[r],enumerable:!0})},xn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of In(t))!En.call(e,a)&&a!==r&&At(e,a,{get:()=>t[a],enumerable:!(n=_n(t,a))||n.enumerable});return e};var vn=e=>xn(At({},"__esModule",{value:!0}),e);var Qt=(e,t,r)=>t.has(e)||Kt("Cannot "+r);var Ve=(e,t,r)=>(Qt(e,t,"read from private field"),r?r.call(e):t.get(e)),Dt=(e,t,r)=>t.has(e)?Kt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),wt=(e,t,r,n)=>(Qt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Za={};Cn(Za,{DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES:()=>Ht,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES:()=>$t,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES:()=>zt,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL:()=>jt,DAILY_REPORT_SSE_CATCH_UP_BATCH:()=>ht,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS:()=>Yt,DailyReportSseReader:()=>$e,DailyReportViewerScope:()=>ye,SqlResultCache:()=>ke,createDailyReportHandlers:()=>ft,createDailyReportServer:()=>Xa,createDailyReportService:()=>bt,createEpochStore:()=>nt,createSharpThumbnailRenderer:()=>sn,defineDailyReportSchema:()=>Xr,generateETag:()=>Be,isStreamIdLte:()=>De,jsonResponseWithETag:()=>pe,predictSharpThumbnailWorkingSetBytes:()=>on,transformJsonArray:()=>Qr});module.exports=vn(Za);var nt=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{}}}),ke=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.invalidate=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,a=this.buckets.get(n);if(!a)return;let o=t.ttlMsOverride??this.config.defaultTtlMs;if(o-(a.expireAt-Date.now())<o*r||this.inFlight.has(n))return;let c;c=(async()=>{let T=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,l=await t.fetcher();return this.inFlight.get(n)===c&&this.buckets.set(n,{records:l,expireAt:Date.now()+o,epoch:T}),l})(),this.inFlight.set(n,c),c.catch(()=>{}).finally(()=>{this.inFlight.get(n)===c&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:a}=t,o=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&o&&o.expireAt>Date.now())if(t.epochKey){let c=await this.epochStore.getEpoch(t.epochKey);if(c===null||o.epoch===c)return this.maybeRefreshAhead(t),a?o.records.map(T=>structuredClone(T)):o.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),a?o.records.map(c=>structuredClone(c)):o.records;if(!n&&this.inFlight.has(r)){let c=await this.inFlight.get(r);return a?c.map(T=>structuredClone(T)):c}let p;p=(async()=>{let c=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let T=await t.fetcher();if(n||this.inFlight.get(r)===p){let l=Date.now()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:T,expireAt:l,epoch:c}),this.buckets.size>500&&this.cleanExpired()}return T})(),n||this.inFlight.set(r,p);try{let c=await p;return a?c.map(T=>structuredClone(T)):c}finally{this.inFlight.get(r)===p&&this.inFlight.delete(r)}};this.flush=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=Date.now();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};var Wr=require("@aiquants/sse"),we=require("@aiquants/sse/server");var Mn=/^\d{4}-\d{2}-\d{2}$/,Pn=/^\d{4}\/\d{2}\/\d{2}$/,Xt=e=>e<10?`0${e}`:`${e}`,Zt=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Xt(e.getMonth()+1),n=Xt(e.getDate());return`${t}-${r}-${n}`};var ue=e=>{if(e==null)return null;if(e instanceof Date)return Zt(e);let t=e.trim();if(t==="")return null;if(Mn.test(t))return t;if(Pn.test(t))return t.replaceAll("/","-");let r=new Date(t);return Zt(r)};var _t=e=>{let t=2166136261,r=-624069552;for(let n of e){let a=n.reportHubId;t^=a&255,t=Math.imul(t,16777619),t^=a>>>8&255,t=Math.imul(t,16777619),t^=a>>>16&255,t=Math.imul(t,16777619),t^=a>>>24&255,t=Math.imul(t,16777619),r^=a>>>24&255,r=Math.imul(r,16777619),r^=a>>>16&255,r=Math.imul(r,16777619),r^=a>>>8&255,r=Math.imul(r,16777619),r^=a&255,r=Math.imul(r,16777619);let o=n.businessDate;if(o===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let p=0;p<o.length;p++){let c=o.charCodeAt(p);t^=c&255,t=Math.imul(t,16777619),r^=c&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},at=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,er=e=>{for(let t=1;t<e.length;t++)if(at(e[t-1],e[t])>0)return!1;return!0};var tr=(e,t)=>{let r=e.findIndex(n=>at({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var me=(e,t,r=console)=>{let n=a=>typeof a=="string"?[`${t} ${a}`]:[t,a];return{debug:(a,...o)=>{e<=0&&r.debug(...n(a),...o)},info:(a,...o)=>{e<=1&&r.info(...n(a),...o)},warn:(a,...o)=>{e<=2&&r.warn(...n(a),...o)},error:(a,...o)=>{e<=3&&r.error(...n(a),...o)}}};var f=require("zod");var rr=15e3,nr="lastEventId",Ln=/^\d{1,15}-\d{1,15}$/,ar=e=>Ln.test(e),kn=f.z.object({name:f.z.string().nullish(),affiliation:f.z.string().nullish()}),Nn=f.z.object({name:f.z.string().nullish(),text:f.z.string().nullish(),color:f.z.string().nullish()}),On=f.z.object({id:f.z.number(),name:f.z.string().nullish(),color:f.z.string().nullish()}),ir=f.z.object({id:f.z.number(),userId:f.z.string().nullish(),userName:f.z.string().nullish(),content:f.z.string().nullish(),createdAt:f.z.string().nullish(),isMine:f.z.boolean()}),Bn=f.z.object({id:f.z.string(),fileName:f.z.string(),fileType:f.z.string().nullable(),fileSize:f.z.number().nullable(),createdAt:f.z.string().nullable(),state:f.z.enum(["present","absent","unknown"]),hasThumbnail:f.z.boolean().default(!1)}),It=f.z.object({reportHubId:f.z.number(),date:f.z.string().nullish(),createdAt:f.z.string().nullish(),author:f.z.string().nullish(),userId:f.z.string().nullish(),sourceType:f.z.string().nullish(),employeeName:f.z.string().nullish(),updatedBy:f.z.string().nullish(),updatedAt:f.z.string().nullish(),category:f.z.string().nullish(),creationCategory:f.z.string().nullish(),visitTimeFrom:f.z.string().nullish(),visitTimeTo:f.z.string().nullish(),customerName:f.z.string().nullish(),interviewers:f.z.array(kn),subject:f.z.string().nullish(),content:f.z.string().nullish(),externalComments:f.z.array(Nn),isRead:f.z.boolean(),isStarred:f.z.boolean(),labels:f.z.array(On),postedComments:f.z.array(ir),attachments:f.z.array(Bn).default([])}),Un=f.z.object({type:f.z.literal("connected")}),it=f.z.object({type:f.z.literal("status-update"),reportHubId:f.z.number(),statusType:f.z.enum(["star","read"]),value:f.z.boolean(),clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),Et=f.z.string().optional(),Ct=f.z.object({type:f.z.literal("comment-add"),reportHubId:f.z.number(),comment:ir,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional(),sourceType:Et}),xt=f.z.object({type:f.z.literal("comment-delete"),reportHubId:f.z.number(),commentId:f.z.number(),clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional(),sourceType:Et}),vt=f.z.object({type:f.z.literal("report-create"),reportHubId:f.z.number(),report:It,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),Mt=f.z.object({type:f.z.literal("report-update"),reportHubId:f.z.number(),report:It,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),Pt=f.z.object({type:f.z.literal("report-publish"),reportHubId:f.z.number(),report:It,clientTempId:f.z.string(),recipientRawUserId:f.z.number().optional()}),Lt=f.z.object({type:f.z.literal("report-delete"),reportHubId:f.z.number(),clientTempId:f.z.string(),sourceType:Et}),or=f.z.discriminatedUnion("type",[Un,it,Ct,xt,vt,Mt,Pt,Lt]);var kt=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),sr=e=>Object.hasOwn(kt,e);var $n="download",Hn="thumbnail",Fn="1";var lr=e=>{let t=e.getAll(Hn),r=e.getAll($n);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&sr(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Fn?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var ur=(e,t)=>(r,n)=>{let a=n?"markAttachmentPresent":"markAttachmentMissing";e[a](r).catch(o=>{t.error(`${a} failed attachment=${r} message=${o instanceof Error?o.message:"unknown"}`)})};var ot=6e4/1e3,st=5e3/1e3,cr=(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},dr=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Yn=/^[\x20-\x7E]+$/,Vn=/^[\w.+-]+\/[\w.+-]+/,Nt=e=>e&&Yn.test(e)&&Vn.test(e)?e:null,mr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),pr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),lt=e=>{switch(e){case"not_found":case"denied":case"invalid_path":return 404;case"too_large":return 413;default:return 502}},yr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable"},Ne="Attachment request failed";var zn=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,Oe=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${zn(r)}`),ut=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var hr=32*1024*1024,jn=60,Gn=4,Wn=120,Jn=2,Kn=8*1024*1024,he=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw Oe(e,`an integer >= ${r}`,t)},Ie=(e,t,r,n)=>t===void 0?n:he(e,t,r),Qn=[["attachmentThumbnailRenderer",["readAttachment","attachmentIdCodec"]],["readAttachment",["attachmentIdCodec"]],["attachmentIdCodec",["readAttachment"]],["attachmentMaxBytes",["readAttachment"]],["attachmentRateLimitPerMinute",["readAttachment"]],["attachmentConcurrency",["readAttachment"]],["attachmentThumbnailRateLimitPerMinute",["attachmentThumbnailRenderer"]],["attachmentThumbnailConcurrency",["attachmentThumbnailRenderer"]],["attachmentThumbnailCacheBytes",["attachmentThumbnailRenderer"]]],Ot=e=>{for(let[t,r]of Qn){if(e[t]===void 0)continue;let n=r.find(a=>e[a]===void 0);if(n!==void 0)throw ut(n,`injected when ${t} is given`)}},fr=(e,t)=>(Ot({attachmentIdCodec:t.idCodec,readAttachment:t.readAttachment,attachmentThumbnailRenderer:t.thumbnailRenderer,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes}),Object.freeze({originalRateLimitPerMinute:Ie("attachmentRateLimitPerMinute",e.attachmentRateLimitPerMinute,1,jn),originalConcurrency:Ie("attachmentConcurrency",e.attachmentConcurrency,1,Gn),thumbnailRateLimitPerMinute:Ie("attachmentThumbnailRateLimitPerMinute",e.attachmentThumbnailRateLimitPerMinute,1,Wn),thumbnailConcurrency:Ie("attachmentThumbnailConcurrency",e.attachmentThumbnailConcurrency,1,Jn),thumbnailCacheBytes:Ie("attachmentThumbnailCacheBytes",e.attachmentThumbnailCacheBytes,0,Kn)}));var ct=e=>{let t=he("limit",e.limit,1),r=e.queue===null?null:{max:he("queue.max",e.queue.max,0),maxPerOwner:he("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:he("queue.maxWaitMs",e.queue.maxWaitMs,1)},n=0,a=[],o=new Map,p=(l,g)=>{let m=(o.get(l)??0)+g;m<=0?o.delete(l):o.set(l,m)},c=()=>{for(;n<t;){let l=a.shift();if(!l)return;p(l.owner,-1),n+=1,l.grant(T())}},T=()=>{let l=!1;return()=>{l||(l=!0,n-=1,c())}};return{acquire:(l,g)=>{if(g.aborted)return Promise.resolve(null);if(n<t)return n+=1,Promise.resolve(T());if(r===null||a.length>=r.max||(o.get(l)??0)>=r.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:m}=r,_=A=>{let E=()=>{let S=a.indexOf(Q);S<0||(a.splice(S,1),p(l,-1),H(),A(null))},J=setTimeout(E,m);J.unref?.();let H=()=>{clearTimeout(J),g.removeEventListener("abort",E)},Q={owner:l,grant:S=>{H(),A(S)}};a.push(Q),p(l,1),g.addEventListener("abort",E,{once:!0})};return new Promise(_)}}};var Xn=1024,ze=e=>{he("limitPerMinute",e,1);let t=new Map,r=(p,c)=>{c<=p.lastRefillMs||(p.tokens=Math.min(e,p.tokens+(c-p.lastRefillMs)*e/6e4),p.lastRefillMs=c)},n=(p,c)=>{let T=t.get(p);T&&t.delete(p);let l=T??{tokens:e,lastRefillMs:c,deniedSinceAdmission:0};r(l,c),t.set(p,l);for(let g of t.keys()){if(t.size<=Xn)break;t.delete(g)}return l},a=p=>{if(p.tokens<1)return null;p.tokens-=1;let c=Math.max(0,p.deniedSinceAdmission-1);return p.deniedSinceAdmission=0,{allowed:!0,suppressedDenials:c}},o=p=>(p.deniedSinceAdmission+=1,{allowed:!1,firstDenial:p.deniedSinceAdmission===1});return{consume:(p,c)=>{let T=n(p,c);return a(T)??o(T)},refund:(p,c,T)=>{let l=t.get(p);l&&(r(l,c),l.tokens=Math.min(e,l.tokens+T))}}};var Zn=12e4,ea=(e,t,r)=>{let n=setTimeout(t,r);n.unref?.();let a=()=>{clearTimeout(n),t()},o=!1;return new ReadableStream({pull(p){if(o){p.close(),a();return}o=!0,p.enqueue(e)},cancel(){a()}})},br=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,p=t.attachmentDelivery,c=ze(e.rateLimitPerMinute),T=ct({limit:e.concurrency,queue:null});return async l=>{let{request:g,delivery:m,attachmentId:_,internalUserId:A,readAttachment:E,cookie:J,fail:H}=l,Q=p.maxBytes,S=c.consume(A,Date.now());if(!S.allowed)return S.firstDenial&&a.warn(`429 attachment=${_} viewer=${A} reason=rate_limit`),H(429,"Too many requests",{"Retry-After":String(ot)});S.suppressedDenials>0&&a.warn(`rate_limit_suppressed count=${S.suppressedDenials} viewer=${A}`);let P=await n(g),V=await t.getAttachmentForUser(P,_,A);if(!V)return a.warn(`404 attachment=${_} viewer=${A} reason=not_visible`),H(404,"Attachment not found");if(V.fileSize!=null&&V.fileSize>Q)return a.warn(`413 attachment=${_} viewer=${A} reason=db_size`),H(413,"Attachment too large");let F=await T.acquire(A,g.signal);if(!F)return g.signal.aborted?(a.info(`503 attachment=${_} viewer=${A} reason=aborted`),H(503,"Attachment request aborted")):(a.warn(`503 attachment=${_} viewer=${A} reason=concurrency`),H(503,"Too many concurrent downloads",{"Retry-After":String(st)}));let R=!1;try{let M=g.method==="HEAD",I=await E(V.filePath,{maxBytes:Q,head:M,principal:r(A),signal:g.signal});if(g.signal.aborted)return a.info(`503 attachment=${_} viewer=${A} reason=aborted`),H(503,"Attachment request aborted");if(!I.ok){let v=lt(I.reason);return I.reason==="not_found"&&o(_,!1),a.warn(`${v} attachment=${_} viewer=${A} reason=${I.reason} code=${I.code??"-"}`),H(v,yr[v])}if(I.bytes.byteLength>Q)return a.error(`500 attachment=${_} viewer=${A} reason=port_contract code=over_max_bytes`),H(500,Ne);let L=Nt(V.fileType)??Nt(I.contentType),b=L!==null&&dr.has(L),x=b?L:"application/octet-stream",q=b&&m.kind!=="download"?"inline":"attachment",O=I.size??I.bytes.byteLength,Y=new Headers({"Content-Type":x,"Content-Length":String(O),"Content-Disposition":`${q}; filename="${pr(V.fileName)}"; filename*=UTF-8''${mr(V.fileName)}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return J&&Y.append("Set-Cookie",J),o(_,!0),a.info(`200 attachment=${_} viewer=${A} type=${x} disposition=${q} bytes=${O}`),M?new Response(null,{status:200,headers:Y}):(R=!0,new Response(ea(I.bytes,F,Zn),{status:200,headers:Y}))}finally{R||F()}}};var Re=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Ci=Re.queueWaitMs+Re.readMs+Re.renderMs+Re.transferMarginMs;var gr=require("crypto"),Be=e=>{let t=JSON.stringify(e);return`"${(0,gr.createHash)("sha256").update(t).digest("hex")}"`};var ta=new Set([194,198,202,206]),ra=64,na=2,Rr=8,Sr=28,Ae=12,Bt=8,aa=20,Tr=Ae+Bt+10,ia=2,Se=(e,t)=>e[t]<<8|e[t+1],Ue=(e,t,r)=>{let n=0;for(let a=r-1;a>=0;a-=1)n=n*256+e[t+a];return n},fe=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},oa=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Ut=e=>{if(e[0]!==255||e[1]!==216)return null;let t=null,r=2;for(;r<e.byteLength;){if(e[r]!==255)return null;for(;r<e.byteLength&&e[r]===255;)r+=1;if(r>=e.byteLength)return null;let n=e[r];if(r+=1,n===0||n===216||n===217)return null;if(n===1||n>=208&&n<=215)continue;if(r+2>e.byteLength)return null;let a=Se(e,r),o=r+2,p=r+a;if(a<2||p>e.byteLength)return null;if(oa(n)){if(t!==null||a<8)return null;let c=Se(e,o+1),T=Se(e,o+3),l=e[o+5];if(T===0||c===0||l===0||a!==8+3*l)return null;let g=[];for(let m=0;m<l;m+=1){let _=e[o+7+3*m],A=_>>4,E=_&15;if(A<1||A>4||E<1||E>4)return null;g.push({horizontal:A,vertical:E})}t={width:T,height:c,components:g,progressive:ta.has(n)}}else if(n===218){if(t===null||a<3)return null;let c=e[o];return c<1||c>4||a!==6+2*c?null:{width:t.width,height:t.height,components:t.components,multiScan:t.progressive||c<t.components.length}}r=p}return null},Ar=e=>{if(!e.multiScan)return 0;let t=Math.max(...e.components.map(a=>a.horizontal)),r=Math.max(...e.components.map(a=>a.vertical)),n=0;for(let{horizontal:a,vertical:o}of e.components){let p=Math.ceil(e.width*a/(t*Rr)),c=Math.ceil(e.height*o/(r*Rr));n+=Math.ceil(p/a)*a*Math.ceil(c/o)*o}return n*ra*na},Dr=e=>{if(e.byteLength<24||Se(e,8)!==0||Se(e,10)!==13||!fe(e,12,"IHDR"))return null;let t=Se(e,16)*65536+Se(e,18),r=Se(e,20)*65536+Se(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},sa=e=>{if(fe(e,Ae,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ue(e,26,2)&16383,r=Ue(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(fe(e,Ae,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ue(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return fe(e,Ae,"VP8X")?e.byteLength<Tr?null:{width:Ue(e,24,3)+1,height:Ue(e,27,3)+1}:null},wr=e=>{if(Dr(e)===null||e.byteLength<=Sr)return null;switch(e[Sr]){case 0:return!1;case 1:return!0;default:return null}},_r=e=>{if(fe(e,Ae,"VP8 "))return"lossy";if(fe(e,Ae,"VP8L"))return"lossless";if(!fe(e,Ae,"VP8X")||e.byteLength<Tr)return null;if((e[aa]&ia)!==0)return"animated";let t=!1;for(let r=Ae;r+Bt<=e.byteLength;){if(fe(e,r,"VP8L"))return"lossless";if(fe(e,r,"VP8 "))return t?"lossy-alpha":"lossy";fe(e,r,"ALPH")&&(t=!0);let n=Ue(e,r+4,4);r+=Bt+n+n%2}return null},Ir={png:Dr,jpeg:Ut,webp:sa};var la=new Set(["image/png","image/jpeg","image/gif","image/webp"]),$t=Object.freeze(["image/webp","image/jpeg","image/png"]),ua={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},ca=new Set($t),da=e=>typeof e=="string"&&ca.has(e),Ht=1024*1024,ma=256,dt=(e,t)=>e.fileType===null||!la.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,pa=[137,80,78,71,13,10,26,10],ya=[255,216,255],ha=[[71,73,70,56,55,97],[71,73,70,56,57,97]],fa=[82,73,70,70],ba=[87,69,66,80],je=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,a]of t.entries())if(e[r+n]!==a)return!1;return!0},Ft=e=>{if(je(e,pa,0))return"png";if(je(e,ya,0))return"jpeg";for(let t of ha)if(je(e,t,0))return"gif";return je(e,fa,0)&&je(e,ba,8)?"webp":null},Er=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:Be([t])}},Cr=(e,t)=>{if(!da(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>Ht)return"too_large";let r=ua[e.contentType];if(Ft(e.bytes)!==r)return"signature";let n=Ir[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},xr=e=>{he("maxBytes",e.maxBytes,0),he("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=a=>{let o=t.get(a);o&&(t.delete(a),r-=o.weight)};return{get:a=>{let o=t.get(a);if(o)return t.delete(a),t.set(a,o),o.entry},set:(a,o)=>{n(a);let p=(o.kind==="thumbnail"?o.bytes.byteLength:0)+ma;if(p>e.maxBytes||e.maxEntries===0)return;let c=o.kind==="thumbnail"?{kind:"thumbnail",bytes:o.bytes.slice(),contentType:o.contentType}:o;t.set(a,{entry:c,weight:p}),r+=p;for(let T of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(T)}}}};var vr=()=>{let e=new Map;return{join:(t,r,n)=>{let a=()=>{let T=new AbortController,l=()=>{e.get(t)?.controller===T&&e.delete(t)},m={promise:n(T.signal).finally(l),controller:T,waiters:0};return e.set(t,m),m},o=e.get(t)??a();o.waiters+=1;let p=()=>{o.waiters-=1,!(o.waiters>0)&&(o.controller.abort(),e.get(t)===o&&e.delete(t))};r.aborted?p():r.addEventListener("abort",p,{once:!0});let c=()=>{r.removeEventListener("abort",p)};return o.promise.finally(c)}}};var qt=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:a,onStuck:o}=e,p=Date.now(),c=new AbortController,T=!1,l,g,m=(F,R)=>{let M=setTimeout(F,R);return M.unref?.(),M},_=()=>{o(Date.now()-p)},A=F=>{l=m(()=>{T=!0,F({timedOut:!0}),g=m(_,t),c.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},E=new Promise(A),J=AbortSignal.any([r,c.signal]),H=F=>{F(n(J))},Q=new Promise(H),S=F=>{clearTimeout(l),clearTimeout(g),T&&a(Date.now()-p,F)},P=Q.then(()=>S(null),F=>S({error:F}));return{outcome:Promise.race([Q.then(F=>({timedOut:!1,value:F})),E]),settled:P}};var Ee={404:"Attachment not found",500:Ne,502:"Thumbnail unavailable",503:"Too many concurrent thumbnail requests"},Mr=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:a,recordObjectState:o,logger:p}=e,c=(g,m)=>{if(g.fileSize===null||(m.kind==="exact"?m.bytes===g.fileSize:g.fileSize>m.maxBytes))return"verified";let A=m.kind==="exact"?String(m.bytes):`>${m.maxBytes}`;return p.warn(`size_mismatch expected=${g.fileSize} got=${A} attachment=${g.attachmentId} viewer=${g.owner} variant=thumbnail`),"unverified"},T=(g,m)=>(_,A)=>{let E=A===null?"":` message=${A.error instanceof Error?A.error.message:"unknown"}`;p.warn(`${g}_overrun ms=${_} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail${E}`)},l=(g,m)=>_=>{p.warn(`${g}_stuck ms=${_} attachment=${m.attachmentId} viewer=${m.owner} variant=thumbnail`)};return async(g,m)=>{let _=await t.acquire(g.owner,m);if(!_)return{kind:"failure",status:503,reason:m.aborted?"aborted":"queue"};let A=null;try{if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let E=qt({budgetMs:Re.readMs,flightSignal:m,call:I=>g.readAttachment(g.filePath,{maxBytes:n,head:!1,principal:a(g.owner),signal:I}),onOverrun:T("read",g),onStuck:l("read",g)}),J=await E.outcome;if(J.timedOut)return A=E.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"read_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let H=J.value;if(!H.ok&&H.reason!=="too_large")return H.reason==="not_found"&&o(g.attachmentId,!1),{kind:"failure",status:lt(H.reason)===404?404:502,reason:H.reason,code:H.code};if(H.ok&&H.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let Q=c(g,H.ok?{kind:"exact",bytes:H.bytes.byteLength}:{kind:"over",maxBytes:n}),S=I=>(Q==="verified"&&r.set(g.key,I),{...I,identity:Q});if(!H.ok)return S({kind:"unrenderable",reason:"too_large"});let P=Ft(H.bytes);if(P===null)return S({kind:"unrenderable",reason:"signature"});let V=qt({budgetMs:Re.renderMs,flightSignal:m,call:I=>g.renderer.render(H.bytes,{format:P,maxWidth:g.box.maxWidth,maxHeight:g.box.maxHeight,signal:I}),onOverrun:T("render",g),onStuck:l("render",g)}),F=await V.outcome;if(F.timedOut)return A=V.settled,m.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};if(m.aborted)return{kind:"failure",status:503,reason:"aborted"};let R=F.value;if(!R.ok)return R.reason==="unsupported"?S({kind:"unrenderable",reason:"unsupported"}):R.reason==="failed"?{kind:"failure",status:502,reason:"render_failed"}:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};let M=Cr(R,g.box);return M!==null?{kind:"failure",status:500,reason:"port_contract",code:M}:S({kind:"thumbnail",bytes:R.bytes,contentType:R.contentType})}finally{A===null?_():A.then(_)}}};var kr=10,ga=1/kr,Pr=1-ga,Ra=1024,Sa=64,Ta=8,Lr="private, no-cache",Aa="no-store",Da=e=>{switch(e.status){case 404:case 502:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Nr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,p=t.attachmentDelivery,c=ze(e.rateLimitPerMinute),T=ze(e.rateLimitPerMinute*kr),l=ct({limit:e.concurrency,queue:{max:Sa,maxPerOwner:Ta,maxWaitMs:Re.queueWaitMs}}),g=xr({maxBytes:e.cacheBytes,maxEntries:Ra}),m=vr(),_=Mr({gate:l,cache:g,maxBytes:p.maxBytes,encodeUserId:r,recordObjectState:o,logger:a}),A=(S,P,V,F)=>{let R=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${F}`;if(P.kind==="failure")return a[Da(P)](`${P.status} ${R} reason=${P.reason} code=${P.code??"-"}`),S.fail(P.status,Ee[P.status],P.status===503?{"Retry-After":String(st)}:{});let M=P.identity==="verified"?"":` identity=${P.identity}`;if(P.kind==="unrenderable")return a.info(`404 ${R} reason=${P.reason}${M}`),S.fail(404,Ee[404]);let I=P.identity==="verified"?{"Cache-Control":Lr,ETag:V}:{"Cache-Control":Aa},L=new Headers({"Content-Type":P.contentType,"Content-Length":String(P.bytes.byteLength),...I,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return S.cookie&&L.append("Set-Cookie",S.cookie),a.info(`200 ${R} type=${P.contentType} bytes=${P.bytes.byteLength}${M}`),new Response(P.bytes,{status:200,headers:L})},E=(S,P,V)=>(P.firstDenial&&a.warn(`429 attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail reason=${V}`),S.fail(429,"Too many requests",{"Retry-After":String(ot)})),J=(S,P,V)=>{P.suppressedDenials>0&&a.warn(`${V}_suppressed count=${P.suppressedDenials} viewer=${S.internalUserId} variant=thumbnail`)},H=S=>{let P=c.consume(S.internalUserId,Date.now());return P.allowed?(J(S,P,"rate_limit"),null):E(S,P,"rate_limit")},Q=(S,P)=>{if(!P)return H(S);let V=T.consume(S.internalUserId,Date.now());return V.allowed?(J(S,V,"revalidation_rate_limit"),null):E(S,V,"revalidation_rate_limit")};return async(S,P)=>{let{request:V,attachmentId:F,internalUserId:R,readAttachment:M,cookie:I,fail:L}=S,b=kt[P],x=p.thumbnailRenderer;if(!x)return L(404,Ee[404]);let q=V.headers.get("If-None-Match"),O=q!==null,Y=Q(S,O);if(Y)return Y;let v=await n(V),$=await t.getAttachmentForUser(v,F,R),j=$!==null&&dt($,p.maxBytes)?Er({rendererId:x.id,box:b,attachmentId:F,filePath:$.filePath,fileType:$.fileType,fileSize:$.fileSize}):null;if(j&&cr(q,j.etag)){let C=new Headers({"Cache-Control":Lr,ETag:j.etag});return I&&C.append("Set-Cookie",I),a.info(`304 attachment=${F} viewer=${R} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:C})}if(O){let C=H(S);if(C)return C}if(!$)return a.warn(`404 attachment=${F} viewer=${R} variant=thumbnail reason=not_visible`),L(404,Ee[404]);if(!j)return c.refund(R,Date.now(),Pr),a.info(`404 attachment=${F} viewer=${R} variant=thumbnail reason=not_eligible`),L(404,Ee[404]);let{key:z,etag:ee}=j,K=g.get(z);if(K)return c.refund(R,Date.now(),Pr),A(S,{...K,identity:"verified"},ee,"hit");let X=C=>_({key:z,attachmentId:F,filePath:$.filePath,fileSize:$.fileSize,box:b,owner:R,readAttachment:M,renderer:x},C),k;try{k=await m.join(z,V.signal,X)}catch(C){return a.error(`500 attachment=${F} viewer=${R} variant=thumbnail cache=miss reason=port_exception message=${C instanceof Error?C.message:"unknown"}`),L(500,Ee[500])}return A(S,k,ee,"miss")}};var wa='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Or=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:a,logger:o}=e,p=r.attachmentDelivery,c=fr(e.tuning,p),T={service:r,encodeUserId:n,resolveViewerScope:a,logger:o,recordObjectState:ur(r,o)},l=br({...T,rateLimitPerMinute:c.originalRateLimitPerMinute,concurrency:c.originalConcurrency}),g=Nr({...T,rateLimitPerMinute:c.thumbnailRateLimitPerMinute,concurrency:c.thumbnailConcurrency,cacheBytes:c.thumbnailCacheBytes});return async({request:m,params:_})=>{let A=null,E=(J,H,Q={})=>{let S=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...Q});return A&&S.append("Set-Cookie",A),new Response(JSON.stringify({error:{message:H}}),{status:J,headers:S})};try{let{user:J,cookie:H}=await t(m,{failureRedirect:null});if(A=H??null,!J)return E(401,"Unauthorized");let Q=lr(new URL(m.url).searchParams);if(Q.kind==="invalid")return E(400,"Invalid attachment request");if(Q.kind==="thumbnail"&&m.method!=="GET")return E(405,"Method not allowed",{Allow:"GET"});if(m.method!=="GET"&&m.method!=="HEAD")return E(405,"Method not allowed",{Allow:"GET, HEAD"});let{idCodec:S,readAttachment:P}=p;if(!(S&&P))return E(404,"Attachment not found");if(_.token===void 0)throw new Error(wa);let V=S.decode(_.token);if(V===null||!Number.isSafeInteger(V)||V<=0)return E(400,"Invalid attachment token");let F=await r.getUserIdByExternalId(J.id);if(!F)return E(403,"Forbidden");let R={request:m,delivery:Q,attachmentId:V,internalUserId:F,readAttachment:P,cookie:A,fail:E};return Q.kind==="thumbnail"?await g(R,Q.variant):await l(R)}catch(J){if(J instanceof Response)throw J;return o.error(`500 attachment=? viewer=? reason=unexpected message=${J instanceof Error?J.message:"unknown"}`),E(500,Ne)}}};var _a=me(1,"[Response]"),pe=(e,t,r,n=200,a=_a)=>{let o=Be(r),p=e.headers.get("If-None-Match");a.info(`[jsonResponseWithETag] ETag: ${o}, If-None-Match: ${p}`);let c=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:o});return t&&c.append("Set-Cookie",t),e.method==="GET"&&n===200&&p===o?new Response(null,{status:304,headers:c}):new Response(JSON.stringify(r),{status:n,headers:c})};var Br=require("@aiquants/sse"),Ur=require("@aiquants/sse/shared-source");var De=(e,t)=>{let[r,n]=e.split("-").map(Number),[a,o]=t.split("-").map(Number);return r!==a?r<a:n<=o},pt="$",Ia=5e3,Ea=100,$e=class{constructor(t){this.config=t;this._lastId=pt;this._positioning=null;this._generation=0;this._logger=t.logger??me(1,"[SSE Reader]"),this._source=this._createSource()}ready(){if(this._lastId!==pt)return Promise.resolve();if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{t===this._generation&&(this._positioning=null,r!==null&&this._lastId===pt&&(this._lastId=r))})}return this._positioning}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=pt,this._source=this._createSource()}async _readTail(){try{let t=await this.config.redis?.getClient();if(!t)return null;let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}catch(t){return this._logger.warn("Failed to resolve stream tail anchor; falling back to $:",t),null}}_createSource(){return(0,Ur.createSharedSource)({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:Br.systemSseRuntime,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this.config.redis?.createClient();if(!r)throw new Error("Failed to create Redis client for SSE reader");r.on("error",o=>{this._logger.error("Redis client error:",o)}),await this.ready();let n=!1,a=this._readLoop(r,t,()=>n);return async()=>{if(n=!0,r.isOpen)try{await r.quit()}catch{}await a}}async _readLoop(t,r,n){let a=this._lastId;try{for(;!n()&&t.isOpen;){let o=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Ia,COUNT:Ea});if(o)for(let p of o)for(let c of p.messages)a=c.id,this._invalidateCaches(c.message),r.next({id:c.id,message:c.message})}}catch(o){n()||(this._logger.error("xRead loop error:",o),r.fail(o instanceof Error?o:new Error(String(o))));return}n()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){try{let r=t?.data?JSON.parse(t.data):null,n=r?.type;if((n==="report-create"||n==="report-delete"||n==="report-publish")&&this.config.cache.invalidatePrefix("daily-report:ids"),n==="comment-add"||n==="comment-delete"||n==="status-update"){let a=r?.reportHubId;typeof a=="number"&&(this.config.cache.invalidate(`daily-report:detail:${a}`),this.config.cache.invalidatePrefix(`daily-report:detail:${a}:user:`))}}catch{}}};var We=require("drizzle-orm");var Ca="",xa=64,va=e=>e.toLowerCase(),Ma=e=>e.trim().toLowerCase();function $r(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=Ma(r);n.length>0&&t.add(n)}return t}function be(e,t){return e===null?!0:t==null?!1:e.has(va(t))}function Ce(e){return e!==null&&e.size===0}function Fr(e,t){if(t!==null)return t.size===0?We.sql`1 = 0`:(0,We.inArray)(We.sql`LOWER(${e})`,[...t])}var He,Fe,Ge=class Ge{constructor(t,r){Dt(this,He);Dt(this,Fe);wt(this,He,t),wt(this,Fe,r)}get visible(){return Ve(this,He)===null?null:new Set(Ve(this,He))}get commentable(){return Ve(this,Fe)===null?null:new Set(Ve(this,Fe))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=$r(r?t.read:t),a=r?t.comment:void 0;if(a===void 0)return new Ge(n,n);let o=$r(a),p=new Set;for(let c of o??[])n.has(c)&&p.add(c);return new Ge(n,p)}static unrestricted(t){return new Ge(null,null)}};He=new WeakMap,Fe=new WeakMap;var ye=Ge;function Je(e){let t=Hr(e.visible),r=Hr(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Hr(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Ca);if(t.length<=xa)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 Pa=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},yt=30,Jr=4e3,La="stream interrupted by server error",ka=/^\d{4}-\d{2}-\d{2}$/,Na=15e3,qr=Symbol("ids-stream-heartbeat"),Yr=864e5,Oa={baseMs:2e3,jitterMs:8e3},Yt=6e4,ht=1e3,Vr=JSON.stringify({type:"connected"}),zr="0-0",Ba=/^[0-9a-f]{1,16}$/,Ua=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),a=n!==null&&Ba.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:a}:{invalid:!0};let o=Number.parseInt(t,10);return!Number.isSafeInteger(o)||String(o)!==t||o<=0?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:o},snapshot:a}:ka.test(r)?{cursor:{businessDate:r,reportHubId:o},snapshot:a}:{invalid:!0}};async function*jr(e,t,r,n){let a=t?tr(e,t):0,o=!0;for(;;){let p=e.slice(a,a+(o?r:Jr));a+=p.length;let c=a>=e.length,T=p[p.length-1];if(yield{kind:"chunk",items:p,nextCursor:c||!T?null:{businessDate:T.businessDate,reportHubId:T.reportHubId},isLast:c,...o?{total:e.length}:{},...o?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...o&&n.restarted?{restarted:!0}:{}},o=!1,c)return}}var Gr=(e,t,r,n)=>{let a=new TextEncoder,o=!1,p=null,c=new ReadableStream({async pull(l){if(o||r.signal.aborted){await t.return(void 0).catch(()=>{});try{l.close()}catch{}return}let g=null;try{p===null&&(p=t.next());let m=new Promise(J=>{g=setTimeout(()=>J(qr),Na)}),_=await Promise.race([p,m]);if(g!==null&&(clearTimeout(g),g=null),_===qr){if(o||r.signal.aborted){await t.return(void 0).catch(()=>{});try{l.close()}catch{}return}l.enqueue(a.encode(`
|
|
2
|
+
`));return}p=null;let{value:A,done:E}=_;if(E){l.close();return}if(o||r.signal.aborted){await t.return(void 0).catch(()=>{});try{l.close()}catch{}return}l.enqueue(a.encode(`${JSON.stringify(A)}
|
|
3
|
+
`))}catch(m){if(g!==null&&clearTimeout(g),p=null,o||r.signal.aborted)return;n.error(`ids-stream emission failed: ${m instanceof Error?m.message:String(m)}`);try{let _={kind:"error",error:La};l.enqueue(a.encode(`${JSON.stringify(_)}
|
|
4
|
+
`)),l.close()}catch{}}},cancel(){o=!0,t.return(void 0).catch(()=>{})}}),T=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&T.append("Set-Cookie",e),new Response(c,{status:200,headers:T})},$a=(e,t,r,n)=>{if(r===null&&n===null)return!0;let a=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return be(r,e.report.sourceType);case"comment-add":case"comment-delete":return be(n,a??"Internal");case"report-delete":return be(r,a)}},Ha=["externalComments","postedComments"],Fa=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||be(r,e.report.sourceType))return!1;let n=t.report;if(typeof n!="object"||n===null)return!1;let a=n;for(let o of Ha)a[o]=[];return!0};function ft(e){let{authenticate:t,service:r,encodeUserId:n,redis:a,sseReader:o,streamKey:p}=e,c=e.loginRedirectPath??"/auth/login",T=e.logger??me(3,"[DailyReportAPI]"),l=e.logger??me(3,"[DailyReportVisibility]"),g=e.logger??me(1,"[DailyReportSSE]"),m=e.logger??me(1,"[DailyReportAttachment]"),_=async(R,M="initial")=>{let I=e.resolveVisibleSourceTypes;if(!I)return ye.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let L=await I(R,{reason:M});return L==null?ye.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):ye.restrictTo(L)}catch(L){return l.error("resolveVisibleSourceTypes threw; failing closed (deny all)",L),ye.restrictTo([])}},A=async({request:R})=>{let{user:M,cookie:I}=await t(R,{failureRedirect:c}),L=new Headers;I&&L.append("Set-Cookie",I);let b=await r.getUserIdByExternalId(M.id),x=b?n(b):null;return{data:{user:M,userId:x},headers:L}},E={"business-date":async(R,M,I,L,b)=>{let x=ue(R.searchParams.get("businessDate")),q=R.searchParams.get("forceRefresh")==="true";if(!x)return pe(I,M,{error:{message:"Invalid business date"}},400);let O=await r.getDailyReportsByBusinessDateByExternalId(b,x,L.id,{forceRefresh:q});return pe(I,M,{businessDate:x,reports:O},200)},"ids-stream":async(R,M,I,L,b)=>{let x=Ua(R);if("invalid"in x)return pe(I,M,{error:{message:"Invalid cursor"}},400);let q=R.searchParams.get("forceRefresh")==="true",O=!1,Y=null,v=null,$=new Promise((z,ee)=>{Y=z,v=ee});$.catch(()=>{});let ae=r.getDailyReportIdsByExternalId(b,L.id,{forceRefresh:q,onFetchStart:x.cursor?void 0:()=>{O=!0,r.readSseStreamAnchor().then(z=>r.getDailyReportIdsFirstPageByExternalId(b,L.id,yt).then(ee=>({items:ee,streamAnchor:z}))).then(z=>Y?.(z),z=>v?.(z))}});if(ae.catch(()=>{}),x.cursor){let{items:z,streamAnchor:ee}=await ae,K=_t(z),X=x.snapshot!==null&&x.snapshot===K;return Gr(M,jr(z,X?x.cursor:null,yt,{snapshot:K,restarted:!X,streamAnchor:ee}),I,T)}let j=(async function*(){let z=await Promise.race([ae.then(X=>({kind:"full",source:X}),X=>({kind:"full-error",error:X})),$.then(X=>({kind:"page",page:X}),()=>({kind:"page-error"}))]),ee=null,K=!1;if(z.kind==="full")ee=z.source;else if(z.kind==="page"){let{items:X,streamAnchor:k}=z.page;if(X.length<yt){yield{kind:"chunk",items:X,nextCursor:null,isLast:!0,total:X.length,streamAnchor:k};return}yield{kind:"chunk",items:X,nextCursor:null,isLast:!1,provisional:!0},K=!0}else if(z.kind==="full-error"&&O){let X=await $.catch(()=>null);X&&X.items.length>0&&(yield{kind:"chunk",items:X.items,nextCursor:null,isLast:!1,provisional:!0})}ee===null&&(ee=await ae),yield*jr(ee.items,null,K?Jr:yt,{snapshot:_t(ee.items),streamAnchor:ee.streamAnchor})})();return Gr(M,j,I,T)},report:async(R,M,I,L,b)=>{let x=R.searchParams.get("reportHubId"),q=R.searchParams.get("forceRefresh")==="true",O=x?Number.parseInt(x,10):NaN;if(!Number.isFinite(O)||O<=0)return pe(I,M,{error:{message:"Invalid reportHubId"}},400);let Y=await r.getDailyReportDetailByIdByExternalId(b,O,L.id,{snapshot:!0,forceRefresh:q});return Y?pe(I,M,{report:Y},200):pe(I,M,{error:{message:"Report not found"}},404)}},J=async({request:R,params:M})=>{let{user:I,cookie:L}=await t(R,{failureRedirect:null}),b=L??null;if(!I)return pe(R,b,{error:{message:"Unauthorized"}},401);if(R.method!=="GET")return pe(R,b,{error:{message:"Method not allowed"}},405);let x=M.endpoint??"",q=E[x];if(!q)return pe(R,b,{error:{message:"Unknown endpoint"}},404);let O=Date.now();try{let Y=new URL(R.url),v=await _(R);return await q(Y,b,R,I,v)}catch(Y){let v=Date.now()-O,$=Y instanceof Error?Y:new Error(String(Y));return T.error(`500 endpoint=${x} elapsed=${v}ms name=${$.name} code=${"code"in $?$.code:"N/A"} message=${$.message}`),T.error("Stack:",$.stack),pe(R,b,{error:{message:"Internal Server Error"}},500)}},H=async({request:R,params:M})=>{let{user:I,cookie:L}=await t(R,{failureRedirect:null}),b=(q,O)=>Pa(q,{...O,setCookie:L});if(!I)return b({error:"Unauthorized"},{status:401});let x=Date.now();try{if(M.endpoint!=="action")return b({error:"Unknown endpoint"},{status:404});let O=await r.getUserIdByExternalId(I.id);if(!O)return b({error:"User not found"},{status:404});let Y=await _(R),v=await R.formData(),$=v.get("intent"),ae=v.get("reportHubId"),j=ae?Number(ae):NaN,z=v.get("businessDate"),ee=Number(v.get("operationTimestamp")),K=v.get("clientTempId");if($==="clearCache")return e.enableDevCacheClear?(await r.clearCache(),b({status:"OK",intent:"clearCache"})):b({error:"Invalid intent"},{status:400});if(!K)return b({error:"clientTempId required"},{status:400});if($!=="create"&&(!j||Number.isNaN(j)))return b({error:"Invalid reportHubId"},{status:400});let X=async(k,C,te)=>{let de=v.get(C);if(de===null)return b({error:`${C} required`},{status:400});try{let ie=await te(de==="true");return b({status:"OK",intent:k,updatedStatus:{isStarred:ie.isStarred,isRead:ie.isRead},operationTimestamp:ee,reportHubId:String(j),clientTempId:K})}catch(ie){if(ie instanceof Error&&ie.message==="Not Found")return b({error:"Report not found"},{status:404});throw ie}};switch($){case"create":{if(!z)return b({error:"businessDate required"},{status:400});let k=await r.createDailyReport(O,z,K);return b({status:"OK",intent:"create",report:k,reportHubId:String(k.reportHubId),clientTempId:K})}case"update":{let k=v.get("title"),C=v.get("content");try{return await r.updateDailyReport(j,O,{title:k,content:C},K),b({status:"OK",intent:"update",reportHubId:String(j),clientTempId:K})}catch(te){if(te instanceof Error){if(te.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(te.message==="Not Found")return b({error:"Report not found"},{status:404})}throw te}}case"publish":try{let k=await r.publishDailyReport(j,O,K);return b({status:"OK",intent:"publish",reportHubId:String(j),clientTempId:K,report:k})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return b({error:"Report not found"},{status:404})}throw k}case"delete":try{return await r.deleteDailyReport(j,O,K),b({status:"OK",intent:"delete",reportHubId:String(j),clientTempId:K})}catch(k){if(k instanceof Error){if(k.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(k.message==="Not Found")return b({error:"Report not found"},{status:404})}throw k}case"toggleStar":return await X("toggleStar","isStarred",k=>r.setStarStatus(Y,O,j,z,k,K));case"toggleRead":return await X("toggleRead","isRead",k=>r.setReadStatus(Y,O,j,z,k,K));case"addComment":{let k=v.get("content");if(!k)return b({error:"Content required"},{status:400});try{let C=await r.addComment(Y,O,j,k,z,K),te={...C,userId:C.userId};return b({status:"OK",intent:"addComment",newComment:te,reportHubId:String(j),clientTempId:K})}catch(C){if(C instanceof Error){if(C.message==="Not Found")return b({error:"Report not found"},{status:404});if(C.message.startsWith("Comments are restricted"))return b({error:"Comments are restricted for this report"},{status:403})}throw C}}case"deleteComment":{let k=Number(v.get("commentId"));if(!k||Number.isNaN(k))return b({error:"Invalid commentId"},{status:400});try{return await r.deleteComment(Y,O,j,k,z,K),b({status:"OK",reportHubId:String(j),deletedCommentId:String(k),clientTempId:K})}catch(C){if(C instanceof Error){if(C.message==="Unauthorized")return b({error:"Unauthorized"},{status:403});if(C.message==="Not Found")return b({error:"Comment not found"},{status:404})}throw C}}default:return b({error:"Invalid intent"},{status:400})}}catch(q){if(q instanceof Response)throw q;let O=Date.now()-x,Y=q instanceof Error?q:new Error(String(q));return T.error(`500 action elapsed=${O}ms name=${Y.name} message=${Y.message}`),T.error("Stack:",Y.stack),b({error:"Internal Server Error"},{status:500})}},Q=(R,M)=>{R.writeEvent({event:null,id:M,data:Vr})},S=(R,M,I,L)=>{if(I.data)try{let b=JSON.parse(I.data),x=or.safeParse(b);if(!x.success){g.error("SSE message validation failed:",x.error.format());return}let q=x.data,O=typeof b.recipientRawUserId=="number"?b.recipientRawUserId:void 0;if((q.type==="status-update"||O!==void 0)&&O!==L.internalUserId||!$a(q,b,L.visibleSet,L.commentableSet)){Q(R,M);return}let v=Fa(q,b,L.commentableSet),$;if("recipientRawUserId"in b){let{recipientRawUserId:ae,...j}=b;$=JSON.stringify(j)}else v?$=JSON.stringify(b):$=I.data;R.writeEvent({event:null,id:M,data:$})}catch(b){g.error(`[SSE:${L.internalUserId}] processEntry error:`,b)}},P=async(R,M)=>{let{request:I,internalUserId:L,cursor:b}=M,x=M.initialScope.visible,q=M.initialScope.commentable,O=0,Y=setInterval(()=>{let C=++O;_(I,"refresh").then(te=>{C===O&&(x=te.visible,q=te.commentable)})},Yt);R.onClose(()=>clearInterval(Y));let v=b===null?zr:b,$=b!==null&&a!==void 0,ae=[],j=null,z=C=>{De(C.id,v)||(v=C.id,S(R,C.id,C.message,{internalUserId:L,visibleSet:x,commentableSet:q}))},ee=async(C,te)=>{let[de]=await C.xRange(p,"-","+",{COUNT:1});return de!==void 0&&!De(de.id,te)},K=async(C,te)=>{if(await ee(C,te))return!1;let de=te;for(;;){let ie=await C.xRange(p,de,"+",{COUNT:ht}),ve=ie[0];if(ve!==void 0&&ve.id!==de&&await ee(C,de))return!1;for(let Xe of ie){if(j!==null&&De(j,Xe.id))return!0;z(Xe)}let Qe=ie.at(-1);if(ie.length<ht||Qe===void 0||R.isClosed())return!0;de=Qe.id}},X=o.subscribe(C=>{if(!$){z(C);return}De(C.id,v)||(j===null&&(j=C.id),ae.push(C))},C=>{g.error(`[SSE:${L}] Fan-Out reader error:`,C),R.close()});if(R.onClose(X),b===null){await o.ready();try{let C=await a?.getClient();if(C){let te=await C.xRevRange(p,"+","-",{COUNT:1});te.length>0&&!De(te[0].id,v)&&(v=te[0].id)}}catch{}}if(R.writeEvent({event:null,id:v===zr?null:v,data:Vr}),(0,we.startSseHeartbeat)(R,{intervalMs:rr,retry:Oa,runtime:Wr.systemSseRuntime}),b===null||a===void 0)return;await o.ready();let k=await a.getClient();if(k===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await K(k,b)){R.writeRetry(Yr),R.writeEvent({event:"resync-required",id:null,data:""}),R.close();return}$=!1;for(let C of ae.splice(0))z(C)},V=async({request:R,params:M})=>{let I,L=()=>{let x=new Headers;return I!==void 0&&x.append("Set-Cookie",I),x},b=x=>(0,we.terminalStreamResponse)(x,{data:"",retryMs:Yr,headers:L()});try{let x=await t(R,{failureRedirect:null});I=x.cookie;let{user:q}=x;if(!q)return b("auth-required");let O=await r.getUserIdByExternalId(q.id);if(!O)return b("forbidden");if(M.endpoint!=="updates")return new Response("Not Found",{status:404,headers:L()});let Y=(0,we.readLastEventId)(R,nr);if(Y!==null&&!ar(Y))return g.warn(`[SSE:${O}] malformed resume cursor; asking the client to resync`),b("resync-required");let v=await _(R);return(0,we.createSseResponse)({requestSignal:R.signal,headers:L(),onError:($,ae)=>g.error(`[SSE:${O}] ${ae} failed:`,$),produce:$=>P($,{request:R,internalUserId:O,cursor:Y,initialScope:v})})}catch(x){if(x instanceof Response)throw x;let q=x instanceof Error?x:new Error(String(x));return g.error(`500 sse name=${q.name} message=${q.message}`),new Response("Internal Server Error",{status:500,headers:L()})}},F=Or({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:_,logger:m,tuning:e});return{index:{loader:A},api:{loader:J,action:H},sse:{loader:V},attachment:{loader:F}}}var Kr=require("@aiquants/mssql"),u=require("drizzle-orm");var xe=e=>(0,u.getColumns)(e),qa=e=>{if(e!==void 0){if(typeof e!="object"||e===null)throw Oe("attachmentThumbnailRenderer","an object with id and render",e);if(e.render===void 0)throw ut("attachmentThumbnailRenderer.render","a function");if(typeof e.render!="function")throw Oe("attachmentThumbnailRenderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Oe("attachmentThumbnailRenderer.id","a non-blank string naming the rendering pipeline version",e.id);return e}},ce=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),a=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),o=String(r.getMonth()+1).padStart(2,"0"),p=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${a}-${o}-${p}`;let c=String(r.getHours()).padStart(2,"0"),T=String(r.getMinutes()).padStart(2,"0"),l=String(r.getSeconds()).padStart(2,"0");return`${a}-${o}-${p} ${c}:${T}:${l}`};function bt(e){let{db:t,tables:r,userTable:n,resolveUserId:a,encodeUserId:o,redis:p,cache:c,epochs:T}=e,{hub:l,internal:g,comment:m,label:_,hubLabel:A,userStatus:E}=r,J=e.externalSources??[],H=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],Q=H[0]??"\u4E0B\u66F8\u304D",S=e.logger??me(1,"[DailyReportService]");Ot({attachmentIdCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,attachmentThumbnailRenderer:e.attachmentThumbnailRenderer,attachmentMaxBytes:e.attachmentMaxBytes});let P=Object.freeze({idCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,thumbnailRenderer:qa(e.attachmentThumbnailRenderer),maxBytes:Ie("attachmentMaxBytes",e.attachmentMaxBytes,1,hr)}),V=i=>(0,Kr.runWithTransactionRetry)(s=>t.transaction(d=>s(()=>i(d))),e.transactionRetry),F="daily-report:ids",R=e.idsTtlMs??18e4,M="daily-report:ids:epoch",I="daily-report:business-date:",L=e.businessDateTtlMs??3e5,b="daily-report:date-epoch:",x="daily-report:detail-epoch:",O=`${e.streamKey??"daily-report:sse-stream"}:v2`,Y=e.streamMaxLen??1e4,v=i=>T.incrementEpoch(i),$=i=>Fr(l.sourceType,i),ae=(i,s)=>`${F}:user:${i}:st:${s}`,j=i=>`${F}:user:${i}:`,z=(i,s,d)=>`daily-report:date:${i}:user:${s}:st:${d}`,ee=(i,s)=>`daily-report:date:${i}:user:${s}:`,K=(i,s,d)=>`daily-report:detail:${i}:user:${s}:st:${d}`,X=(i,s)=>`daily-report:detail:${i}:user:${s}:`,k=async(i,s)=>{let d=await p?.getClient();if(!d){S.warn(`[SSE] Redis client unavailable (${s})`);return}let h=Date.now();try{await d.xAdd(O,"*",{data:JSON.stringify(i)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:Y}});let D=Date.now()-h;D>1e3&&S.warn(`[SSE] Slow publish (${s}): ${D}ms`)}catch(D){S.error(`[SSE] Redis publish failed (${s}):`,D)}},C=async()=>{try{let i=await p?.getClient();if(i===void 0)return null;let[s]=await i.xRevRange(O,"+","-",{COUNT:1});return s===void 0?null:s.id}catch(i){return S.error("[DailyReportService] SSE stream anchor read failed",i),null}},te=i=>i==null||i===""?null:/^\d+$/.test(i)?o(Number(i)):i,de=()=>{let i={};for(let s of J)i[`ext_${s.sourceType}`]=xe(s.table);return i},ie=i=>{let s=i;for(let d of J)s=s.leftJoin(d.table,(0,u.and)((0,u.eq)(l.sourceType,d.sourceType),(0,u.eq)(l.sourceIdNum,d.idColumn)));return s},ve=(i,s,d)=>{let{hub:h,internal:D}=s,B=h.summary,w=[],N=null,U=null,Z=null,G=null,re=null,oe=null,Pe=[],Te=J.find(W=>W.sourceType===h.sourceType),Le=Te?s[`ext_${Te.sourceType}`]:void 0;if(Te&&Le){let W=Te.mapRow(Le);W.content!==void 0&&(B=W.content),W.employeeName!==void 0&&(oe=W.employeeName),W.category!==void 0&&(N=W.category),W.creationCategory!==void 0&&(U=W.creationCategory),W.visitTimeFrom!==void 0&&(Z=W.visitTimeFrom),W.visitTimeTo!==void 0&&(G=W.visitTimeTo),W.customerName!==void 0&&(re=W.customerName),W.interviewers!==void 0&&(w=W.interviewers),W.externalComments!==void 0&&(Pe=W.externalComments)}else h.sourceType==="Internal"&&D&&(B=D.body);let ge=(s.labels??[]).map(W=>({id:W.id,name:W.name,color:W.color})),se=s.postedCommentRows??[],ne=be(i.commentable,h.sourceType),le=U?H.includes(U):!1,Tt=Me?.[0]??null;return le&&Tt&&!ge.some(W=>W.id===Tt)&&ge.push({id:Tt,name:Q,color:null}),{reportHubId:h.id,date:ce(h.businessDate,"YYYY-MM-DD"),author:s.creatorName??te(h.createdBy)??"",userId:h.userId?o(h.userId):"",sourceType:h.sourceType??"Internal",createdAt:ce(h.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:ce(h.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:te(h.updatedBy),employeeName:oe??s.creatorName??te(h.createdBy),category:N,creationCategory:U,visitTimeFrom:Z,visitTimeTo:G,customerName:re,interviewers:w,subject:h.title,content:B,externalComments:ne?Pe:[],isRead:s.isRead??!1,isStarred:s.isStarred??!1,labels:ge,postedComments:se.filter(W=>ne||d!==void 0&&W.userId===d).map(W=>({...W,userId:o(W.userId),isMine:d?W.userId===d:!1})),attachments:s.attachments}},Qe=async(i,s)=>{let d=(0,u.aliasedTable)(A,"draft_label"),h=await _e();return(await t.select({reportHubId:l.id,businessDate:l.businessDate,sourceType:l.sourceType}).from(l).leftJoin(d,(0,u.and)((0,u.eq)(d.hubId,l.id),(0,u.inArray)(d.labelId,h))).where((0,u.and)((0,u.isNull)(l.deletedAt),(0,u.or)((0,u.eq)(l.userId,s),(0,u.isNull)(l.userId),(0,u.isNull)(d.hubId)),$(i.visible))).orderBy((0,u.desc)(l.businessDate),(0,u.desc)(l.id))).map(B=>({...B,businessDate:ce(B.businessDate,"YYYY-MM-DD")}))},Xe=async(i,s,d)=>{let h=await qe(s);if(!h)return[];if(Ce(i.visible))return[];let D=(0,u.aliasedTable)(A,"draft_label"),B=await _e();return(await t.select({reportHubId:l.id,businessDate:l.businessDate,sourceType:l.sourceType}).top(d).from(l).leftJoin(D,(0,u.and)((0,u.eq)(D.hubId,l.id),(0,u.inArray)(D.labelId,B))).where((0,u.and)((0,u.isNull)(l.deletedAt),(0,u.or)((0,u.eq)(l.userId,h),(0,u.isNull)(l.userId),(0,u.isNull)(D.hubId)),$(i.visible))).orderBy((0,u.desc)(l.businessDate),(0,u.desc)(l.id))).map(N=>({...N,businessDate:ce(N.businessDate,"YYYY-MM-DD")}))},ln=async(i,s)=>{let d=await ie(t.select({hub:xe(l),internal:xe(g),creatorName:n.displayName,...de()}).from(l)).leftJoin(g,(0,u.eq)(l.id,g.hubId)).leftJoin(n,(0,u.eq)(l.userId,n.id)).where((0,u.and)((0,u.eq)(l.businessDate,u.sql`${s}`),(0,u.isNull)(l.deletedAt),$(i.visible))).orderBy((0,u.desc)(l.id)),h=await tt(d.map(D=>D.hub.id));return d.map(D=>ve(i,{...D,attachments:h.get(D.hub.id)??[]}))},un=i=>`${I}${i}`,Ze=new Map,qe=async i=>{if(!e.disableUserIdCache&&Ze.has(i))return Ze.get(i)??null;let s=await a(i);return s!==null&&!e.disableUserIdCache&&Ze.set(i,s),s},cn=async(i,s,{forceRefresh:d=!1,snapshot:h=!1,ttlMsOverride:D,onFetchStart:B}={})=>{let w=await qe(s);if(!w)return{items:[],streamAnchor:null};if(Ce(i.visible))return{items:[],streamAnchor:await C()};let N=ae(w,Je(i)),[U]=await c.getOrFetch({cacheKey:N,fetcher:async()=>{let Z=await C(),G=await Qe(i,w);return er(G)?[{items:G,streamAnchor:Z}]:(S.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)"),[{items:[...G].sort(at),streamAnchor:Z}])},onFetchStart:B,forceRefresh:d,snapshot:h,ttlMsOverride:D??R,epochKey:M,refreshAheadRatio:.5});if(U===void 0)throw new Error("[DailyReportService] ids cache returned no record");return U},dn=(i,s,{forceRefresh:d=!1,snapshot:h=!1,ttlMsOverride:D}={})=>{let B=ue(s);return B?Ce(i.visible)?Promise.resolve([]):c.getOrFetch({cacheKey:`${un(B)}:st:${Je(i)}`,fetcher:()=>ln(i,B),forceRefresh:d,snapshot:h,ttlMsOverride:D??L}):Promise.resolve([])},Me=null,et=async()=>(Me!==null||(Me=(await t.select({id:_.id}).from(_).where((0,u.inArray)(_.name,H)).orderBy(_.id)).map(s=>s.id)),Me),_e=async()=>{let i=await et();return i.length>0?i:[-1]},gt=async()=>{let i=await et();if(i.length===0)return null;let[s]=await t.select({id:_.id}).top(1).from(_).where((0,u.eq)(_.name,Q));return s?.id??i[0]},mn=(i,s)=>s!=null?"absent":i!=null?"present":"unknown",tt=async i=>{let s=new Map,d=r.attachment,h=P.idCodec;if(i.length===0||!d||!h)return s;let D=P.thumbnailRenderer!==void 0&&P.readAttachment!==void 0,B=await t.select({id:d.id,hubId:d.hubId,fileName:d.fileName,fileType:d.fileType,fileSize:d.fileSize,createdAt:d.createdAt,objectCheckedAt:d.objectCheckedAt,objectMissingAt:d.objectMissingAt}).from(d).where((0,u.inArray)(d.hubId,i)).orderBy((0,u.asc)(d.createdAt),(0,u.asc)(d.id));for(let w of B){let N=w.fileType?String(w.fileType):null,U=w.fileSize!=null?Number(w.fileSize):null,Z=mn(w.objectCheckedAt,w.objectMissingAt),G={id:h.encode(Number(w.id)),fileName:String(w.fileName),fileType:N,fileSize:U,createdAt:ce(w.createdAt,"YYYY-MM-DD HH:mm:ss"),state:Z,hasThumbnail:D&&Z!=="absent"&&dt({fileType:N,fileSize:U},P.maxBytes)},re=s.get(Number(w.hubId));re?re.push(G):s.set(Number(w.hubId),[G])}return s},pn=async(i,s,d)=>{let h=r.attachment;if(!h||Ce(i.visible))return null;let D=await _e(),B=(0,u.aliasedTable)(A,"draft_label");return(await t.select({fileName:h.fileName,filePath:h.filePath,fileType:h.fileType,fileSize:h.fileSize}).top(1).from(h).innerJoin(l,(0,u.eq)(l.id,h.hubId)).leftJoin(B,(0,u.and)((0,u.eq)(B.hubId,l.id),(0,u.inArray)(B.labelId,D))).where((0,u.and)((0,u.eq)(h.id,s),(0,u.isNull)(l.deletedAt),(0,u.or)((0,u.eq)(l.userId,d),(0,u.isNull)(B.hubId)),$(i.visible))))[0]??null},yn=async i=>{let s=r.attachment;if(!s)return;let d=new Date;try{await t.update(s).set({objectCheckedAt:d,objectMissingAt:d,updatedAt:d}).where((0,u.eq)(s.id,i))}catch(h){S.error("markAttachmentMissing failed",h)}},hn=async i=>{let s=r.attachment;if(!s)return;let d=new Date;try{await t.update(s).set({objectCheckedAt:d,objectMissingAt:null,updatedAt:d}).where((0,u.eq)(s.id,i))}catch(h){S.error("markAttachmentPresent failed",h)}},fn=async(i,s,d,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:B}={})=>{let w=await qe(d);if(!w)return[];let N=ue(s);if(!N)return[];if(Ce(i.visible))return[];let U=z(N,w,Je(i));return c.getOrFetch({cacheKey:U,fetcher:async()=>{let Z=await _e(),G=(0,u.aliasedTable)(A,"draft_label"),re=await ie(t.select({hub:xe(l),internal:xe(g),isRead:E.isRead,isStarred:E.isStarred,creatorName:n.displayName,...de()}).from(l)).leftJoin(g,(0,u.eq)(l.id,g.hubId)).leftJoin(E,(0,u.and)((0,u.eq)(l.id,E.hubId),(0,u.eq)(E.userId,w))).leftJoin(G,(0,u.and)((0,u.eq)(G.hubId,l.id),(0,u.inArray)(G.labelId,Z))).leftJoin(n,(0,u.eq)(l.userId,n.id)).where((0,u.and)((0,u.eq)(l.businessDate,u.sql`${N}`),(0,u.isNull)(l.deletedAt),(0,u.or)((0,u.eq)(l.userId,w),(0,u.isNull)(G.hubId)),$(i.visible))).orderBy((0,u.desc)(l.id));if(re.length===0)return[];let oe=re.map(ne=>ne.hub.id),Pe=await t.select({hubId:A.hubId,id:_.id,name:_.name,color:_.color}).from(A).innerJoin(_,(0,u.eq)(A.labelId,_.id)).where((0,u.inArray)(A.hubId,oe)),Te=await t.select({hubId:m.hubId,id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,u.eq)(m.userId,n.id)).where((0,u.inArray)(m.hubId,oe)).orderBy((0,u.asc)(m.createdAt)),Le=await tt(oe),ge=new Map,se=new Map;for(let ne of Pe){let le=ge.get(ne.hubId);le||(le=[],ge.set(ne.hubId,le)),le.push({id:ne.id,name:ne.name,color:ne.color})}for(let ne of Te){let le=se.get(ne.hubId);le||(le=[],se.set(ne.hubId,le)),le.push({id:ne.id,content:ne.body,createdAt:ce(ne.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ne.userId,userName:ne.userName||""})}return re.map(ne=>{let le=ne.hub.id;return ve(i,{...ne,attachments:Le.get(le)??[],labels:ge.get(le)||[],postedCommentRows:se.get(le)||[]},w)})},forceRefresh:h,snapshot:D,ttlMsOverride:B??L,epochKey:`${b}${N}`})},Ye=async(i,s,d,{forceRefresh:h=!1,snapshot:D=!1,ttlMsOverride:B}={})=>{if(Ce(i.visible))return null;let w=K(s,d,Je(i));return(await c.getOrFetch({cacheKey:w,fetcher:async()=>{let U=await _e(),Z=(0,u.aliasedTable)(A,"draft_label"),G=await ie(t.select({hub:xe(l),internal:xe(g),isRead:E.isRead,isStarred:E.isStarred,creatorName:n.displayName,...de()}).from(l)).leftJoin(g,(0,u.eq)(l.id,g.hubId)).leftJoin(E,(0,u.and)((0,u.eq)(l.id,E.hubId),(0,u.eq)(E.userId,d))).leftJoin(Z,(0,u.and)((0,u.eq)(Z.hubId,l.id),(0,u.inArray)(Z.labelId,U))).leftJoin(n,(0,u.eq)(l.userId,n.id)).where((0,u.and)((0,u.eq)(l.id,s),(0,u.isNull)(l.deletedAt),(0,u.or)((0,u.eq)(l.userId,d),(0,u.isNull)(Z.hubId)),$(i.visible)));if(G.length===0)return[];let re=G[0].hub.id,oe=await t.select({id:_.id,name:_.name,color:_.color}).from(A).innerJoin(_,(0,u.eq)(A.labelId,_.id)).where((0,u.eq)(A.hubId,re)),Pe=await t.select({id:m.id,body:m.body,createdAt:m.createdAt,userId:m.userId,userName:n.displayName}).from(m).leftJoin(n,(0,u.eq)(m.userId,n.id)).where((0,u.eq)(m.hubId,re)).orderBy((0,u.asc)(m.createdAt)),Te=await tt([re]),Le=oe.map(se=>({id:se.id,name:se.name,color:se.color})),ge=Pe.map(se=>({id:se.id,content:se.body,createdAt:ce(se.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:se.userId,userName:se.userName||""}));return[ve(i,{...G[0],attachments:Te.get(re)??[],labels:Le,postedCommentRows:ge},d)]},forceRefresh:h,snapshot:D,ttlMsOverride:B??L,epochKey:`${x}${s}`}))[0]??null},bn=async(i,s,d,h={})=>{let D=await qe(d);return D?Ye(i,s,D,h):null},gn=async(i,s)=>{let d=await _e(),h=(0,u.aliasedTable)(A,"draft_label"),[D]=await t.select({sourceType:l.sourceType,deletedAt:l.deletedAt}).top(1).from(l).leftJoin(h,(0,u.and)((0,u.eq)(h.hubId,l.id),(0,u.inArray)(h.labelId,d))).where((0,u.and)((0,u.eq)(l.id,i),(0,u.or)((0,u.eq)(l.userId,s),(0,u.isNull)(h.hubId))));return D??null},Rt=async(i,s,d)=>{let h=await gn(s,d);if(!h||h.deletedAt||!be(i.visible,h.sourceType))throw new Error("Not Found")},Rn=async(i,s,d,h,D,B)=>{await Rt(i,d,s);let w=await t.select().top(1).from(E).where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,s))),N;if(w.length>0?w[0].isStarred!==D?N=(await t.update(E).set({isStarred:D,updatedAt:new Date,updatedBy:String(s)}).output().where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,s))))[0]:N=w[0]:N=(await t.insert(E).output().values({hubId:d,userId:s,isStarred:D,isRead:!1,createdAt:new Date,createdBy:String(s),updatedAt:new Date,updatedBy:String(s)}))[0],h){let U=ue(h);U&&(c.invalidatePrefix(ee(U,s)),await v(`${b}${U}`))}return c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(X(d,s)),await v(`${x}${d}`),await k(it.parse({type:"status-update",reportHubId:d,recipientRawUserId:s,statusType:"star",value:D,clientTempId:B}),"setStarStatus"),N},Sn=async(i,s,d,h,D,B)=>{await Rt(i,d,s);let w=await t.select().top(1).from(E).where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,s))),N;if(w.length>0?w[0].isRead!==D?N=(await t.update(E).set({isRead:D,updatedAt:new Date,updatedBy:String(s)}).output().where((0,u.and)((0,u.eq)(E.hubId,d),(0,u.eq)(E.userId,s))))[0]:N=w[0]:N=(await t.insert(E).output().values({hubId:d,userId:s,isRead:D,isStarred:!1,createdAt:new Date,createdBy:String(s),updatedAt:new Date,updatedBy:String(s)}))[0],h){let U=ue(h);U&&(c.invalidatePrefix(ee(U,s)),await v(`${b}${U}`))}return c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(X(d,s)),await v(`${x}${d}`),await k(it.parse({type:"status-update",reportHubId:d,recipientRawUserId:s,statusType:"read",value:D,clientTempId:B}),"setReadStatus"),N},Gt=async(i,s)=>{if(s===null)return;let d=await _e(),[h]=await t.select({hubId:A.hubId}).top(1).from(A).where((0,u.and)((0,u.eq)(A.hubId,i),(0,u.inArray)(A.labelId,d)));return h?s:void 0},Tn=async(i,s,d,h,D,B)=>{let[w]=await t.select({sourceType:l.sourceType,deletedAt:l.deletedAt,userId:l.userId}).top(1).from(l).where((0,u.eq)(l.id,d));if(!w||w.deletedAt)throw new Error("Not Found");if(await Rt(i,d,s),!be(i.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 N=await Gt(d,w.userId),[U]=await t.insert(m).output().values({hubId:d,userId:s,body:h,createdAt:new Date,createdBy:String(s),updatedAt:new Date,updatedBy:String(s)}),[Z]=await t.select({displayName:n.displayName}).top(1).from(n).where((0,u.eq)(n.id,s)),G=Z?.displayName??"";if(D){let oe=ue(D);oe&&(c.invalidatePrefix(`daily-report:date:${oe}:user:`),await v(`${b}${oe}`))}c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(`daily-report:detail:${d}:user:`),await v(`${x}${d}`);let re={id:U.id,userId:o(U.userId),userName:G,content:U.body,createdAt:ce(U.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await k(Ct.parse({type:"comment-add",reportHubId:d,comment:re,clientTempId:B,recipientRawUserId:N,sourceType:w.sourceType}),"addComment"),re},An=async(i,s)=>await i.select().top(1).from(m).where((0,u.eq)(m.id,s)),Dn=async(i,s,d,h,D,B)=>{let w=await An(t,h);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==d)throw new Error("Not Found");let[N]=await t.select({userId:l.userId,sourceType:l.sourceType}).top(1).from(l).where((0,u.eq)(l.id,w[0].hubId));if(!(N&&be(i.visible,N.sourceType)))throw new Error("Not Found");if(w[0].userId!==s)throw new Error("Unauthorized");let U=await Gt(d,N.userId);if(await t.delete(m).where((0,u.eq)(m.id,h)),D){let Z=ue(D);Z&&(c.invalidatePrefix(`daily-report:date:${Z}:user:`),await v(`${b}${Z}`))}c.invalidate(`daily-report:detail:${d}`),c.invalidatePrefix(`daily-report:detail:${d}:user:`),await v(`${x}${d}`),await k(xt.parse({type:"comment-delete",reportHubId:d,commentId:h,clientTempId:B,recipientRawUserId:U,sourceType:N?.sourceType}),"deleteComment")},wn=async(i,s,d)=>{S.info("createDailyReport called",{userId:i,businessDate:s});let[h]=await t.select({displayName:n.displayName}).from(n).where((0,u.eq)(n.id,i)),D=h?.displayName??o(i);try{let B=await V(async U=>{S.info("Starting transaction");let Z=`internal-temp-${Date.now()}-${Math.random()}`,[G]=await U.insert(l).output().values({sourceType:"Internal",sourceId:Z,businessDate:new Date(s),userId:i,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)});await U.update(l).set({sourceId:String(G.id)}).where((0,u.eq)(l.id,G.id)),S.info("Hub created",G),await U.insert(g).values({hubId:G.id,body:"",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)}),S.info("Internal created"),S.info("Calling getDraftLabelId");let re=await gt();S.info("draftLabelId",re);let oe=[];return re&&(await U.insert(A).values({hubId:G.id,labelId:re,createdAt:new Date,createdBy:String(i)}),oe.push({id:re,name:Q,color:null})),S.info("Label assigned"),{reportHubId:G.id,date:s,createdAt:ce(G.createdAt,"YYYY-MM-DD HH:mm:ss"),author:D,userId:o(i),sourceType:"Internal",employeeName:D,updatedBy:o(i),updatedAt:ce(G.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:G.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:oe,postedComments:[],attachments:[]}}),w=ue(s);w&&c.invalidatePrefix(ee(w,i)),c.invalidatePrefix(I),c.invalidatePrefix(j(i)),await v(M),w&&await v(`${b}${w}`);let N=await Ye(ye.unrestricted("post-write self read: the writer always sees the row they just wrote"),B.reportHubId,i,{forceRefresh:!0});if(N){let U=await et(),Z=N.labels.some(G=>U.includes(G.id));await k(vt.parse({type:"report-create",reportHubId:N.reportHubId,report:N,clientTempId:d,recipientRawUserId:Z?i:void 0}),"createDailyReport")}return N??B}catch(B){throw S.error("Error in createDailyReport",B),B}},rt=async(i,s)=>await i.select().top(1).from(l).where((0,u.eq)(l.id,s)),St=async(i,s,d)=>{await i.update(l).set(d).where((0,u.eq)(l.id,s))},Wt=async(i,s,d)=>{await i.update(g).set(d).where((0,u.eq)(g.hubId,s))},Jt=async(i,s,d)=>{await i.delete(A).where((0,u.and)((0,u.eq)(A.hubId,s),(0,u.eq)(A.labelId,d)))};return{streamKey:O,streamMaxLen:Y,attachmentDelivery:P,clearCache:async()=>{c.clearAll(),Ze.clear(),Me=null,T&&await v(M),S.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(i,s)=>{c.invalidatePrefix(I),c.invalidatePrefix(F),await v(M);for(let d of new Set(i))c.invalidatePrefix(`daily-report:detail:${d}:user:`),await v(`${x}${d}`);for(let d of new Set(s)){let h=ue(d);h&&await v(`${b}${h}`)}},getUserIdByExternalId:qe,getDailyReportIdsByExternalId:cn,getDailyReportIdsFirstPageByExternalId:Xe,readSseStreamAnchor:C,getDailyReportsByBusinessDate:dn,getDailyReportsByBusinessDateByExternalId:fn,getDailyReportDetailById:Ye,getDailyReportDetailByIdByExternalId:bn,getDraftLabelId:gt,getAttachmentsByHubIds:tt,getAttachmentForUser:pn,markAttachmentMissing:yn,markAttachmentPresent:hn,setStarStatus:Rn,setReadStatus:Sn,addComment:Tn,deleteComment:Dn,createDailyReport:wn,updateDailyReport:async(i,s,d,h)=>{let D=await rt(t,i);if(!D.length||D[0].deletedAt)throw new Error("Not Found");if(D[0].userId!==s)throw new Error("Unauthorized");await V(async N=>{d.title!==void 0&&await St(N,i,{title:d.title,updatedAt:new Date,updatedBy:String(s)}),d.content!==void 0&&await Wt(N,i,{body:d.content,updatedAt:new Date,updatedBy:String(s)})}),c.invalidate(`daily-report:detail:${i}`),c.invalidatePrefix(`daily-report:detail:${i}:user:`),c.invalidatePrefix(I),await v(`${x}${i}`);let B=ue(ce(D[0].businessDate,"YYYY-MM-DD"));B&&(c.invalidatePrefix(`daily-report:date:${B}:user:`),await v(`${b}${B}`));let w=await Ye(ye.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,s,{forceRefresh:!0});if(w){let N=await et(),U=w.labels.some(Z=>N.includes(Z.id));await k(Mt.parse({type:"report-update",reportHubId:w.reportHubId,report:w,clientTempId:h,recipientRawUserId:U?s:void 0}),"updateDailyReport")}},publishDailyReport:async(i,s,d)=>{let h=await rt(t,i);if(!h.length)throw new Error("Not Found");if(h[0].userId!==s)throw new Error("Unauthorized");let D=await gt();if(!D)return null;if(await Jt(t,i,D),c.invalidatePrefix(`daily-report:detail:${i}:user:`),c.invalidatePrefix(I),c.invalidatePrefix(F),await v(M),h[0].businessDate){let N=ue(ce(h[0].businessDate,"YYYY-MM-DD"));N&&await v(`${b}${N}`)}let B=ue(ce(h[0].businessDate,"YYYY-MM-DD"));B&&c.invalidatePrefix(ee(B,s));let w=await Ye(ye.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,s,{forceRefresh:!0});return w&&await k(Pt.parse({type:"report-publish",reportHubId:w.reportHubId,report:w,clientTempId:d}),"publishDailyReport"),w??null},deleteDailyReport:async(i,s,d)=>{let h=await rt(t,i);if(!h.length||h[0].deletedAt)throw new Error("Not Found");if(h[0].userId!==s)throw new Error("Unauthorized");if(await St(t,i,{deletedAt:new Date,deletedBy:String(s),updatedAt:new Date,updatedBy:String(s)}),c.invalidatePrefix(`daily-report:detail:${i}:user:`),c.invalidatePrefix(I),c.invalidatePrefix(F),await v(M),h[0].businessDate){let D=ue(ce(h[0].businessDate,"YYYY-MM-DD"));D&&await v(`${b}${D}`)}await k(Lt.parse({type:"report-delete",reportHubId:i,clientTempId:d,sourceType:h[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:rt,updateDailyReportHub:St,updateDailyReportInternal:Wt,deleteDailyReportLabel:Jt}}var Ya=me(1,"[DailyReportExternalSource]"),Qr=(e,t,r,n=Ya)=>{if(!e)return[];try{let a=JSON.parse(e);return Array.isArray(a)?a.map(r).filter(o=>o!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(a){return n.warn(`Failed to parse ${t}:`,a),[]}};var Ke=require("drizzle-orm"),y=require("drizzle-orm/mssql-core");function Xr(e,t){let r=(0,y.mssqlSchema)(e),n=t.userTable,a=r.table("DailyReportHub",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),sourceType:(0,y.nvarchar)("source_type",{length:20}).notNull(),sourceId:(0,y.nvarchar)("source_id",{length:100}).notNull(),sourceIdNum:(0,y.bigint)("source_id_num",{mode:"number"}).generatedAlwaysAs(Ke.sql`TRY_CAST(source_id AS BIGINT)`),businessDate:(0,y.date)("business_date"),userId:(0,y.bigint)("user_id",{mode:"number"}),title:(0,y.nvarchar)("title",{length:200}),summary:(0,y.nvarchar)("summary",{length:"max"}),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull(),deletedAt:(0,y.datetime2)("deleted_at"),deletedBy:(0,y.nvarchar)("deleted_by",{length:50})},m=>[(0,y.primaryKey)({name:`${e}_DailyReportHub_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportHub_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,y.index)(`${e}_DailyReportHub_business_date_index`).on(m.businessDate),(0,y.index)(`${e}_DailyReportHub_updated_at_index`).on(m.updatedAt),(0,y.index)(`${e}_DailyReportHub_source_index`).on(m.sourceType,m.sourceId),(0,y.index)(`${e}_DailyReportHub_user_id_index`).on(m.userId),(0,y.index)(`${e}_DailyReportHub_business_date_id_index`).on((0,Ke.desc)(m.businessDate),(0,Ke.desc)(m.id)),(0,y.index)(`${e}_DailyReportHub_deleted_at_index`).on(m.deletedAt)]),o=r.table("DailyReportInternal",{hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),body:(0,y.nvarchar)("body",{length:"max"}),metadata:(0,y.nvarchar)("metadata",{length:"max"}),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportInternal_pk`,columns:[m.hubId]}),(0,y.foreignKey)({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]})]),p=r.table("DailyReportComment",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,y.bigint)("user_id",{mode:"number"}).notNull(),body:(0,y.nvarchar)("body",{length:"max"}).notNull(),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportComment_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportComment_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportComment_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]}),(0,y.index)(`${e}_DailyReportComment_hub_id_index`).on(m.hubId)]),c=r.table("DailyReportLabel",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),userId:(0,y.bigint)("user_id",{mode:"number"}),name:(0,y.nvarchar)("name",{length:50}).notNull(),color:(0,y.nvarchar)("color",{length:20}),sortOrder:(0,y.int)("sort_order"),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportLabel_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportLabel_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),T=r.table("DailyReportHub_Label",{hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),labelId:(0,y.bigint)("label_id",{mode:"number"}).notNull(),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportHub_Label_pk`,columns:[m.hubId,m.labelId]}),(0,y.foreignKey)({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[m.labelId],foreignColumns:[c.id]})]),l=r.table("DailyReportUserStatus",{hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),userId:(0,y.bigint)("user_id",{mode:"number"}).notNull(),isRead:(0,y.bit)("is_read").default(!1).notNull(),isStarred:(0,y.bit)("is_starred").default(!1).notNull(),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportUserStatus_pk`,columns:[m.hubId,m.userId]}),(0,y.foreignKey)({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[m.userId],foreignColumns:[n.id]})]),g=r.table("DailyReportAttachment",{id:(0,y.bigint)("id",{mode:"number"}).identity().notNull(),hubId:(0,y.bigint)("hub_id",{mode:"number"}).notNull(),uploadedBy:(0,y.bigint)("uploaded_by",{mode:"number"}),sourceKey:(0,y.nvarchar)("source_key",{length:200}).notNull(),fileName:(0,y.nvarchar)("file_name",{length:255}).notNull(),filePath:(0,y.nvarchar)("file_path",{length:"max"}).notNull(),fileType:(0,y.nvarchar)("file_type",{length:100}),fileSize:(0,y.bigint)("file_size",{mode:"number"}),objectCheckedAt:(0,y.datetime2)("object_checked_at"),objectMissingAt:(0,y.datetime2)("object_missing_at"),createdAt:(0,y.datetime2)("created_at").notNull(),createdBy:(0,y.nvarchar)("created_by",{length:50}).notNull(),updatedAt:(0,y.datetime2)("updated_at").notNull(),updatedBy:(0,y.nvarchar)("updated_by",{length:50}).notNull()},m=>[(0,y.primaryKey)({name:`${e}_DailyReportAttachment_pk`,columns:[m.id]}),(0,y.foreignKey)({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[m.hubId],foreignColumns:[a.id]}),(0,y.foreignKey)({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[m.uploadedBy],foreignColumns:[n.id]}),(0,y.uniqueIndex)(`${e}_DailyReportAttachment_source_unique`).on(m.hubId,m.sourceKey),(0,y.index)(`${e}_DailyReportAttachment_hub_id_index`).on(m.hubId,m.createdAt)]);return{hub:a,internal:o,comment:p,attachment:g,label:c,hubLabel:T,userStatus:l}}var Va=5e7,zt=2e8,za=1,jt=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),ja=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Zr=75,en=4,tn="#ffffff",Ga=1,Wa={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Ja=[/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/],Vt=Object.freeze({ok:!1,reason:"failed"}),rn=Object.freeze({ok:!1,reason:"unsupported"}),nn=(e,t)=>{switch(t){case"jpeg":{let r=Ut(e);return r===null?null:{layout:r.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Ar(r)}}case"png":{let r=wr(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=_r(e);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},an=(e,t)=>{let r=ja.get(t.depth);if(r===void 0)return null;let n=t.channels*r,a=jt,o=a.wholeImageBuffer[e.layout];return(o.kind==="none"?0:o.kind==="decoded-raster"?t.width*t.height*n:o.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*o.bytesPerPixel)+a.pipelineRows*t.width*n+a.fixedBytes},on=(e,t,r)=>{let n=nn(e,t);return n===null?null:an(n,r)},Ka=e=>e!==null&&e<=zt,Qa=e=>{let t=e instanceof Error?e.message:"";return Ja.some(r=>r.test(t))?"failed":"unsupported"},sn=e=>{e.cache(!1),e.concurrency(za),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Wa)});let t=async(n,a,o,p,c)=>{let T=nn(n,a);if(T===null)return rn;try{let l=e(n,{limitInputPixels:Va,animated:!1});if(!Ka(an(T,await l.metadata())))return rn;if(c.aborted)return Vt;let g=await l.rotate().resize({width:o,height:p,fit:"inside",withoutEnlargement:!0}).flatten({background:tn}).webp({quality:Zr,effort:en}).toBuffer();return{ok:!0,bytes:new Uint8Array(g),contentType:"image/webp"}}catch(l){return{ok:!1,reason:Qa(l)}}},r=async(n,{format:a,maxWidth:o,maxHeight:p,signal:c})=>{if(c.aborted)return Vt;let T=await t(n,a,o,p,c);return c.aborted?Vt:T};return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Zr}-e${en}/flatten-${tn}/v${Ga}`,render:r}};function Xa(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=nt(e.redis),r=new ke({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=bt({...e,cache:r,epochs:t}),a=new $e({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),o=ft({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes,redis:e.redis,sseReader:a,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:a,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(p=>p.sourceType)])],...o}}0&&(module.exports={DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,DAILY_REPORT_SSE_CATCH_UP_BATCH,DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,DailyReportSseReader,DailyReportViewerScope,SqlResultCache,createDailyReportHandlers,createDailyReportServer,createDailyReportService,createEpochStore,createSharpThumbnailRenderer,defineDailyReportSchema,generateETag,isStreamIdLte,jsonResponseWithETag,predictSharpThumbnailWorkingSetBytes,transformJsonArray});
|
|
5
5
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|
package/dist/server.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var Xt=e=>{throw TypeError(e)};var Zt=(e,t,r)=>t.has(e)||Xt("Cannot "+r);var Qe=(e,t,r)=>(Zt(e,t,"read from private field"),r?r.call(e):t.get(e)),It=(e,t,r)=>t.has(e)?Xt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Et=(e,t,r,n)=>(Zt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var Ct=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),Xe=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.invalidate=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,a=this.buckets.get(n);if(!a)return;let l=t.ttlMsOverride??this.config.defaultTtlMs;if(l-(a.expireAt-Date.now())<l*r||this.inFlight.has(n))return;let u;u=(async()=>{let R=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,s=await t.fetcher();return this.inFlight.get(n)===u&&this.buckets.set(n,{records:s,expireAt:Date.now()+l,epoch:R}),s})(),this.inFlight.set(n,u),u.catch(()=>{}).finally(()=>{this.inFlight.get(n)===u&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:a}=t,l=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&l&&l.expireAt>Date.now())if(t.epochKey){let u=await this.epochStore.getEpoch(t.epochKey);if(u===null||l.epoch===u)return this.maybeRefreshAhead(t),a?l.records.map(R=>structuredClone(R)):l.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),a?l.records.map(u=>structuredClone(u)):l.records;if(!n&&this.inFlight.has(r)){let u=await this.inFlight.get(r);return a?u.map(R=>structuredClone(R)):u}let m;m=(async()=>{let u=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let R=await t.fetcher();if(n||this.inFlight.get(r)===m){let s=Date.now()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:R,expireAt:s,epoch:u}),this.buckets.size>500&&this.cleanExpired()}return R})(),n||this.inFlight.set(r,m);try{let u=await m;return a?u.map(R=>structuredClone(R)):u}finally{this.inFlight.get(r)===m&&this.inFlight.delete(r)}};this.flush=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=Date.now();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};import{systemSseRuntime as xa}from"@aiquants/sse";import{createSseResponse as va,readLastEventId as Ma,startSseHeartbeat as La,terminalStreamResponse as Pa}from"@aiquants/sse/server";var En=/^\d{4}-\d{2}-\d{2}$/,Cn=/^\d{4}\/\d{2}\/\d{2}$/,er=e=>e<10?`0${e}`:`${e}`,tr=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=er(e.getMonth()+1),n=er(e.getDate());return`${t}-${r}-${n}`};var me=e=>{if(e==null)return null;if(e instanceof Date)return tr(e);let t=e.trim();if(t==="")return null;if(En.test(t))return t;if(Cn.test(t))return t.replaceAll("/","-");let r=new Date(t);return tr(r)};var xt=e=>{let t=2166136261,r=-624069552;for(let n of e){let a=n.reportHubId;t^=a&255,t=Math.imul(t,16777619),t^=a>>>8&255,t=Math.imul(t,16777619),t^=a>>>16&255,t=Math.imul(t,16777619),t^=a>>>24&255,t=Math.imul(t,16777619),r^=a>>>24&255,r=Math.imul(r,16777619),r^=a>>>16&255,r=Math.imul(r,16777619),r^=a>>>8&255,r=Math.imul(r,16777619),r^=a&255,r=Math.imul(r,16777619);let l=n.businessDate;if(l===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let m=0;m<l.length;m++){let u=l.charCodeAt(m);t^=u&255,t=Math.imul(t,16777619),r^=u&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},dt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,rr=e=>{for(let t=1;t<e.length;t++)if(dt(e[t-1],e[t])>0)return!1;return!0};var nr=(e,t)=>{let r=e.findIndex(n=>dt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var fe=(e,t,r=console)=>{let n=a=>typeof a=="string"?[`${t} ${a}`]:[t,a];return{debug:(a,...l)=>{e<=0&&r.debug(...n(a),...l)},info:(a,...l)=>{e<=1&&r.info(...n(a),...l)},warn:(a,...l)=>{e<=2&&r.warn(...n(a),...l)},error:(a,...l)=>{e<=3&&r.error(...n(a),...l)}}};import{z as y}from"zod";var ar=15e3,ir="lastEventId",xn=/^\d{1,15}-\d{1,15}$/,or=e=>xn.test(e),vn=y.object({name:y.string().nullish(),affiliation:y.string().nullish()}),Mn=y.object({name:y.string().nullish(),text:y.string().nullish(),color:y.string().nullish()}),Ln=y.object({id:y.number(),name:y.string().nullish(),color:y.string().nullish()}),sr=y.object({id:y.number(),userId:y.string().nullish(),userName:y.string().nullish(),content:y.string().nullish(),createdAt:y.string().nullish(),isMine:y.boolean()}),Pn=y.object({id:y.string(),fileName:y.string(),fileType:y.string().nullable(),fileSize:y.number().nullable(),createdAt:y.string().nullable(),state:y.enum(["present","absent","unknown"]),hasThumbnail:y.boolean().default(!1)}),vt=y.object({reportHubId:y.number(),date:y.string().nullish(),createdAt:y.string().nullish(),author:y.string().nullish(),userId:y.string().nullish(),sourceType:y.string().nullish(),employeeName:y.string().nullish(),updatedBy:y.string().nullish(),updatedAt:y.string().nullish(),category:y.string().nullish(),creationCategory:y.string().nullish(),visitTimeFrom:y.string().nullish(),visitTimeTo:y.string().nullish(),customerName:y.string().nullish(),interviewers:y.array(vn),subject:y.string().nullish(),content:y.string().nullish(),externalComments:y.array(Mn),isRead:y.boolean(),isStarred:y.boolean(),labels:y.array(Ln),postedComments:y.array(sr),attachments:y.array(Pn).default([])}),kn=y.object({type:y.literal("connected")}),mt=y.object({type:y.literal("status-update"),reportHubId:y.number(),statusType:y.enum(["star","read"]),value:y.boolean(),clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Mt=y.string().optional(),Lt=y.object({type:y.literal("comment-add"),reportHubId:y.number(),comment:sr,clientTempId:y.string(),recipientRawUserId:y.number().optional(),sourceType:Mt}),Pt=y.object({type:y.literal("comment-delete"),reportHubId:y.number(),commentId:y.number(),clientTempId:y.string(),recipientRawUserId:y.number().optional(),sourceType:Mt}),kt=y.object({type:y.literal("report-create"),reportHubId:y.number(),report:vt,clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Nt=y.object({type:y.literal("report-update"),reportHubId:y.number(),report:vt,clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Ot=y.object({type:y.literal("report-publish"),reportHubId:y.number(),report:vt,clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Bt=y.object({type:y.literal("report-delete"),reportHubId:y.number(),clientTempId:y.string(),sourceType:Mt}),lr=y.discriminatedUnion("type",[kn,mt,Lt,Pt,kt,Nt,Ot,Bt]);var Ut=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),ur=e=>Object.hasOwn(Ut,e);var Nn="download",On="thumbnail",Bn="1";var cr=e=>{let t=e.getAll(On),r=e.getAll(Nn);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&ur(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Bn?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var dr=(e,t)=>(r,n)=>{let a=n?"markAttachmentPresent":"markAttachmentMissing";e[a](r).catch(l=>{t.error(`${a} failed attachment=${r} message=${l instanceof Error?l.message:"unknown"}`)})};var pt=6e4/1e3,yt=5e3/1e3,mr=(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},pr=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),$n=/^[\x20-\x7E]+$/,Hn=/^[\w.+-]+\/[\w.+-]+/,$t=e=>e&&$n.test(e)&&Hn.test(e)?e:null,yr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),hr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),ht=e=>{switch(e){case"not_found":case"denied":case"invalid_path":return 404;case"too_large":return 413;default:return 502}},fr={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable"},Fe="Attachment request failed";var Fn=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,qe=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Fn(r)}`),ft=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var br=32*1024*1024,qn=60,Yn=4,Vn=120,zn=2,jn=8*1024*1024,Re=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw qe(e,`an integer >= ${r}`,t)},Me=(e,t,r,n)=>t===void 0?n:Re(e,t,r),Gn=[["attachmentThumbnailRenderer",["readAttachment","attachmentIdCodec"]],["readAttachment",["attachmentIdCodec"]],["attachmentIdCodec",["readAttachment"]],["attachmentMaxBytes",["readAttachment"]],["attachmentRateLimitPerMinute",["readAttachment"]],["attachmentConcurrency",["readAttachment"]],["attachmentThumbnailRateLimitPerMinute",["attachmentThumbnailRenderer"]],["attachmentThumbnailConcurrency",["attachmentThumbnailRenderer"]],["attachmentThumbnailCacheBytes",["attachmentThumbnailRenderer"]]],Ht=e=>{for(let[t,r]of Gn){if(e[t]===void 0)continue;let n=r.find(a=>e[a]===void 0);if(n!==void 0)throw ft(n,`injected when ${t} is given`)}},gr=(e,t)=>(Ht({attachmentIdCodec:t.idCodec,readAttachment:t.readAttachment,attachmentThumbnailRenderer:t.thumbnailRenderer,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes}),Object.freeze({originalRateLimitPerMinute:Me("attachmentRateLimitPerMinute",e.attachmentRateLimitPerMinute,1,qn),originalConcurrency:Me("attachmentConcurrency",e.attachmentConcurrency,1,Yn),thumbnailRateLimitPerMinute:Me("attachmentThumbnailRateLimitPerMinute",e.attachmentThumbnailRateLimitPerMinute,1,Vn),thumbnailConcurrency:Me("attachmentThumbnailConcurrency",e.attachmentThumbnailConcurrency,1,zn),thumbnailCacheBytes:Me("attachmentThumbnailCacheBytes",e.attachmentThumbnailCacheBytes,0,jn)}));var bt=e=>{let t=Re("limit",e.limit,1),r=e.queue===null?null:{max:Re("queue.max",e.queue.max,0),maxPerOwner:Re("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:Re("queue.maxWaitMs",e.queue.maxWaitMs,1)},n=0,a=[],l=new Map,m=(s,f)=>{let d=(l.get(s)??0)+f;d<=0?l.delete(s):l.set(s,d)},u=()=>{for(;n<t;){let s=a.shift();if(!s)return;m(s.owner,-1),n+=1,s.grant(R())}},R=()=>{let s=!1;return()=>{s||(s=!0,n-=1,u())}};return{acquire:(s,f)=>{if(f.aborted)return Promise.resolve(null);if(n<t)return n+=1,Promise.resolve(R());if(r===null||a.length>=r.max||(l.get(s)??0)>=r.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:d}=r,D=S=>{let I=()=>{let g=a.indexOf(K);g<0||(a.splice(g,1),m(s,-1),$(),S(null))},W=setTimeout(I,d);W.unref?.();let $=()=>{clearTimeout(W),f.removeEventListener("abort",I)},K={owner:s,grant:g=>{$(),S(g)}};a.push(K),m(s,1),f.addEventListener("abort",I,{once:!0})};return new Promise(D)}}};var Wn=1024,Ze=e=>{Re("limitPerMinute",e,1);let t=new Map,r=(m,u)=>{u<=m.lastRefillMs||(m.tokens=Math.min(e,m.tokens+(u-m.lastRefillMs)*e/6e4),m.lastRefillMs=u)},n=(m,u)=>{let R=t.get(m);R&&t.delete(m);let s=R??{tokens:e,lastRefillMs:u,deniedSinceAdmission:0};r(s,u),t.set(m,s);for(let f of t.keys()){if(t.size<=Wn)break;t.delete(f)}return s},a=m=>{if(m.tokens<1)return null;m.tokens-=1;let u=Math.max(0,m.deniedSinceAdmission-1);return m.deniedSinceAdmission=0,{allowed:!0,suppressedDenials:u}},l=m=>(m.deniedSinceAdmission+=1,{allowed:!1,firstDenial:m.deniedSinceAdmission===1});return{consume:(m,u)=>{let R=n(m,u);return a(R)??l(R)},refund:(m,u,R)=>{let s=t.get(m);s&&(r(s,u),s.tokens=Math.min(e,s.tokens+R))}}};var Jn=12e4,Kn=(e,t,r)=>{let n=setTimeout(t,r);n.unref?.();let a=()=>{clearTimeout(n),t()},l=!1;return new ReadableStream({pull(m){if(l){m.close(),a();return}l=!0,m.enqueue(e)},cancel(){a()}})},Rr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:l}=e,m=t.attachmentDelivery,u=Ze(e.rateLimitPerMinute),R=bt({limit:e.concurrency,queue:null});return async s=>{let{request:f,delivery:d,attachmentId:D,internalUserId:S,readAttachment:I,cookie:W,fail:$}=s,K=m.maxBytes,g=u.consume(S,Date.now());if(!g.allowed)return g.firstDenial&&a.warn(`429 attachment=${D} viewer=${S} reason=rate_limit`),$(429,"Too many requests",{"Retry-After":String(pt)});g.suppressedDenials>0&&a.warn(`rate_limit_suppressed count=${g.suppressedDenials} viewer=${S}`);let M=await n(f),Y=await t.getAttachmentForUser(M,D,S);if(!Y)return a.warn(`404 attachment=${D} viewer=${S} reason=not_visible`),$(404,"Attachment not found");if(Y.fileSize!=null&&Y.fileSize>K)return a.warn(`413 attachment=${D} viewer=${S} reason=db_size`),$(413,"Attachment too large");let H=await R.acquire(S,f.signal);if(!H)return f.signal.aborted?(a.info(`503 attachment=${D} viewer=${S} reason=aborted`),$(503,"Attachment request aborted")):(a.warn(`503 attachment=${D} viewer=${S} reason=concurrency`),$(503,"Too many concurrent downloads",{"Retry-After":String(yt)}));let b=!1;try{let v=f.method==="HEAD",w=await I(Y.filePath,{maxBytes:K,head:v,principal:r(S),signal:f.signal});if(f.signal.aborted)return a.info(`503 attachment=${D} viewer=${S} reason=aborted`),$(503,"Attachment request aborted");if(!w.ok){let x=ht(w.reason);return w.reason==="not_found"&&l(D,!1),a.warn(`${x} attachment=${D} viewer=${S} reason=${w.reason} code=${w.code??"-"}`),$(x,fr[x])}if(w.bytes.byteLength>K)return a.error(`500 attachment=${D} viewer=${S} reason=port_contract code=over_max_bytes`),$(500,Fe);let L=$t(Y.fileType)??$t(w.contentType),h=L!==null&&pr.has(L),C=h?L:"application/octet-stream",F=h&&d.kind!=="download"?"inline":"attachment",N=w.size??w.bytes.byteLength,q=new Headers({"Content-Type":C,"Content-Length":String(N),"Content-Disposition":`${F}; filename="${hr(Y.fileName)}"; filename*=UTF-8''${yr(Y.fileName)}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return W&&q.append("Set-Cookie",W),l(D,!0),a.info(`200 attachment=${D} viewer=${S} type=${C} disposition=${F} bytes=${N}`),v?new Response(null,{status:200,headers:q}):(b=!0,new Response(Kn(w.bytes,H,Jn),{status:200,headers:q}))}finally{b||H()}}};var _e=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Hi=_e.queueWaitMs+_e.readMs+_e.renderMs+_e.transferMarginMs;import{createHash as Qn}from"crypto";var et=e=>{let t=JSON.stringify(e);return`"${Qn("sha256").update(t).digest("hex")}"`};var Xn=new Set([194,198,202,206]),Zn=64,ea=2,Sr=8,Tr=28,Ce=12,Ft=8,ta=20,Ar=Ce+Ft+10,ra=2,Ie=(e,t)=>e[t]<<8|e[t+1],Ye=(e,t,r)=>{let n=0;for(let a=r-1;a>=0;a-=1)n=n*256+e[t+a];return n},Ae=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},na=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,qt=e=>{if(e[0]!==255||e[1]!==216)return null;let t=null,r=2;for(;r<e.byteLength;){if(e[r]!==255)return null;for(;r<e.byteLength&&e[r]===255;)r+=1;if(r>=e.byteLength)return null;let n=e[r];if(r+=1,n===0||n===216||n===217)return null;if(n===1||n>=208&&n<=215)continue;if(r+2>e.byteLength)return null;let a=Ie(e,r),l=r+2,m=r+a;if(a<2||m>e.byteLength)return null;if(na(n)){if(t!==null||a<8)return null;let u=Ie(e,l+1),R=Ie(e,l+3),s=e[l+5];if(R===0||u===0||s===0||a!==8+3*s)return null;let f=[];for(let d=0;d<s;d+=1){let D=e[l+7+3*d],S=D>>4,I=D&15;if(S<1||S>4||I<1||I>4)return null;f.push({horizontal:S,vertical:I})}t={width:R,height:u,components:f,progressive:Xn.has(n)}}else if(n===218){if(t===null||a<3)return null;let u=e[l];return u<1||u>4||a!==6+2*u?null:{width:t.width,height:t.height,components:t.components,multiScan:t.progressive||u<t.components.length}}r=m}return null},Dr=e=>{if(!e.multiScan)return 0;let t=Math.max(...e.components.map(a=>a.horizontal)),r=Math.max(...e.components.map(a=>a.vertical)),n=0;for(let{horizontal:a,vertical:l}of e.components){let m=Math.ceil(e.width*a/(t*Sr)),u=Math.ceil(e.height*l/(r*Sr));n+=Math.ceil(m/a)*a*Math.ceil(u/l)*l}return n*Zn*ea},wr=e=>{if(e.byteLength<24||Ie(e,8)!==0||Ie(e,10)!==13||!Ae(e,12,"IHDR"))return null;let t=Ie(e,16)*65536+Ie(e,18),r=Ie(e,20)*65536+Ie(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},aa=e=>{if(Ae(e,Ce,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ye(e,26,2)&16383,r=Ye(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ae(e,Ce,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ye(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ae(e,Ce,"VP8X")?e.byteLength<Ar?null:{width:Ye(e,24,3)+1,height:Ye(e,27,3)+1}:null},_r=e=>{if(wr(e)===null||e.byteLength<=Tr)return null;switch(e[Tr]){case 0:return!1;case 1:return!0;default:return null}},Ir=e=>{if(Ae(e,Ce,"VP8 "))return"lossy";if(Ae(e,Ce,"VP8L"))return"lossless";if(!Ae(e,Ce,"VP8X")||e.byteLength<Ar)return null;if((e[ta]&ra)!==0)return"animated";let t=!1;for(let r=Ce;r+Ft<=e.byteLength;){if(Ae(e,r,"VP8L"))return"lossless";if(Ae(e,r,"VP8 "))return t?"lossy-alpha":"lossy";Ae(e,r,"ALPH")&&(t=!0);let n=Ye(e,r+4,4);r+=Ft+n+n%2}return null},Er={png:wr,jpeg:qt,webp:aa};var ia=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Cr=Object.freeze(["image/webp","image/jpeg","image/png"]),oa={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},sa=new Set(Cr),la=e=>typeof e=="string"&&sa.has(e),xr=1024*1024,ua=256,gt=(e,t)=>e.fileType===null||!ia.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,ca=[137,80,78,71,13,10,26,10],da=[255,216,255],ma=[[71,73,70,56,55,97],[71,73,70,56,57,97]],pa=[82,73,70,70],ya=[87,69,66,80],tt=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,a]of t.entries())if(e[r+n]!==a)return!1;return!0},Yt=e=>{if(tt(e,ca,0))return"png";if(tt(e,da,0))return"jpeg";for(let t of ma)if(tt(e,t,0))return"gif";return tt(e,pa,0)&&tt(e,ya,8)?"webp":null},vr=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:et([t])}},Mr=(e,t)=>{if(!la(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>xr)return"too_large";let r=oa[e.contentType];if(Yt(e.bytes)!==r)return"signature";let n=Er[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Lr=e=>{Re("maxBytes",e.maxBytes,0),Re("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=a=>{let l=t.get(a);l&&(t.delete(a),r-=l.weight)};return{get:a=>{let l=t.get(a);if(l)return t.delete(a),t.set(a,l),l.entry},set:(a,l)=>{n(a);let m=(l.kind==="thumbnail"?l.bytes.byteLength:0)+ua;if(m>e.maxBytes||e.maxEntries===0)return;let u=l.kind==="thumbnail"?{kind:"thumbnail",bytes:l.bytes.slice(),contentType:l.contentType}:l;t.set(a,{entry:u,weight:m}),r+=m;for(let R of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(R)}}}};var Pr=()=>{let e=new Map;return{join:(t,r,n)=>{let a=()=>{let R=new AbortController,s=()=>{e.get(t)?.controller===R&&e.delete(t)},d={promise:n(R.signal).finally(s),controller:R,waiters:0};return e.set(t,d),d},l=e.get(t)??a();l.waiters+=1;let m=()=>{l.waiters-=1,!(l.waiters>0)&&(l.controller.abort(),e.get(t)===l&&e.delete(t))};r.aborted?m():r.addEventListener("abort",m,{once:!0});let u=()=>{r.removeEventListener("abort",m)};return l.promise.finally(u)}}};var Vt=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:a,onStuck:l}=e,m=Date.now(),u=new AbortController,R=!1,s,f,d=(H,b)=>{let v=setTimeout(H,b);return v.unref?.(),v},D=()=>{l(Date.now()-m)},S=H=>{s=d(()=>{R=!0,H({timedOut:!0}),f=d(D,t),u.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},I=new Promise(S),W=AbortSignal.any([r,u.signal]),$=H=>{H(n(W))},K=new Promise($),g=H=>{clearTimeout(s),clearTimeout(f),R&&a(Date.now()-m,H)},M=K.then(()=>g(null),H=>g({error:H}));return{outcome:Promise.race([K.then(H=>({timedOut:!1,value:H})),I]),settled:M}};var Le={404:"Attachment not found",500:Fe,502:"Thumbnail unavailable",503:"Too many concurrent thumbnail requests"},kr=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:a,recordObjectState:l,logger:m}=e,u=(f,d)=>{if(f.fileSize===null||(d.kind==="exact"?d.bytes===f.fileSize:f.fileSize>d.maxBytes))return"verified";let S=d.kind==="exact"?String(d.bytes):`>${d.maxBytes}`;return m.warn(`size_mismatch expected=${f.fileSize} got=${S} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},R=(f,d)=>(D,S)=>{let I=S===null?"":` message=${S.error instanceof Error?S.error.message:"unknown"}`;m.warn(`${f}_overrun ms=${D} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail${I}`)},s=(f,d)=>D=>{m.warn(`${f}_stuck ms=${D} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail`)};return async(f,d)=>{let D=await t.acquire(f.owner,d);if(!D)return{kind:"failure",status:503,reason:d.aborted?"aborted":"queue"};let S=null;try{if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let I=Vt({budgetMs:_e.readMs,flightSignal:d,call:w=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:a(f.owner),signal:w}),onOverrun:R("read",f),onStuck:s("read",f)}),W=await I.outcome;if(W.timedOut)return S=I.settled,d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"read_timeout"};if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let $=W.value;if(!$.ok&&$.reason!=="too_large")return $.reason==="not_found"&&l(f.attachmentId,!1),{kind:"failure",status:ht($.reason)===404?404:502,reason:$.reason,code:$.code};if($.ok&&$.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let K=u(f,$.ok?{kind:"exact",bytes:$.bytes.byteLength}:{kind:"over",maxBytes:n}),g=w=>(K==="verified"&&r.set(f.key,w),{...w,identity:K});if(!$.ok)return g({kind:"unrenderable",reason:"too_large"});let M=Yt($.bytes);if(M===null)return g({kind:"unrenderable",reason:"signature"});let Y=Vt({budgetMs:_e.renderMs,flightSignal:d,call:w=>f.renderer.render($.bytes,{format:M,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:w}),onOverrun:R("render",f),onStuck:s("render",f)}),H=await Y.outcome;if(H.timedOut)return S=Y.settled,d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let b=H.value;if(!b.ok)return b.reason==="unsupported"?g({kind:"unrenderable",reason:"unsupported"}):b.reason==="failed"?{kind:"failure",status:502,reason:"render_failed"}:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};let v=Mr(b,f.box);return v!==null?{kind:"failure",status:500,reason:"port_contract",code:v}:g({kind:"thumbnail",bytes:b.bytes,contentType:b.contentType})}finally{S===null?D():S.then(D)}}};var Br=10,ha=1/Br,Nr=1-ha,fa=1024,ba=64,ga=8,Or="private, no-cache",Ra="no-store",Sa=e=>{switch(e.status){case 404:case 502:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Ur=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:l}=e,m=t.attachmentDelivery,u=Ze(e.rateLimitPerMinute),R=Ze(e.rateLimitPerMinute*Br),s=bt({limit:e.concurrency,queue:{max:ba,maxPerOwner:ga,maxWaitMs:_e.queueWaitMs}}),f=Lr({maxBytes:e.cacheBytes,maxEntries:fa}),d=Pr(),D=kr({gate:s,cache:f,maxBytes:m.maxBytes,encodeUserId:r,recordObjectState:l,logger:a}),S=(g,M,Y,H)=>{let b=`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail cache=${H}`;if(M.kind==="failure")return a[Sa(M)](`${M.status} ${b} reason=${M.reason} code=${M.code??"-"}`),g.fail(M.status,Le[M.status],M.status===503?{"Retry-After":String(yt)}:{});let v=M.identity==="verified"?"":` identity=${M.identity}`;if(M.kind==="unrenderable")return a.info(`404 ${b} reason=${M.reason}${v}`),g.fail(404,Le[404]);let w=M.identity==="verified"?{"Cache-Control":Or,ETag:Y}:{"Cache-Control":Ra},L=new Headers({"Content-Type":M.contentType,"Content-Length":String(M.bytes.byteLength),...w,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return g.cookie&&L.append("Set-Cookie",g.cookie),a.info(`200 ${b} type=${M.contentType} bytes=${M.bytes.byteLength}${v}`),new Response(M.bytes,{status:200,headers:L})},I=(g,M,Y)=>(M.firstDenial&&a.warn(`429 attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail reason=${Y}`),g.fail(429,"Too many requests",{"Retry-After":String(pt)})),W=(g,M,Y)=>{M.suppressedDenials>0&&a.warn(`${Y}_suppressed count=${M.suppressedDenials} viewer=${g.internalUserId} variant=thumbnail`)},$=g=>{let M=u.consume(g.internalUserId,Date.now());return M.allowed?(W(g,M,"rate_limit"),null):I(g,M,"rate_limit")},K=(g,M)=>{if(!M)return $(g);let Y=R.consume(g.internalUserId,Date.now());return Y.allowed?(W(g,Y,"revalidation_rate_limit"),null):I(g,Y,"revalidation_rate_limit")};return async(g,M)=>{let{request:Y,attachmentId:H,internalUserId:b,readAttachment:v,cookie:w,fail:L}=g,h=Ut[M],C=m.thumbnailRenderer;if(!C)return L(404,Le[404]);let F=Y.headers.get("If-None-Match"),N=F!==null,q=K(g,N);if(q)return q;let x=await n(Y),U=await t.getAttachmentForUser(x,H,b),z=U!==null&>(U,m.maxBytes)?vr({rendererId:C.id,box:h,attachmentId:H,filePath:U.filePath,fileType:U.fileType,fileSize:U.fileSize}):null;if(z&&mr(F,z.etag)){let E=new Headers({"Cache-Control":Or,ETag:z.etag});return w&&E.append("Set-Cookie",w),a.info(`304 attachment=${H} viewer=${b} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:E})}if(N){let E=$(g);if(E)return E}if(!U)return a.warn(`404 attachment=${H} viewer=${b} variant=thumbnail reason=not_visible`),L(404,Le[404]);if(!z)return u.refund(b,Date.now(),Nr),a.info(`404 attachment=${H} viewer=${b} variant=thumbnail reason=not_eligible`),L(404,Le[404]);let{key:V,etag:ee}=z,J=f.get(V);if(J)return u.refund(b,Date.now(),Nr),S(g,{...J,identity:"verified"},ee,"hit");let Q=E=>D({key:V,attachmentId:H,filePath:U.filePath,fileSize:U.fileSize,box:h,owner:b,readAttachment:v,renderer:C},E),P;try{P=await d.join(V,Y.signal,Q)}catch(E){return a.error(`500 attachment=${H} viewer=${b} variant=thumbnail cache=miss reason=port_exception message=${E instanceof Error?E.message:"unknown"}`),L(500,Le[500])}return S(g,P,ee,"miss")}};var Ta='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',$r=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:a,logger:l}=e,m=r.attachmentDelivery,u=gr(e.tuning,m),R={service:r,encodeUserId:n,resolveViewerScope:a,logger:l,recordObjectState:dr(r,l)},s=Rr({...R,rateLimitPerMinute:u.originalRateLimitPerMinute,concurrency:u.originalConcurrency}),f=Ur({...R,rateLimitPerMinute:u.thumbnailRateLimitPerMinute,concurrency:u.thumbnailConcurrency,cacheBytes:u.thumbnailCacheBytes});return async({request:d,params:D})=>{let S=null,I=(W,$,K={})=>{let g=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...K});return S&&g.append("Set-Cookie",S),new Response(JSON.stringify({error:{message:$}}),{status:W,headers:g})};try{let{user:W,cookie:$}=await t(d,{failureRedirect:null});if(S=$??null,!W)return I(401,"Unauthorized");let K=cr(new URL(d.url).searchParams);if(K.kind==="invalid")return I(400,"Invalid attachment request");if(K.kind==="thumbnail"&&d.method!=="GET")return I(405,"Method not allowed",{Allow:"GET"});if(d.method!=="GET"&&d.method!=="HEAD")return I(405,"Method not allowed",{Allow:"GET, HEAD"});let{idCodec:g,readAttachment:M}=m;if(!(g&&M))return I(404,"Attachment not found");if(D.token===void 0)throw new Error(Ta);let Y=g.decode(D.token);if(Y===null||!Number.isSafeInteger(Y)||Y<=0)return I(400,"Invalid attachment token");let H=await r.getUserIdByExternalId(W.id);if(!H)return I(403,"Forbidden");let b={request:d,delivery:K,attachmentId:Y,internalUserId:H,readAttachment:M,cookie:S,fail:I};return K.kind==="thumbnail"?await f(b,K.variant):await s(b)}catch(W){if(W instanceof Response)throw W;return l.error(`500 attachment=? viewer=? reason=unexpected message=${W instanceof Error?W.message:"unknown"}`),I(500,Fe)}}};var Aa=fe(1,"[Response]"),be=(e,t,r,n=200,a=Aa)=>{let l=et(r),m=e.headers.get("If-None-Match");a.info(`[jsonResponseWithETag] ETag: ${l}, If-None-Match: ${m}`);let u=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:l});return t&&u.append("Set-Cookie",t),e.method==="GET"&&n===200&&m===l?new Response(null,{status:304,headers:u}):new Response(JSON.stringify(r),{status:n,headers:u})};import{EventEmitter as Da}from"events";var Pe=(e,t)=>{let[r,n]=e.split("-").map(Number),[a,l]=t.split("-").map(Number);return r!==a?r<a:n<=l},rt=class{constructor(t){this.config=t;this._emitter=new Da;this._state="idle";this._refCount=0;this._lastId="$";this._emitter.setMaxListeners(0),this._logger=t.logger??fe(1,"[SSE Reader]")}subscribe(t,r){return this._emitter.on("entry",t),r&&this._emitter.on("error",r),this._refCount++,this._refCount===1&&this._startLoop(),()=>{this._emitter.removeListener("entry",t),r&&this._emitter.removeListener("error",r),this._refCount--,this._refCount<=0&&(this._refCount=0,this._stopLoop())}}async destroy(){this._refCount=0,await this._stopLoop(),this._emitter.removeAllListeners(),this._lastId="$"}async _startLoop(){for(;this._state==="stopping";)await new Promise(t=>setTimeout(t,50));if(this._state!=="running"&&this._refCount!==0){this._state="running";try{this._client=await this.config.redis?.createClient()}catch(t){this._state="idle",this._emitError(t instanceof Error?t:new Error("Failed to create Redis client for SSE reader"));return}if(!this._client){this._state="idle",this._emitError(new Error("Failed to create Redis client for SSE reader"));return}if(this._client.on("error",t=>{this._logger.error("Redis client error:",t)}),this._lastId==="$")try{let t=await this.config.redis?.getClient();if(t){let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});this._lastId=r.length>0?r[0].id:"0-0"}}catch(t){this._logger.warn("Failed to resolve stream tail anchor; falling back to $:",t)}try{for(;this._state==="running"&&this._client?.isOpen;){let t=await this._client.xRead([{key:this.config.streamKey,id:this._lastId}],{BLOCK:5e3,COUNT:100});if(t)for(let r of t)for(let n of r.messages){this._lastId=n.id;try{let a=n.message?.data?JSON.parse(n.message.data):null,l=a?.type;if((l==="report-create"||l==="report-delete"||l==="report-publish")&&this.config.cache.invalidatePrefix("daily-report:ids"),l==="comment-add"||l==="comment-delete"||l==="status-update"){let m=a?.reportHubId;typeof m=="number"&&(this.config.cache.invalidate(`daily-report:detail:${m}`),this.config.cache.invalidatePrefix(`daily-report:detail:${m}:user:`))}}catch{}this._emitter.emit("entry",{id:n.id,message:n.message})}}}catch(t){!(t?.constructor?.name==="ClientClosedError")&&this._state==="running"&&(this._logger.error("xRead loop error:",t),this._emitError(t instanceof Error?t:new Error(String(t))))}finally{if(this._client?.isOpen)try{await this._client.quit()}catch{}this._client=void 0,this._state="idle",this._refCount>0&&this._startLoop()}}}async _stopLoop(){if(this._state==="running"){if(this._state="stopping",this._client?.isOpen)try{await this._client.quit()}catch{}for(;this._state==="stopping";)await new Promise(t=>setTimeout(t,50))}}_emitError(t){this._emitter.listenerCount("error")>0?this._emitter.emit("error",t):this._logger.error("SSE reader error (no error listeners):",t)}};import{inArray as wa,sql as Hr}from"drizzle-orm";var _a="",Ia=64,Ea=e=>e.toLowerCase(),Ca=e=>e.trim().toLowerCase();function Fr(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=Ca(r);n.length>0&&t.add(n)}return t}function De(e,t){return e===null?!0:t==null?!1:e.has(Ea(t))}function ke(e){return e!==null&&e.size===0}function Yr(e,t){if(t!==null)return t.size===0?Hr`1 = 0`:wa(Hr`LOWER(${e})`,[...t])}var Ve,ze,nt=class nt{constructor(t,r){It(this,Ve);It(this,ze);Et(this,Ve,t),Et(this,ze,r)}get visible(){return Qe(this,Ve)===null?null:new Set(Qe(this,Ve))}get commentable(){return Qe(this,ze)===null?null:new Set(Qe(this,ze))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=Fr(r?t.read:t),a=r?t.comment:void 0;if(a===void 0)return new nt(n,n);let l=Fr(a),m=new Set;for(let u of l??[])n.has(u)&&m.add(u);return new nt(n,m)}static unrestricted(t){return new nt(null,null)}};Ve=new WeakMap,ze=new WeakMap;var ge=nt;function at(e){let t=qr(e.visible),r=qr(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function qr(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(_a);if(t.length<=Ia)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 ka=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},St=30,Kr=4e3,Na="stream interrupted by server error",Oa=/^\d{4}-\d{2}-\d{2}$/,Ba=15e3,Vr=Symbol("ids-stream-heartbeat"),zr=864e5,Ua={baseMs:2e3,jitterMs:8e3},Qr=6e4,zt=1e3,jr=JSON.stringify({type:"connected"}),Gr="0-0",$a=/^[0-9a-f]{1,16}$/,Ha=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),a=n!==null&&$a.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:a}:{invalid:!0};let l=Number.parseInt(t,10);return!Number.isSafeInteger(l)||String(l)!==t||l<=0?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:l},snapshot:a}:Oa.test(r)?{cursor:{businessDate:r,reportHubId:l},snapshot:a}:{invalid:!0}};async function*Wr(e,t,r,n){let a=t?nr(e,t):0,l=!0;for(;;){let m=e.slice(a,a+(l?r:Kr));a+=m.length;let u=a>=e.length,R=m[m.length-1];if(yield{kind:"chunk",items:m,nextCursor:u||!R?null:{businessDate:R.businessDate,reportHubId:R.reportHubId},isLast:u,...l?{total:e.length}:{},...l?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...l&&n.restarted?{restarted:!0}:{}},l=!1,u)return}}var Jr=(e,t,r,n)=>{let a=new TextEncoder,l=!1,m=null,u=new ReadableStream({async pull(s){if(l||r.signal.aborted){await t.return(void 0).catch(()=>{});try{s.close()}catch{}return}let f=null;try{m===null&&(m=t.next());let d=new Promise(W=>{f=setTimeout(()=>W(Vr),Ba)}),D=await Promise.race([m,d]);if(f!==null&&(clearTimeout(f),f=null),D===Vr){if(l||r.signal.aborted){await t.return(void 0).catch(()=>{});try{s.close()}catch{}return}s.enqueue(a.encode(`
|
|
2
|
-
`));return}m=null;let{value:S,done:I}=D;if(I){
|
|
3
|
-
`))}catch(d){if(f!==null&&clearTimeout(f),m=null,
|
|
4
|
-
`)),s.close()}catch{}}},cancel(){l=!0,t.return(void 0).catch(()=>{})}}),R=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&R.append("Set-Cookie",e),new Response(u,{status:200,headers:R})},Fa=(e,t,r,n)=>{if(r===null&&n===null)return!0;let a=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return De(r,e.report.sourceType);case"comment-add":case"comment-delete":return De(n,a??"Internal");case"report-delete":return De(r,a)}},qa=["externalComments","postedComments"],Ya=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||De(r,e.report.sourceType))return!1;let n=t.report;if(typeof n!="object"||n===null)return!1;let a=n;for(let l of qa)a[l]=[];return!0};function jt(e){let{authenticate:t,service:r,encodeUserId:n,redis:a,sseReader:l,streamKey:m}=e,u=e.loginRedirectPath??"/auth/login",R=e.logger??fe(3,"[DailyReportAPI]"),s=e.logger??fe(3,"[DailyReportVisibility]"),f=e.logger??fe(1,"[DailyReportSSE]"),d=e.logger??fe(1,"[DailyReportAttachment]"),D=async(b,v="initial")=>{let w=e.resolveVisibleSourceTypes;if(!w)return ge.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let L=await w(b,{reason:v});return L==null?ge.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):ge.restrictTo(L)}catch(L){return s.error("resolveVisibleSourceTypes threw; failing closed (deny all)",L),ge.restrictTo([])}},S=async({request:b})=>{let{user:v,cookie:w}=await t(b,{failureRedirect:u}),L=new Headers;w&&L.append("Set-Cookie",w);let h=await r.getUserIdByExternalId(v.id),C=h?n(h):null;return{data:{user:v,userId:C},headers:L}},I={"business-date":async(b,v,w,L,h)=>{let C=me(b.searchParams.get("businessDate")),F=b.searchParams.get("forceRefresh")==="true";if(!C)return be(w,v,{error:{message:"Invalid business date"}},400);let N=await r.getDailyReportsByBusinessDateByExternalId(h,C,L.id,{forceRefresh:F});return be(w,v,{businessDate:C,reports:N},200)},"ids-stream":async(b,v,w,L,h)=>{let C=Ha(b);if("invalid"in C)return be(w,v,{error:{message:"Invalid cursor"}},400);let F=b.searchParams.get("forceRefresh")==="true",N=!1,q=null,x=null,U=new Promise((V,ee)=>{q=V,x=ee});U.catch(()=>{});let oe=r.getDailyReportIdsByExternalId(h,L.id,{forceRefresh:F,onFetchStart:C.cursor?void 0:()=>{N=!0,r.readSseStreamAnchor().then(V=>r.getDailyReportIdsFirstPageByExternalId(h,L.id,St).then(ee=>({items:ee,streamAnchor:V}))).then(V=>q?.(V),V=>x?.(V))}});if(oe.catch(()=>{}),C.cursor){let{items:V,streamAnchor:ee}=await oe,J=xt(V),Q=C.snapshot!==null&&C.snapshot===J;return Jr(v,Wr(V,Q?C.cursor:null,St,{snapshot:J,restarted:!Q,streamAnchor:ee}),w,R)}let z=(async function*(){let V=await Promise.race([oe.then(Q=>({kind:"full",source:Q}),Q=>({kind:"full-error",error:Q})),U.then(Q=>({kind:"page",page:Q}),()=>({kind:"page-error"}))]),ee=null,J=!1;if(V.kind==="full")ee=V.source;else if(V.kind==="page"){let{items:Q,streamAnchor:P}=V.page;if(Q.length<St){yield{kind:"chunk",items:Q,nextCursor:null,isLast:!0,total:Q.length,streamAnchor:P};return}yield{kind:"chunk",items:Q,nextCursor:null,isLast:!1,provisional:!0},J=!0}else if(V.kind==="full-error"&&N){let Q=await U.catch(()=>null);Q&&Q.items.length>0&&(yield{kind:"chunk",items:Q.items,nextCursor:null,isLast:!1,provisional:!0})}ee===null&&(ee=await oe),yield*Wr(ee.items,null,J?Kr:St,{snapshot:xt(ee.items),streamAnchor:ee.streamAnchor})})();return Jr(v,z,w,R)},report:async(b,v,w,L,h)=>{let C=b.searchParams.get("reportHubId"),F=b.searchParams.get("forceRefresh")==="true",N=C?Number.parseInt(C,10):NaN;if(!Number.isFinite(N)||N<=0)return be(w,v,{error:{message:"Invalid reportHubId"}},400);let q=await r.getDailyReportDetailByIdByExternalId(h,N,L.id,{snapshot:!0,forceRefresh:F});return q?be(w,v,{report:q},200):be(w,v,{error:{message:"Report not found"}},404)}},W=async({request:b,params:v})=>{let{user:w,cookie:L}=await t(b,{failureRedirect:null}),h=L??null;if(!w)return be(b,h,{error:{message:"Unauthorized"}},401);if(b.method!=="GET")return be(b,h,{error:{message:"Method not allowed"}},405);let C=v.endpoint??"",F=I[C];if(!F)return be(b,h,{error:{message:"Unknown endpoint"}},404);let N=Date.now();try{let q=new URL(b.url),x=await D(b);return await F(q,h,b,w,x)}catch(q){let x=Date.now()-N,U=q instanceof Error?q:new Error(String(q));return R.error(`500 endpoint=${C} elapsed=${x}ms name=${U.name} code=${"code"in U?U.code:"N/A"} message=${U.message}`),R.error("Stack:",U.stack),be(b,h,{error:{message:"Internal Server Error"}},500)}},$=async({request:b,params:v})=>{let{user:w,cookie:L}=await t(b,{failureRedirect:null}),h=(F,N)=>ka(F,{...N,setCookie:L});if(!w)return h({error:"Unauthorized"},{status:401});let C=Date.now();try{if(v.endpoint!=="action")return h({error:"Unknown endpoint"},{status:404});let N=await r.getUserIdByExternalId(w.id);if(!N)return h({error:"User not found"},{status:404});let q=await D(b),x=await b.formData(),U=x.get("intent"),oe=x.get("reportHubId"),z=oe?Number(oe):NaN,V=x.get("businessDate"),ee=Number(x.get("operationTimestamp")),J=x.get("clientTempId");if(U==="clearCache")return e.enableDevCacheClear?(await r.clearCache(),h({status:"OK",intent:"clearCache"})):h({error:"Invalid intent"},{status:400});if(!J)return h({error:"clientTempId required"},{status:400});if(U!=="create"&&(!z||Number.isNaN(z)))return h({error:"Invalid reportHubId"},{status:400});let Q=async(P,E,te)=>{let ye=x.get(E);if(ye===null)return h({error:`${E} required`},{status:400});try{let le=await te(ye==="true");return h({status:"OK",intent:P,updatedStatus:{isStarred:le.isStarred,isRead:le.isRead},operationTimestamp:ee,reportHubId:String(z),clientTempId:J})}catch(le){if(le instanceof Error&&le.message==="Not Found")return h({error:"Report not found"},{status:404});throw le}};switch(U){case"create":{if(!V)return h({error:"businessDate required"},{status:400});let P=await r.createDailyReport(N,V,J);return h({status:"OK",intent:"create",report:P,reportHubId:String(P.reportHubId),clientTempId:J})}case"update":{let P=x.get("title"),E=x.get("content");try{return await r.updateDailyReport(z,N,{title:P,content:E},J),h({status:"OK",intent:"update",reportHubId:String(z),clientTempId:J})}catch(te){if(te instanceof Error){if(te.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(te.message==="Not Found")return h({error:"Report not found"},{status:404})}throw te}}case"publish":try{let P=await r.publishDailyReport(z,N,J);return h({status:"OK",intent:"publish",reportHubId:String(z),clientTempId:J,report:P})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return h({error:"Report not found"},{status:404})}throw P}case"delete":try{return await r.deleteDailyReport(z,N,J),h({status:"OK",intent:"delete",reportHubId:String(z),clientTempId:J})}catch(P){if(P instanceof Error){if(P.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(P.message==="Not Found")return h({error:"Report not found"},{status:404})}throw P}case"toggleStar":return await Q("toggleStar","isStarred",P=>r.setStarStatus(q,N,z,V,P,J));case"toggleRead":return await Q("toggleRead","isRead",P=>r.setReadStatus(q,N,z,V,P,J));case"addComment":{let P=x.get("content");if(!P)return h({error:"Content required"},{status:400});try{let E=await r.addComment(q,N,z,P,V,J),te={...E,userId:E.userId};return h({status:"OK",intent:"addComment",newComment:te,reportHubId:String(z),clientTempId:J})}catch(E){if(E instanceof Error){if(E.message==="Not Found")return h({error:"Report not found"},{status:404});if(E.message.startsWith("Comments are restricted"))return h({error:"Comments are restricted for this report"},{status:403})}throw E}}case"deleteComment":{let P=Number(x.get("commentId"));if(!P||Number.isNaN(P))return h({error:"Invalid commentId"},{status:400});try{return await r.deleteComment(q,N,z,P,V,J),h({status:"OK",reportHubId:String(z),deletedCommentId:String(P),clientTempId:J})}catch(E){if(E instanceof Error){if(E.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(E.message==="Not Found")return h({error:"Comment not found"},{status:404})}throw E}}default:return h({error:"Invalid intent"},{status:400})}}catch(F){if(F instanceof Response)throw F;let N=Date.now()-C,q=F instanceof Error?F:new Error(String(F));return R.error(`500 action elapsed=${N}ms name=${q.name} message=${q.message}`),R.error("Stack:",q.stack),h({error:"Internal Server Error"},{status:500})}},K=(b,v)=>{b.writeEvent({event:null,id:v,data:jr})},g=(b,v,w,L)=>{if(w.data)try{let h=JSON.parse(w.data),C=lr.safeParse(h);if(!C.success){f.error("SSE message validation failed:",C.error.format());return}let F=C.data,N=typeof h.recipientRawUserId=="number"?h.recipientRawUserId:void 0;if((F.type==="status-update"||N!==void 0)&&N!==L.internalUserId||!Fa(F,h,L.visibleSet,L.commentableSet)){K(b,v);return}let x=Ya(F,h,L.commentableSet),U;if("recipientRawUserId"in h){let{recipientRawUserId:oe,...z}=h;U=JSON.stringify(z)}else x?U=JSON.stringify(h):U=w.data;b.writeEvent({event:null,id:v,data:U})}catch(h){f.error(`[SSE:${L.internalUserId}] processEntry error:`,h)}},M=async(b,v)=>{let{request:w,internalUserId:L,cursor:h}=v,C=v.initialScope.visible,F=v.initialScope.commentable,N=0,q=setInterval(()=>{let E=++N;D(w,"refresh").then(te=>{E===N&&(C=te.visible,F=te.commentable)})},Qr);b.onClose(()=>clearInterval(q));let x=h===null?Gr:h,U=h!==null&&a!==void 0,oe=[],z=null,V=E=>{Pe(E.id,x)||(x=E.id,g(b,E.id,E.message,{internalUserId:L,visibleSet:C,commentableSet:F}))},ee=async(E,te)=>{let[ye]=await E.xRange(m,"-","+",{COUNT:1});return ye!==void 0&&!Pe(ye.id,te)},J=async(E,te)=>{if(await ee(E,te))return!1;let ye=te;for(;;){let le=await E.xRange(m,ye,"+",{COUNT:zt}),Be=le[0];if(Be!==void 0&&Be.id!==ye&&await ee(E,ye))return!1;for(let ot of le){if(z!==null&&Pe(z,ot.id))return!0;V(ot)}let it=le.at(-1);if(le.length<zt||it===void 0||b.isClosed())return!0;ye=it.id}},Q=l.subscribe(E=>{if(!U){V(E);return}Pe(E.id,x)||(z===null&&(z=E.id),oe.push(E))},E=>{f.error(`[SSE:${L}] Fan-Out reader error:`,E),b.close()});if(b.onClose(Q),h===null)try{let E=await a?.getClient();if(E){let te=await E.xRevRange(m,"+","-",{COUNT:1});te.length>0&&!Pe(te[0].id,x)&&(x=te[0].id)}}catch{}if(b.writeEvent({event:null,id:x===Gr?null:x,data:jr}),La(b,{intervalMs:ar,retry:Ua,runtime:xa}),h===null||a===void 0)return;let P=await a.getClient();if(P===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await J(P,h)){b.writeRetry(zr),b.writeEvent({event:"resync-required",id:null,data:""}),b.close();return}U=!1;for(let E of oe.splice(0))V(E)},Y=async({request:b,params:v})=>{let w,L=()=>{let C=new Headers;return w!==void 0&&C.append("Set-Cookie",w),C},h=C=>Pa(C,{data:"",retryMs:zr,headers:L()});try{let C=await t(b,{failureRedirect:null});w=C.cookie;let{user:F}=C;if(!F)return h("auth-required");let N=await r.getUserIdByExternalId(F.id);if(!N)return h("forbidden");if(v.endpoint!=="updates")return new Response("Not Found",{status:404,headers:L()});let q=Ma(b,ir);if(q!==null&&!or(q))return f.warn(`[SSE:${N}] malformed resume cursor; asking the client to resync`),h("resync-required");let x=await D(b);return va({requestSignal:b.signal,headers:L(),onError:(U,oe)=>f.error(`[SSE:${N}] ${oe} failed:`,U),produce:U=>M(U,{request:b,internalUserId:N,cursor:q,initialScope:x})})}catch(C){if(C instanceof Response)throw C;let F=C instanceof Error?C:new Error(String(C));return f.error(`500 sse name=${F.name} message=${F.message}`),new Response("Internal Server Error",{status:500,headers:L()})}},H=$r({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:D,logger:d,tuning:e});return{index:{loader:S},api:{loader:W,action:$},sse:{loader:Y},attachment:{loader:H}}}import{runWithTransactionRetry as Va}from"@aiquants/mssql";import{aliasedTable as je,and as ne,asc as Tt,desc as Ge,eq as _,getColumns as za,inArray as Se,isNull as he,or as We,sql as Xr}from"drizzle-orm";var Ne=e=>za(e),ja=e=>{if(e!==void 0){if(typeof e!="object"||e===null)throw qe("attachmentThumbnailRenderer","an object with id and render",e);if(e.render===void 0)throw ft("attachmentThumbnailRenderer.render","a function");if(typeof e.render!="function")throw qe("attachmentThumbnailRenderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw qe("attachmentThumbnailRenderer.id","a non-blank string naming the rendering pipeline version",e.id);return e}},pe=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),a=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),l=String(r.getMonth()+1).padStart(2,"0"),m=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${a}-${l}-${m}`;let u=String(r.getHours()).padStart(2,"0"),R=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0");return`${a}-${l}-${m} ${u}:${R}:${s}`};function Gt(e){let{db:t,tables:r,userTable:n,resolveUserId:a,encodeUserId:l,redis:m,cache:u,epochs:R}=e,{hub:s,internal:f,comment:d,label:D,hubLabel:S,userStatus:I}=r,W=e.externalSources??[],$=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],K=$[0]??"\u4E0B\u66F8\u304D",g=e.logger??fe(1,"[DailyReportService]");Ht({attachmentIdCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,attachmentThumbnailRenderer:e.attachmentThumbnailRenderer,attachmentMaxBytes:e.attachmentMaxBytes});let M=Object.freeze({idCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,thumbnailRenderer:ja(e.attachmentThumbnailRenderer),maxBytes:Me("attachmentMaxBytes",e.attachmentMaxBytes,1,br)}),Y=i=>Va(o=>t.transaction(c=>o(()=>i(c))),e.transactionRetry),H="daily-report:ids",b=e.idsTtlMs??18e4,v="daily-report:ids:epoch",w="daily-report:business-date:",L=e.businessDateTtlMs??3e5,h="daily-report:date-epoch:",C="daily-report:detail-epoch:",N=`${e.streamKey??"daily-report:sse-stream"}:v2`,q=e.streamMaxLen??1e4,x=i=>R.incrementEpoch(i),U=i=>Yr(s.sourceType,i),oe=(i,o)=>`${H}:user:${i}:st:${o}`,z=i=>`${H}:user:${i}:`,V=(i,o,c)=>`daily-report:date:${i}:user:${o}:st:${c}`,ee=(i,o)=>`daily-report:date:${i}:user:${o}:`,J=(i,o,c)=>`daily-report:detail:${i}:user:${o}:st:${c}`,Q=(i,o)=>`daily-report:detail:${i}:user:${o}:`,P=async(i,o)=>{let c=await m?.getClient();if(!c){g.warn(`[SSE] Redis client unavailable (${o})`);return}let p=Date.now();try{await c.xAdd(N,"*",{data:JSON.stringify(i)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:q}});let T=Date.now()-p;T>1e3&&g.warn(`[SSE] Slow publish (${o}): ${T}ms`)}catch(T){g.error(`[SSE] Redis publish failed (${o}):`,T)}},E=async()=>{try{let i=await m?.getClient();if(i===void 0)return null;let[o]=await i.xRevRange(N,"+","-",{COUNT:1});return o===void 0?null:o.id}catch(i){return g.error("[DailyReportService] SSE stream anchor read failed",i),null}},te=i=>i==null||i===""?null:/^\d+$/.test(i)?l(Number(i)):i,ye=()=>{let i={};for(let o of W)i[`ext_${o.sourceType}`]=Ne(o.table);return i},le=i=>{let o=i;for(let c of W)o=o.leftJoin(c.table,ne(_(s.sourceType,c.sourceType),_(s.sourceIdNum,c.idColumn)));return o},Be=(i,o,c)=>{let{hub:p,internal:T}=o,O=p.summary,A=[],k=null,B=null,X=null,j=null,re=null,ue=null,$e=[],Ee=W.find(G=>G.sourceType===p.sourceType),He=Ee?o[`ext_${Ee.sourceType}`]:void 0;if(Ee&&He){let G=Ee.mapRow(He);G.content!==void 0&&(O=G.content),G.employeeName!==void 0&&(ue=G.employeeName),G.category!==void 0&&(k=G.category),G.creationCategory!==void 0&&(B=G.creationCategory),G.visitTimeFrom!==void 0&&(X=G.visitTimeFrom),G.visitTimeTo!==void 0&&(j=G.visitTimeTo),G.customerName!==void 0&&(re=G.customerName),G.interviewers!==void 0&&(A=G.interviewers),G.externalComments!==void 0&&($e=G.externalComments)}else p.sourceType==="Internal"&&T&&(O=T.body);let we=(o.labels??[]).map(G=>({id:G.id,name:G.name,color:G.color})),ce=o.postedCommentRows??[],ae=De(i.commentable,p.sourceType),de=B?$.includes(B):!1,_t=Ue?.[0]??null;return de&&_t&&!we.some(G=>G.id===_t)&&we.push({id:_t,name:K,color:null}),{reportHubId:p.id,date:pe(p.businessDate,"YYYY-MM-DD"),author:o.creatorName??te(p.createdBy)??"",userId:p.userId?l(p.userId):"",sourceType:p.sourceType??"Internal",createdAt:pe(p.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:pe(p.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:te(p.updatedBy),employeeName:ue??o.creatorName??te(p.createdBy),category:k,creationCategory:B,visitTimeFrom:X,visitTimeTo:j,customerName:re,interviewers:A,subject:p.title,content:O,externalComments:ae?$e:[],isRead:o.isRead??!1,isStarred:o.isStarred??!1,labels:we,postedComments:ce.filter(G=>ae||c!==void 0&&G.userId===c).map(G=>({...G,userId:l(G.userId),isMine:c?G.userId===c:!1})),attachments:o.attachments}},it=async(i,o)=>{let c=je(S,"draft_label"),p=await ve();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).from(s).leftJoin(c,ne(_(c.hubId,s.id),Se(c.labelId,p))).where(ne(he(s.deletedAt),We(_(s.userId,o),he(s.userId),he(c.hubId)),U(i.visible))).orderBy(Ge(s.businessDate),Ge(s.id))).map(O=>({...O,businessDate:pe(O.businessDate,"YYYY-MM-DD")}))},ot=async(i,o,c)=>{let p=await Je(o);if(!p)return[];if(ke(i.visible))return[];let T=je(S,"draft_label"),O=await ve();return(await t.select({reportHubId:s.id,businessDate:s.businessDate,sourceType:s.sourceType}).top(c).from(s).leftJoin(T,ne(_(T.hubId,s.id),Se(T.labelId,O))).where(ne(he(s.deletedAt),We(_(s.userId,p),he(s.userId),he(T.hubId)),U(i.visible))).orderBy(Ge(s.businessDate),Ge(s.id))).map(k=>({...k,businessDate:pe(k.businessDate,"YYYY-MM-DD")}))},cn=async(i,o)=>{let c=await le(t.select({hub:Ne(s),internal:Ne(f),creatorName:n.displayName,...ye()}).from(s)).leftJoin(f,_(s.id,f.hubId)).leftJoin(n,_(s.userId,n.id)).where(ne(_(s.businessDate,Xr`${o}`),he(s.deletedAt),U(i.visible))).orderBy(Ge(s.id)),p=await ut(c.map(T=>T.hub.id));return c.map(T=>Be(i,{...T,attachments:p.get(T.hub.id)??[]}))},dn=i=>`${w}${i}`,st=new Map,Je=async i=>{if(!e.disableUserIdCache&&st.has(i))return st.get(i)??null;let o=await a(i);return o!==null&&!e.disableUserIdCache&&st.set(i,o),o},mn=async(i,o,{forceRefresh:c=!1,snapshot:p=!1,ttlMsOverride:T,onFetchStart:O}={})=>{let A=await Je(o);if(!A)return{items:[],streamAnchor:null};if(ke(i.visible))return{items:[],streamAnchor:await E()};let k=oe(A,at(i)),[B]=await u.getOrFetch({cacheKey:k,fetcher:async()=>{let X=await E(),j=await it(i,A);return rr(j)?[{items:j,streamAnchor:X}]:(g.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)"),[{items:[...j].sort(dt),streamAnchor:X}])},onFetchStart:O,forceRefresh:c,snapshot:p,ttlMsOverride:T??b,epochKey:v,refreshAheadRatio:.5});if(B===void 0)throw new Error("[DailyReportService] ids cache returned no record");return B},pn=(i,o,{forceRefresh:c=!1,snapshot:p=!1,ttlMsOverride:T}={})=>{let O=me(o);return O?ke(i.visible)?Promise.resolve([]):u.getOrFetch({cacheKey:`${dn(O)}:st:${at(i)}`,fetcher:()=>cn(i,O),forceRefresh:c,snapshot:p,ttlMsOverride:T??L}):Promise.resolve([])},Ue=null,lt=async()=>(Ue!==null||(Ue=(await t.select({id:D.id}).from(D).where(Se(D.name,$)).orderBy(D.id)).map(o=>o.id)),Ue),ve=async()=>{let i=await lt();return i.length>0?i:[-1]},At=async()=>{let i=await lt();if(i.length===0)return null;let[o]=await t.select({id:D.id}).top(1).from(D).where(_(D.name,K));return o?.id??i[0]},yn=(i,o)=>o!=null?"absent":i!=null?"present":"unknown",ut=async i=>{let o=new Map,c=r.attachment,p=M.idCodec;if(i.length===0||!c||!p)return o;let T=M.thumbnailRenderer!==void 0&&M.readAttachment!==void 0,O=await t.select({id:c.id,hubId:c.hubId,fileName:c.fileName,fileType:c.fileType,fileSize:c.fileSize,createdAt:c.createdAt,objectCheckedAt:c.objectCheckedAt,objectMissingAt:c.objectMissingAt}).from(c).where(Se(c.hubId,i)).orderBy(Tt(c.createdAt),Tt(c.id));for(let A of O){let k=A.fileType?String(A.fileType):null,B=A.fileSize!=null?Number(A.fileSize):null,X=yn(A.objectCheckedAt,A.objectMissingAt),j={id:p.encode(Number(A.id)),fileName:String(A.fileName),fileType:k,fileSize:B,createdAt:pe(A.createdAt,"YYYY-MM-DD HH:mm:ss"),state:X,hasThumbnail:T&&X!=="absent"&>({fileType:k,fileSize:B},M.maxBytes)},re=o.get(Number(A.hubId));re?re.push(j):o.set(Number(A.hubId),[j])}return o},hn=async(i,o,c)=>{let p=r.attachment;if(!p||ke(i.visible))return null;let T=await ve(),O=je(S,"draft_label");return(await t.select({fileName:p.fileName,filePath:p.filePath,fileType:p.fileType,fileSize:p.fileSize}).top(1).from(p).innerJoin(s,_(s.id,p.hubId)).leftJoin(O,ne(_(O.hubId,s.id),Se(O.labelId,T))).where(ne(_(p.id,o),he(s.deletedAt),We(_(s.userId,c),he(O.hubId)),U(i.visible))))[0]??null},fn=async i=>{let o=r.attachment;if(!o)return;let c=new Date;try{await t.update(o).set({objectCheckedAt:c,objectMissingAt:c,updatedAt:c}).where(_(o.id,i))}catch(p){g.error("markAttachmentMissing failed",p)}},bn=async i=>{let o=r.attachment;if(!o)return;let c=new Date;try{await t.update(o).set({objectCheckedAt:c,objectMissingAt:null,updatedAt:c}).where(_(o.id,i))}catch(p){g.error("markAttachmentPresent failed",p)}},gn=async(i,o,c,{forceRefresh:p=!1,snapshot:T=!1,ttlMsOverride:O}={})=>{let A=await Je(c);if(!A)return[];let k=me(o);if(!k)return[];if(ke(i.visible))return[];let B=V(k,A,at(i));return u.getOrFetch({cacheKey:B,fetcher:async()=>{let X=await ve(),j=je(S,"draft_label"),re=await le(t.select({hub:Ne(s),internal:Ne(f),isRead:I.isRead,isStarred:I.isStarred,creatorName:n.displayName,...ye()}).from(s)).leftJoin(f,_(s.id,f.hubId)).leftJoin(I,ne(_(s.id,I.hubId),_(I.userId,A))).leftJoin(j,ne(_(j.hubId,s.id),Se(j.labelId,X))).leftJoin(n,_(s.userId,n.id)).where(ne(_(s.businessDate,Xr`${k}`),he(s.deletedAt),We(_(s.userId,A),he(j.hubId)),U(i.visible))).orderBy(Ge(s.id));if(re.length===0)return[];let ue=re.map(ae=>ae.hub.id),$e=await t.select({hubId:S.hubId,id:D.id,name:D.name,color:D.color}).from(S).innerJoin(D,_(S.labelId,D.id)).where(Se(S.hubId,ue)),Ee=await t.select({hubId:d.hubId,id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,_(d.userId,n.id)).where(Se(d.hubId,ue)).orderBy(Tt(d.createdAt)),He=await ut(ue),we=new Map,ce=new Map;for(let ae of $e){let de=we.get(ae.hubId);de||(de=[],we.set(ae.hubId,de)),de.push({id:ae.id,name:ae.name,color:ae.color})}for(let ae of Ee){let de=ce.get(ae.hubId);de||(de=[],ce.set(ae.hubId,de)),de.push({id:ae.id,content:ae.body,createdAt:pe(ae.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ae.userId,userName:ae.userName||""})}return re.map(ae=>{let de=ae.hub.id;return Be(i,{...ae,attachments:He.get(de)??[],labels:we.get(de)||[],postedCommentRows:ce.get(de)||[]},A)})},forceRefresh:p,snapshot:T,ttlMsOverride:O??L,epochKey:`${h}${k}`})},Ke=async(i,o,c,{forceRefresh:p=!1,snapshot:T=!1,ttlMsOverride:O}={})=>{if(ke(i.visible))return null;let A=J(o,c,at(i));return(await u.getOrFetch({cacheKey:A,fetcher:async()=>{let B=await ve(),X=je(S,"draft_label"),j=await le(t.select({hub:Ne(s),internal:Ne(f),isRead:I.isRead,isStarred:I.isStarred,creatorName:n.displayName,...ye()}).from(s)).leftJoin(f,_(s.id,f.hubId)).leftJoin(I,ne(_(s.id,I.hubId),_(I.userId,c))).leftJoin(X,ne(_(X.hubId,s.id),Se(X.labelId,B))).leftJoin(n,_(s.userId,n.id)).where(ne(_(s.id,o),he(s.deletedAt),We(_(s.userId,c),he(X.hubId)),U(i.visible)));if(j.length===0)return[];let re=j[0].hub.id,ue=await t.select({id:D.id,name:D.name,color:D.color}).from(S).innerJoin(D,_(S.labelId,D.id)).where(_(S.hubId,re)),$e=await t.select({id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,_(d.userId,n.id)).where(_(d.hubId,re)).orderBy(Tt(d.createdAt)),Ee=await ut([re]),He=ue.map(ce=>({id:ce.id,name:ce.name,color:ce.color})),we=$e.map(ce=>({id:ce.id,content:ce.body,createdAt:pe(ce.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ce.userId,userName:ce.userName||""}));return[Be(i,{...j[0],attachments:Ee.get(re)??[],labels:He,postedCommentRows:we},c)]},forceRefresh:p,snapshot:T,ttlMsOverride:O??L,epochKey:`${C}${o}`}))[0]??null},Rn=async(i,o,c,p={})=>{let T=await Je(c);return T?Ke(i,o,T,p):null},Sn=async(i,o)=>{let c=await ve(),p=je(S,"draft_label"),[T]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt}).top(1).from(s).leftJoin(p,ne(_(p.hubId,s.id),Se(p.labelId,c))).where(ne(_(s.id,i),We(_(s.userId,o),he(p.hubId))));return T??null},Dt=async(i,o,c)=>{let p=await Sn(o,c);if(!p||p.deletedAt||!De(i.visible,p.sourceType))throw new Error("Not Found")},Tn=async(i,o,c,p,T,O)=>{await Dt(i,c,o);let A=await t.select().top(1).from(I).where(ne(_(I.hubId,c),_(I.userId,o))),k;if(A.length>0?A[0].isStarred!==T?k=(await t.update(I).set({isStarred:T,updatedAt:new Date,updatedBy:String(o)}).output().where(ne(_(I.hubId,c),_(I.userId,o))))[0]:k=A[0]:k=(await t.insert(I).output().values({hubId:c,userId:o,isStarred:T,isRead:!1,createdAt:new Date,createdBy:String(o),updatedAt:new Date,updatedBy:String(o)}))[0],p){let B=me(p);B&&(u.invalidatePrefix(ee(B,o)),await x(`${h}${B}`))}return u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(Q(c,o)),await x(`${C}${c}`),await P(mt.parse({type:"status-update",reportHubId:c,recipientRawUserId:o,statusType:"star",value:T,clientTempId:O}),"setStarStatus"),k},An=async(i,o,c,p,T,O)=>{await Dt(i,c,o);let A=await t.select().top(1).from(I).where(ne(_(I.hubId,c),_(I.userId,o))),k;if(A.length>0?A[0].isRead!==T?k=(await t.update(I).set({isRead:T,updatedAt:new Date,updatedBy:String(o)}).output().where(ne(_(I.hubId,c),_(I.userId,o))))[0]:k=A[0]:k=(await t.insert(I).output().values({hubId:c,userId:o,isRead:T,isStarred:!1,createdAt:new Date,createdBy:String(o),updatedAt:new Date,updatedBy:String(o)}))[0],p){let B=me(p);B&&(u.invalidatePrefix(ee(B,o)),await x(`${h}${B}`))}return u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(Q(c,o)),await x(`${C}${c}`),await P(mt.parse({type:"status-update",reportHubId:c,recipientRawUserId:o,statusType:"read",value:T,clientTempId:O}),"setReadStatus"),k},Jt=async(i,o)=>{if(o===null)return;let c=await ve(),[p]=await t.select({hubId:S.hubId}).top(1).from(S).where(ne(_(S.hubId,i),Se(S.labelId,c)));return p?o:void 0},Dn=async(i,o,c,p,T,O)=>{let[A]=await t.select({sourceType:s.sourceType,deletedAt:s.deletedAt,userId:s.userId}).top(1).from(s).where(_(s.id,c));if(!A||A.deletedAt)throw new Error("Not Found");if(await Dt(i,c,o),!De(i.commentable,A.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(A.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let k=await Jt(c,A.userId),[B]=await t.insert(d).output().values({hubId:c,userId:o,body:p,createdAt:new Date,createdBy:String(o),updatedAt:new Date,updatedBy:String(o)}),[X]=await t.select({displayName:n.displayName}).top(1).from(n).where(_(n.id,o)),j=X?.displayName??"";if(T){let ue=me(T);ue&&(u.invalidatePrefix(`daily-report:date:${ue}:user:`),await x(`${h}${ue}`))}u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(`daily-report:detail:${c}:user:`),await x(`${C}${c}`);let re={id:B.id,userId:l(B.userId),userName:j,content:B.body,createdAt:pe(B.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await P(Lt.parse({type:"comment-add",reportHubId:c,comment:re,clientTempId:O,recipientRawUserId:k,sourceType:A.sourceType}),"addComment"),re},wn=async(i,o)=>await i.select().top(1).from(d).where(_(d.id,o)),_n=async(i,o,c,p,T,O)=>{let A=await wn(t,p);if(A.length===0)throw new Error("Not Found");if(A[0].hubId!==c)throw new Error("Not Found");let[k]=await t.select({userId:s.userId,sourceType:s.sourceType}).top(1).from(s).where(_(s.id,A[0].hubId));if(!(k&&De(i.visible,k.sourceType)))throw new Error("Not Found");if(A[0].userId!==o)throw new Error("Unauthorized");let B=await Jt(c,k.userId);if(await t.delete(d).where(_(d.id,p)),T){let X=me(T);X&&(u.invalidatePrefix(`daily-report:date:${X}:user:`),await x(`${h}${X}`))}u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(`daily-report:detail:${c}:user:`),await x(`${C}${c}`),await P(Pt.parse({type:"comment-delete",reportHubId:c,commentId:p,clientTempId:O,recipientRawUserId:B,sourceType:k?.sourceType}),"deleteComment")},In=async(i,o,c)=>{g.info("createDailyReport called",{userId:i,businessDate:o});let[p]=await t.select({displayName:n.displayName}).from(n).where(_(n.id,i)),T=p?.displayName??l(i);try{let O=await Y(async B=>{g.info("Starting transaction");let X=`internal-temp-${Date.now()}-${Math.random()}`,[j]=await B.insert(s).output().values({sourceType:"Internal",sourceId:X,businessDate:new Date(o),userId:i,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)});await B.update(s).set({sourceId:String(j.id)}).where(_(s.id,j.id)),g.info("Hub created",j),await B.insert(f).values({hubId:j.id,body:"",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)}),g.info("Internal created"),g.info("Calling getDraftLabelId");let re=await At();g.info("draftLabelId",re);let ue=[];return re&&(await B.insert(S).values({hubId:j.id,labelId:re,createdAt:new Date,createdBy:String(i)}),ue.push({id:re,name:K,color:null})),g.info("Label assigned"),{reportHubId:j.id,date:o,createdAt:pe(j.createdAt,"YYYY-MM-DD HH:mm:ss"),author:T,userId:l(i),sourceType:"Internal",employeeName:T,updatedBy:l(i),updatedAt:pe(j.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:j.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ue,postedComments:[],attachments:[]}}),A=me(o);A&&u.invalidatePrefix(ee(A,i)),u.invalidatePrefix(w),u.invalidatePrefix(z(i)),await x(v),A&&await x(`${h}${A}`);let k=await Ke(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),O.reportHubId,i,{forceRefresh:!0});if(k){let B=await lt(),X=k.labels.some(j=>B.includes(j.id));await P(kt.parse({type:"report-create",reportHubId:k.reportHubId,report:k,clientTempId:c,recipientRawUserId:X?i:void 0}),"createDailyReport")}return k??O}catch(O){throw g.error("Error in createDailyReport",O),O}},ct=async(i,o)=>await i.select().top(1).from(s).where(_(s.id,o)),wt=async(i,o,c)=>{await i.update(s).set(c).where(_(s.id,o))},Kt=async(i,o,c)=>{await i.update(f).set(c).where(_(f.hubId,o))},Qt=async(i,o,c)=>{await i.delete(S).where(ne(_(S.hubId,o),_(S.labelId,c)))};return{streamKey:N,streamMaxLen:q,attachmentDelivery:M,clearCache:async()=>{u.clearAll(),st.clear(),Ue=null,R&&await x(v),g.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(i,o)=>{u.invalidatePrefix(w),u.invalidatePrefix(H),await x(v);for(let c of new Set(i))u.invalidatePrefix(`daily-report:detail:${c}:user:`),await x(`${C}${c}`);for(let c of new Set(o)){let p=me(c);p&&await x(`${h}${p}`)}},getUserIdByExternalId:Je,getDailyReportIdsByExternalId:mn,getDailyReportIdsFirstPageByExternalId:ot,readSseStreamAnchor:E,getDailyReportsByBusinessDate:pn,getDailyReportsByBusinessDateByExternalId:gn,getDailyReportDetailById:Ke,getDailyReportDetailByIdByExternalId:Rn,getDraftLabelId:At,getAttachmentsByHubIds:ut,getAttachmentForUser:hn,markAttachmentMissing:fn,markAttachmentPresent:bn,setStarStatus:Tn,setReadStatus:An,addComment:Dn,deleteComment:_n,createDailyReport:In,updateDailyReport:async(i,o,c,p)=>{let T=await ct(t,i);if(!T.length||T[0].deletedAt)throw new Error("Not Found");if(T[0].userId!==o)throw new Error("Unauthorized");await Y(async k=>{c.title!==void 0&&await wt(k,i,{title:c.title,updatedAt:new Date,updatedBy:String(o)}),c.content!==void 0&&await Kt(k,i,{body:c.content,updatedAt:new Date,updatedBy:String(o)})}),u.invalidate(`daily-report:detail:${i}`),u.invalidatePrefix(`daily-report:detail:${i}:user:`),u.invalidatePrefix(w),await x(`${C}${i}`);let O=me(pe(T[0].businessDate,"YYYY-MM-DD"));O&&(u.invalidatePrefix(`daily-report:date:${O}:user:`),await x(`${h}${O}`));let A=await Ke(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,o,{forceRefresh:!0});if(A){let k=await lt(),B=A.labels.some(X=>k.includes(X.id));await P(Nt.parse({type:"report-update",reportHubId:A.reportHubId,report:A,clientTempId:p,recipientRawUserId:B?o:void 0}),"updateDailyReport")}},publishDailyReport:async(i,o,c)=>{let p=await ct(t,i);if(!p.length)throw new Error("Not Found");if(p[0].userId!==o)throw new Error("Unauthorized");let T=await At();if(!T)return null;if(await Qt(t,i,T),u.invalidatePrefix(`daily-report:detail:${i}:user:`),u.invalidatePrefix(w),u.invalidatePrefix(H),await x(v),p[0].businessDate){let k=me(pe(p[0].businessDate,"YYYY-MM-DD"));k&&await x(`${h}${k}`)}let O=me(pe(p[0].businessDate,"YYYY-MM-DD"));O&&u.invalidatePrefix(ee(O,o));let A=await Ke(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,o,{forceRefresh:!0});return A&&await P(Ot.parse({type:"report-publish",reportHubId:A.reportHubId,report:A,clientTempId:c}),"publishDailyReport"),A??null},deleteDailyReport:async(i,o,c)=>{let p=await ct(t,i);if(!p.length||p[0].deletedAt)throw new Error("Not Found");if(p[0].userId!==o)throw new Error("Unauthorized");if(await wt(t,i,{deletedAt:new Date,deletedBy:String(o),updatedAt:new Date,updatedBy:String(o)}),u.invalidatePrefix(`daily-report:detail:${i}:user:`),u.invalidatePrefix(w),u.invalidatePrefix(H),await x(v),p[0].businessDate){let T=me(pe(p[0].businessDate,"YYYY-MM-DD"));T&&await x(`${h}${T}`)}await P(Bt.parse({type:"report-delete",reportHubId:i,clientTempId:c,sourceType:p[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:ct,updateDailyReportHub:wt,updateDailyReportInternal:Kt,deleteDailyReportLabel:Qt}}var Ga=fe(1,"[DailyReportExternalSource]"),Wa=(e,t,r,n=Ga)=>{if(!e)return[];try{let a=JSON.parse(e);return Array.isArray(a)?a.map(r).filter(l=>l!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(a){return n.warn(`Failed to parse ${t}:`,a),[]}};import{desc as Zr,sql as Ja}from"drizzle-orm";import{bigint as ie,bit as en,date as Ka,datetime2 as se,foreignKey as Te,index as xe,int as Qa,mssqlSchema as Xa,nvarchar as Z,primaryKey as Oe,uniqueIndex as Za}from"drizzle-orm/mssql-core";function ei(e,t){let r=Xa(e),n=t.userTable,a=r.table("DailyReportHub",{id:ie("id",{mode:"number"}).identity().notNull(),sourceType:Z("source_type",{length:20}).notNull(),sourceId:Z("source_id",{length:100}).notNull(),sourceIdNum:ie("source_id_num",{mode:"number"}).generatedAlwaysAs(Ja`TRY_CAST(source_id AS BIGINT)`),businessDate:Ka("business_date"),userId:ie("user_id",{mode:"number"}),title:Z("title",{length:200}),summary:Z("summary",{length:"max"}),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull(),deletedAt:se("deleted_at"),deletedBy:Z("deleted_by",{length:50})},d=>[Oe({name:`${e}_DailyReportHub_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportHub_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),xe(`${e}_DailyReportHub_business_date_index`).on(d.businessDate),xe(`${e}_DailyReportHub_updated_at_index`).on(d.updatedAt),xe(`${e}_DailyReportHub_source_index`).on(d.sourceType,d.sourceId),xe(`${e}_DailyReportHub_user_id_index`).on(d.userId),xe(`${e}_DailyReportHub_business_date_id_index`).on(Zr(d.businessDate),Zr(d.id)),xe(`${e}_DailyReportHub_deleted_at_index`).on(d.deletedAt)]),l=r.table("DailyReportInternal",{hubId:ie("hub_id",{mode:"number"}).notNull(),body:Z("body",{length:"max"}),metadata:Z("metadata",{length:"max"}),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportInternal_pk`,columns:[d.hubId]}),Te({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]})]),m=r.table("DailyReportComment",{id:ie("id",{mode:"number"}).identity().notNull(),hubId:ie("hub_id",{mode:"number"}).notNull(),userId:ie("user_id",{mode:"number"}).notNull(),body:Z("body",{length:"max"}).notNull(),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportComment_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportComment_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportComment_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),xe(`${e}_DailyReportComment_hub_id_index`).on(d.hubId)]),u=r.table("DailyReportLabel",{id:ie("id",{mode:"number"}).identity().notNull(),userId:ie("user_id",{mode:"number"}),name:Z("name",{length:50}).notNull(),color:Z("color",{length:20}),sortOrder:Qa("sort_order"),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportLabel_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportLabel_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),R=r.table("DailyReportHub_Label",{hubId:ie("hub_id",{mode:"number"}).notNull(),labelId:ie("label_id",{mode:"number"}).notNull(),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportHub_Label_pk`,columns:[d.hubId,d.labelId]}),Te({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[d.labelId],foreignColumns:[u.id]})]),s=r.table("DailyReportUserStatus",{hubId:ie("hub_id",{mode:"number"}).notNull(),userId:ie("user_id",{mode:"number"}).notNull(),isRead:en("is_read").default(!1).notNull(),isStarred:en("is_starred").default(!1).notNull(),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportUserStatus_pk`,columns:[d.hubId,d.userId]}),Te({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),f=r.table("DailyReportAttachment",{id:ie("id",{mode:"number"}).identity().notNull(),hubId:ie("hub_id",{mode:"number"}).notNull(),uploadedBy:ie("uploaded_by",{mode:"number"}),sourceKey:Z("source_key",{length:200}).notNull(),fileName:Z("file_name",{length:255}).notNull(),filePath:Z("file_path",{length:"max"}).notNull(),fileType:Z("file_type",{length:100}),fileSize:ie("file_size",{mode:"number"}),objectCheckedAt:se("object_checked_at"),objectMissingAt:se("object_missing_at"),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportAttachment_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[d.uploadedBy],foreignColumns:[n.id]}),Za(`${e}_DailyReportAttachment_source_unique`).on(d.hubId,d.sourceKey),xe(`${e}_DailyReportAttachment_hub_id_index`).on(d.hubId,d.createdAt)]);return{hub:a,internal:l,comment:m,attachment:f,label:u,hubLabel:R,userStatus:s}}var ti=5e7,on=2e8,ri=1,sn=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})})}),ni=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),tn=75,rn=4,nn="#ffffff",ai=1,ii={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},oi=[/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/],Wt=Object.freeze({ok:!1,reason:"failed"}),an=Object.freeze({ok:!1,reason:"unsupported"}),ln=(e,t)=>{switch(t){case"jpeg":{let r=qt(e);return r===null?null:{layout:r.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:Dr(r)}}case"png":{let r=_r(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ir(e);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},un=(e,t)=>{let r=ni.get(t.depth);if(r===void 0)return null;let n=t.channels*r,a=sn,l=a.wholeImageBuffer[e.layout];return(l.kind==="none"?0:l.kind==="decoded-raster"?t.width*t.height*n:l.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*l.bytesPerPixel)+a.pipelineRows*t.width*n+a.fixedBytes},si=(e,t,r)=>{let n=ln(e,t);return n===null?null:un(n,r)},li=e=>e!==null&&e<=on,ui=e=>{let t=e instanceof Error?e.message:"";return oi.some(r=>r.test(t))?"failed":"unsupported"},ci=e=>{e.cache(!1),e.concurrency(ri),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(ii)});let t=async(n,a,l,m,u)=>{let R=ln(n,a);if(R===null)return an;try{let s=e(n,{limitInputPixels:ti,animated:!1});if(!li(un(R,await s.metadata())))return an;if(u.aborted)return Wt;let f=await s.rotate().resize({width:l,height:m,fit:"inside",withoutEnlargement:!0}).flatten({background:nn}).webp({quality:tn,effort:rn}).toBuffer();return{ok:!0,bytes:new Uint8Array(f),contentType:"image/webp"}}catch(s){return{ok:!1,reason:ui(s)}}},r=async(n,{format:a,maxWidth:l,maxHeight:m,signal:u})=>{if(u.aborted)return Wt;let R=await t(n,a,l,m,u);return u.aborted?Wt:R};return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${tn}-e${rn}/flatten-${nn}/v${ai}`,render:r}};function ss(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=Ct(e.redis),r=new Xe({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=Gt({...e,cache:r,epochs:t}),a=new rt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),l=jt({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes,redis:e.redis,sseReader:a,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:a,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(m=>m.sourceType)])],...l}}export{xr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,Cr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,on as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,sn as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,zt as DAILY_REPORT_SSE_CATCH_UP_BATCH,Qr as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,rt as DailyReportSseReader,ge as DailyReportViewerScope,Xe as SqlResultCache,jt as createDailyReportHandlers,ss as createDailyReportServer,Gt as createDailyReportService,Ct as createEpochStore,ci as createSharpThumbnailRenderer,ei as defineDailyReportSchema,et as generateETag,Pe as isStreamIdLte,be as jsonResponseWithETag,si as predictSharpThumbnailWorkingSetBytes,Wa as transformJsonArray};
|
|
1
|
+
var Zt=e=>{throw TypeError(e)};var er=(e,t,r)=>t.has(e)||Zt("Cannot "+r);var Qe=(e,t,r)=>(er(e,t,"read from private field"),r?r.call(e):t.get(e)),Et=(e,t,r)=>t.has(e)?Zt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ct=(e,t,r,n)=>(er(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var xt=e=>({async getEpoch(t){try{let r=await e?.getClient();if(!r)return null;let n=await r.get(t);return n?Number(n):0}catch{return null}},async incrementEpoch(t){try{let r=await e?.getClient();if(!r)return;await r.incr(t)}catch{}}}),Xe=class{constructor(t,r){this.config=t;this.epochStore=r;this.buckets=new Map;this.inFlight=new Map;this.invalidate=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.maybeRefreshAhead=t=>{let r=t.refreshAheadRatio;if(r===void 0)return;let{cacheKey:n}=t,a=this.buckets.get(n);if(!a)return;let o=t.ttlMsOverride??this.config.defaultTtlMs;if(o-(a.expireAt-Date.now())<o*r||this.inFlight.has(n))return;let u;u=(async()=>{let R=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null,l=await t.fetcher();return this.inFlight.get(n)===u&&this.buckets.set(n,{records:l,expireAt:Date.now()+o,epoch:R}),l})(),this.inFlight.set(n,u),u.catch(()=>{}).finally(()=>{this.inFlight.get(n)===u&&this.inFlight.delete(n)})};this.getOrFetch=async t=>{let{cacheKey:r,forceRefresh:n,snapshot:a}=t,o=this.buckets.get(r);if(n&&(this.buckets.delete(r),this.inFlight.delete(r)),!n&&o&&o.expireAt>Date.now())if(t.epochKey){let u=await this.epochStore.getEpoch(t.epochKey);if(u===null||o.epoch===u)return this.maybeRefreshAhead(t),a?o.records.map(R=>structuredClone(R)):o.records;this.buckets.delete(r)}else return this.maybeRefreshAhead(t),a?o.records.map(u=>structuredClone(u)):o.records;if(!n&&this.inFlight.has(r)){let u=await this.inFlight.get(r);return a?u.map(R=>structuredClone(R)):u}let m;m=(async()=>{let u=t.epochKey?await this.epochStore.getEpoch(t.epochKey):null;t.onFetchStart?.();let R=await t.fetcher();if(n||this.inFlight.get(r)===m){let l=Date.now()+(t.ttlMsOverride??this.config.defaultTtlMs);this.buckets.set(r,{records:R,expireAt:l,epoch:u}),this.buckets.size>500&&this.cleanExpired()}return R})(),n||this.inFlight.set(r,m);try{let u=await m;return a?u.map(R=>structuredClone(R)):u}finally{this.inFlight.get(r)===m&&this.inFlight.delete(r)}};this.flush=t=>{this.buckets.delete(t),this.inFlight.delete(t)};this.clearAll=()=>{this.buckets.clear(),this.inFlight.clear()};this.invalidatePrefix=t=>{for(let r of this.buckets.keys())r.startsWith(t)&&this.buckets.delete(r);for(let r of this.inFlight.keys())r.startsWith(t)&&this.inFlight.delete(r)}}cleanExpired(){let t=Date.now();for(let[r,n]of this.buckets.entries())n.expireAt<=t&&this.buckets.delete(r)}};import{systemSseRuntime as La}from"@aiquants/sse";import{createSseResponse as ka,readLastEventId as Na,startSseHeartbeat as Oa,terminalStreamResponse as Ba}from"@aiquants/sse/server";var Cn=/^\d{4}-\d{2}-\d{2}$/,xn=/^\d{4}\/\d{2}\/\d{2}$/,tr=e=>e<10?`0${e}`:`${e}`,rr=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=tr(e.getMonth()+1),n=tr(e.getDate());return`${t}-${r}-${n}`};var me=e=>{if(e==null)return null;if(e instanceof Date)return rr(e);let t=e.trim();if(t==="")return null;if(Cn.test(t))return t;if(xn.test(t))return t.replaceAll("/","-");let r=new Date(t);return rr(r)};var vt=e=>{let t=2166136261,r=-624069552;for(let n of e){let a=n.reportHubId;t^=a&255,t=Math.imul(t,16777619),t^=a>>>8&255,t=Math.imul(t,16777619),t^=a>>>16&255,t=Math.imul(t,16777619),t^=a>>>24&255,t=Math.imul(t,16777619),r^=a>>>24&255,r=Math.imul(r,16777619),r^=a>>>16&255,r=Math.imul(r,16777619),r^=a>>>8&255,r=Math.imul(r,16777619),r^=a&255,r=Math.imul(r,16777619);let o=n.businessDate;if(o===null)t^=1,t=Math.imul(t,16777619),r^=1,r=Math.imul(r,16777619);else for(let m=0;m<o.length;m++){let u=o.charCodeAt(m);t^=u&255,t=Math.imul(t,16777619),r^=u&255,r=Math.imul(r,16777619)}}return t^=e.length,t=Math.imul(t,16777619),r^=e.length,r=Math.imul(r,16777619),((t>>>0).toString(16).padStart(8,"0")+(r>>>0).toString(16).padStart(8,"0")).replace(/^0+(?=.)/,"")},dt=(e,t)=>e.businessDate!==t.businessDate?e.businessDate===null?1:t.businessDate===null||e.businessDate>t.businessDate?-1:1:t.reportHubId-e.reportHubId,nr=e=>{for(let t=1;t<e.length;t++)if(dt(e[t-1],e[t])>0)return!1;return!0};var ar=(e,t)=>{let r=e.findIndex(n=>dt({businessDate:n.businessDate,reportHubId:n.reportHubId},t)>0);return r===-1?e.length:r};var fe=(e,t,r=console)=>{let n=a=>typeof a=="string"?[`${t} ${a}`]:[t,a];return{debug:(a,...o)=>{e<=0&&r.debug(...n(a),...o)},info:(a,...o)=>{e<=1&&r.info(...n(a),...o)},warn:(a,...o)=>{e<=2&&r.warn(...n(a),...o)},error:(a,...o)=>{e<=3&&r.error(...n(a),...o)}}};import{z as y}from"zod";var ir=15e3,or="lastEventId",vn=/^\d{1,15}-\d{1,15}$/,sr=e=>vn.test(e),Mn=y.object({name:y.string().nullish(),affiliation:y.string().nullish()}),Pn=y.object({name:y.string().nullish(),text:y.string().nullish(),color:y.string().nullish()}),Ln=y.object({id:y.number(),name:y.string().nullish(),color:y.string().nullish()}),lr=y.object({id:y.number(),userId:y.string().nullish(),userName:y.string().nullish(),content:y.string().nullish(),createdAt:y.string().nullish(),isMine:y.boolean()}),kn=y.object({id:y.string(),fileName:y.string(),fileType:y.string().nullable(),fileSize:y.number().nullable(),createdAt:y.string().nullable(),state:y.enum(["present","absent","unknown"]),hasThumbnail:y.boolean().default(!1)}),Mt=y.object({reportHubId:y.number(),date:y.string().nullish(),createdAt:y.string().nullish(),author:y.string().nullish(),userId:y.string().nullish(),sourceType:y.string().nullish(),employeeName:y.string().nullish(),updatedBy:y.string().nullish(),updatedAt:y.string().nullish(),category:y.string().nullish(),creationCategory:y.string().nullish(),visitTimeFrom:y.string().nullish(),visitTimeTo:y.string().nullish(),customerName:y.string().nullish(),interviewers:y.array(Mn),subject:y.string().nullish(),content:y.string().nullish(),externalComments:y.array(Pn),isRead:y.boolean(),isStarred:y.boolean(),labels:y.array(Ln),postedComments:y.array(lr),attachments:y.array(kn).default([])}),Nn=y.object({type:y.literal("connected")}),mt=y.object({type:y.literal("status-update"),reportHubId:y.number(),statusType:y.enum(["star","read"]),value:y.boolean(),clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Pt=y.string().optional(),Lt=y.object({type:y.literal("comment-add"),reportHubId:y.number(),comment:lr,clientTempId:y.string(),recipientRawUserId:y.number().optional(),sourceType:Pt}),kt=y.object({type:y.literal("comment-delete"),reportHubId:y.number(),commentId:y.number(),clientTempId:y.string(),recipientRawUserId:y.number().optional(),sourceType:Pt}),Nt=y.object({type:y.literal("report-create"),reportHubId:y.number(),report:Mt,clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Ot=y.object({type:y.literal("report-update"),reportHubId:y.number(),report:Mt,clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Bt=y.object({type:y.literal("report-publish"),reportHubId:y.number(),report:Mt,clientTempId:y.string(),recipientRawUserId:y.number().optional()}),Ut=y.object({type:y.literal("report-delete"),reportHubId:y.number(),clientTempId:y.string(),sourceType:Pt}),ur=y.discriminatedUnion("type",[Nn,mt,Lt,kt,Nt,Ot,Bt,Ut]);var $t=Object.freeze({tile:Object.freeze({maxWidth:480,maxHeight:320})}),cr=e=>Object.hasOwn($t,e);var On="download",Bn="thumbnail",Un="1";var dr=e=>{let t=e.getAll(Bn),r=e.getAll(On);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&cr(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===Un?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};var mr=(e,t)=>(r,n)=>{let a=n?"markAttachmentPresent":"markAttachmentMissing";e[a](r).catch(o=>{t.error(`${a} failed attachment=${r} message=${o instanceof Error?o.message:"unknown"}`)})};var pt=6e4/1e3,yt=5e3/1e3,pr=(e,t)=>{if(e===null)return!1;for(let r of e.split(",")){let n=r.trim();if((n.startsWith("W/")?n.slice(2):n)===t)return!0}return!1},yr=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),Hn=/^[\x20-\x7E]+$/,Fn=/^[\w.+-]+\/[\w.+-]+/,Ht=e=>e&&Hn.test(e)&&Fn.test(e)?e:null,hr=e=>encodeURIComponent(e).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),fr=e=>e.replace(/[^\x20-\x7E]/g,"_").replace(/["\\]/g,"_"),ht=e=>{switch(e){case"not_found":case"denied":case"invalid_path":return 404;case"too_large":return 413;default:return 502}},br={404:"Attachment not found",413:"Attachment too large",502:"Attachment storage unavailable"},Fe="Attachment request failed";var qn=e=>typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):Array.isArray(e)?"array":typeof e,qe=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${qn(r)}`),ft=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`);var gr=32*1024*1024,Yn=60,Vn=4,zn=120,jn=2,Gn=8*1024*1024,Re=(e,t,r)=>{if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=r)return t;throw qe(e,`an integer >= ${r}`,t)},Me=(e,t,r,n)=>t===void 0?n:Re(e,t,r),Wn=[["attachmentThumbnailRenderer",["readAttachment","attachmentIdCodec"]],["readAttachment",["attachmentIdCodec"]],["attachmentIdCodec",["readAttachment"]],["attachmentMaxBytes",["readAttachment"]],["attachmentRateLimitPerMinute",["readAttachment"]],["attachmentConcurrency",["readAttachment"]],["attachmentThumbnailRateLimitPerMinute",["attachmentThumbnailRenderer"]],["attachmentThumbnailConcurrency",["attachmentThumbnailRenderer"]],["attachmentThumbnailCacheBytes",["attachmentThumbnailRenderer"]]],Ft=e=>{for(let[t,r]of Wn){if(e[t]===void 0)continue;let n=r.find(a=>e[a]===void 0);if(n!==void 0)throw ft(n,`injected when ${t} is given`)}},Rr=(e,t)=>(Ft({attachmentIdCodec:t.idCodec,readAttachment:t.readAttachment,attachmentThumbnailRenderer:t.thumbnailRenderer,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes}),Object.freeze({originalRateLimitPerMinute:Me("attachmentRateLimitPerMinute",e.attachmentRateLimitPerMinute,1,Yn),originalConcurrency:Me("attachmentConcurrency",e.attachmentConcurrency,1,Vn),thumbnailRateLimitPerMinute:Me("attachmentThumbnailRateLimitPerMinute",e.attachmentThumbnailRateLimitPerMinute,1,zn),thumbnailConcurrency:Me("attachmentThumbnailConcurrency",e.attachmentThumbnailConcurrency,1,jn),thumbnailCacheBytes:Me("attachmentThumbnailCacheBytes",e.attachmentThumbnailCacheBytes,0,Gn)}));var bt=e=>{let t=Re("limit",e.limit,1),r=e.queue===null?null:{max:Re("queue.max",e.queue.max,0),maxPerOwner:Re("queue.maxPerOwner",e.queue.maxPerOwner,0),maxWaitMs:Re("queue.maxWaitMs",e.queue.maxWaitMs,1)},n=0,a=[],o=new Map,m=(l,f)=>{let d=(o.get(l)??0)+f;d<=0?o.delete(l):o.set(l,d)},u=()=>{for(;n<t;){let l=a.shift();if(!l)return;m(l.owner,-1),n+=1,l.grant(R())}},R=()=>{let l=!1;return()=>{l||(l=!0,n-=1,u())}};return{acquire:(l,f)=>{if(f.aborted)return Promise.resolve(null);if(n<t)return n+=1,Promise.resolve(R());if(r===null||a.length>=r.max||(o.get(l)??0)>=r.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:d}=r,D=S=>{let I=()=>{let g=a.indexOf(K);g<0||(a.splice(g,1),m(l,-1),$(),S(null))},W=setTimeout(I,d);W.unref?.();let $=()=>{clearTimeout(W),f.removeEventListener("abort",I)},K={owner:l,grant:g=>{$(),S(g)}};a.push(K),m(l,1),f.addEventListener("abort",I,{once:!0})};return new Promise(D)}}};var Jn=1024,Ze=e=>{Re("limitPerMinute",e,1);let t=new Map,r=(m,u)=>{u<=m.lastRefillMs||(m.tokens=Math.min(e,m.tokens+(u-m.lastRefillMs)*e/6e4),m.lastRefillMs=u)},n=(m,u)=>{let R=t.get(m);R&&t.delete(m);let l=R??{tokens:e,lastRefillMs:u,deniedSinceAdmission:0};r(l,u),t.set(m,l);for(let f of t.keys()){if(t.size<=Jn)break;t.delete(f)}return l},a=m=>{if(m.tokens<1)return null;m.tokens-=1;let u=Math.max(0,m.deniedSinceAdmission-1);return m.deniedSinceAdmission=0,{allowed:!0,suppressedDenials:u}},o=m=>(m.deniedSinceAdmission+=1,{allowed:!1,firstDenial:m.deniedSinceAdmission===1});return{consume:(m,u)=>{let R=n(m,u);return a(R)??o(R)},refund:(m,u,R)=>{let l=t.get(m);l&&(r(l,u),l.tokens=Math.min(e,l.tokens+R))}}};var Kn=12e4,Qn=(e,t,r)=>{let n=setTimeout(t,r);n.unref?.();let a=()=>{clearTimeout(n),t()},o=!1;return new ReadableStream({pull(m){if(o){m.close(),a();return}o=!0,m.enqueue(e)},cancel(){a()}})},Sr=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,m=t.attachmentDelivery,u=Ze(e.rateLimitPerMinute),R=bt({limit:e.concurrency,queue:null});return async l=>{let{request:f,delivery:d,attachmentId:D,internalUserId:S,readAttachment:I,cookie:W,fail:$}=l,K=m.maxBytes,g=u.consume(S,Date.now());if(!g.allowed)return g.firstDenial&&a.warn(`429 attachment=${D} viewer=${S} reason=rate_limit`),$(429,"Too many requests",{"Retry-After":String(pt)});g.suppressedDenials>0&&a.warn(`rate_limit_suppressed count=${g.suppressedDenials} viewer=${S}`);let M=await n(f),Y=await t.getAttachmentForUser(M,D,S);if(!Y)return a.warn(`404 attachment=${D} viewer=${S} reason=not_visible`),$(404,"Attachment not found");if(Y.fileSize!=null&&Y.fileSize>K)return a.warn(`413 attachment=${D} viewer=${S} reason=db_size`),$(413,"Attachment too large");let H=await R.acquire(S,f.signal);if(!H)return f.signal.aborted?(a.info(`503 attachment=${D} viewer=${S} reason=aborted`),$(503,"Attachment request aborted")):(a.warn(`503 attachment=${D} viewer=${S} reason=concurrency`),$(503,"Too many concurrent downloads",{"Retry-After":String(yt)}));let b=!1;try{let v=f.method==="HEAD",w=await I(Y.filePath,{maxBytes:K,head:v,principal:r(S),signal:f.signal});if(f.signal.aborted)return a.info(`503 attachment=${D} viewer=${S} reason=aborted`),$(503,"Attachment request aborted");if(!w.ok){let x=ht(w.reason);return w.reason==="not_found"&&o(D,!1),a.warn(`${x} attachment=${D} viewer=${S} reason=${w.reason} code=${w.code??"-"}`),$(x,br[x])}if(w.bytes.byteLength>K)return a.error(`500 attachment=${D} viewer=${S} reason=port_contract code=over_max_bytes`),$(500,Fe);let P=Ht(Y.fileType)??Ht(w.contentType),h=P!==null&&yr.has(P),C=h?P:"application/octet-stream",F=h&&d.kind!=="download"?"inline":"attachment",N=w.size??w.bytes.byteLength,q=new Headers({"Content-Type":C,"Content-Length":String(N),"Content-Disposition":`${F}; filename="${fr(Y.fileName)}"; filename*=UTF-8''${hr(Y.fileName)}`,"Cache-Control":"private, no-store","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return W&&q.append("Set-Cookie",W),o(D,!0),a.info(`200 attachment=${D} viewer=${S} type=${C} disposition=${F} bytes=${N}`),v?new Response(null,{status:200,headers:q}):(b=!0,new Response(Qn(w.bytes,H,Kn),{status:200,headers:q}))}finally{b||H()}}};var _e=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Vi=_e.queueWaitMs+_e.readMs+_e.renderMs+_e.transferMarginMs;import{createHash as Xn}from"crypto";var et=e=>{let t=JSON.stringify(e);return`"${Xn("sha256").update(t).digest("hex")}"`};var Zn=new Set([194,198,202,206]),ea=64,ta=2,Tr=8,Ar=28,Ce=12,qt=8,ra=20,Dr=Ce+qt+10,na=2,Ie=(e,t)=>e[t]<<8|e[t+1],Ye=(e,t,r)=>{let n=0;for(let a=r-1;a>=0;a-=1)n=n*256+e[t+a];return n},Ae=(e,t,r)=>{if(e.byteLength<t+r.length)return!1;for(let n=0;n<r.length;n+=1)if(e[t+n]!==r.charCodeAt(n))return!1;return!0},aa=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,Yt=e=>{if(e[0]!==255||e[1]!==216)return null;let t=null,r=2;for(;r<e.byteLength;){if(e[r]!==255)return null;for(;r<e.byteLength&&e[r]===255;)r+=1;if(r>=e.byteLength)return null;let n=e[r];if(r+=1,n===0||n===216||n===217)return null;if(n===1||n>=208&&n<=215)continue;if(r+2>e.byteLength)return null;let a=Ie(e,r),o=r+2,m=r+a;if(a<2||m>e.byteLength)return null;if(aa(n)){if(t!==null||a<8)return null;let u=Ie(e,o+1),R=Ie(e,o+3),l=e[o+5];if(R===0||u===0||l===0||a!==8+3*l)return null;let f=[];for(let d=0;d<l;d+=1){let D=e[o+7+3*d],S=D>>4,I=D&15;if(S<1||S>4||I<1||I>4)return null;f.push({horizontal:S,vertical:I})}t={width:R,height:u,components:f,progressive:Zn.has(n)}}else if(n===218){if(t===null||a<3)return null;let u=e[o];return u<1||u>4||a!==6+2*u?null:{width:t.width,height:t.height,components:t.components,multiScan:t.progressive||u<t.components.length}}r=m}return null},wr=e=>{if(!e.multiScan)return 0;let t=Math.max(...e.components.map(a=>a.horizontal)),r=Math.max(...e.components.map(a=>a.vertical)),n=0;for(let{horizontal:a,vertical:o}of e.components){let m=Math.ceil(e.width*a/(t*Tr)),u=Math.ceil(e.height*o/(r*Tr));n+=Math.ceil(m/a)*a*Math.ceil(u/o)*o}return n*ea*ta},_r=e=>{if(e.byteLength<24||Ie(e,8)!==0||Ie(e,10)!==13||!Ae(e,12,"IHDR"))return null;let t=Ie(e,16)*65536+Ie(e,18),r=Ie(e,20)*65536+Ie(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},ia=e=>{if(Ae(e,Ce,"VP8 ")){if(e.byteLength<30||(e[20]&1)!==0||e[23]!==157||e[24]!==1||e[25]!==42)return null;let t=Ye(e,26,2)&16383,r=Ye(e,28,2)&16383;return t===0||r===0?null:{width:t,height:r}}if(Ae(e,Ce,"VP8L")){if(e.byteLength<25||e[20]!==47)return null;let t=Ye(e,21,4);return{width:(t&16383)+1,height:Math.floor(t/16384)%16384+1}}return Ae(e,Ce,"VP8X")?e.byteLength<Dr?null:{width:Ye(e,24,3)+1,height:Ye(e,27,3)+1}:null},Ir=e=>{if(_r(e)===null||e.byteLength<=Ar)return null;switch(e[Ar]){case 0:return!1;case 1:return!0;default:return null}},Er=e=>{if(Ae(e,Ce,"VP8 "))return"lossy";if(Ae(e,Ce,"VP8L"))return"lossless";if(!Ae(e,Ce,"VP8X")||e.byteLength<Dr)return null;if((e[ra]&na)!==0)return"animated";let t=!1;for(let r=Ce;r+qt<=e.byteLength;){if(Ae(e,r,"VP8L"))return"lossless";if(Ae(e,r,"VP8 "))return t?"lossy-alpha":"lossy";Ae(e,r,"ALPH")&&(t=!0);let n=Ye(e,r+4,4);r+=qt+n+n%2}return null},Cr={png:_r,jpeg:Yt,webp:ia};var oa=new Set(["image/png","image/jpeg","image/gif","image/webp"]),xr=Object.freeze(["image/webp","image/jpeg","image/png"]),sa={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},la=new Set(xr),ua=e=>typeof e=="string"&&la.has(e),vr=1024*1024,ca=256,gt=(e,t)=>e.fileType===null||!oa.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,da=[137,80,78,71,13,10,26,10],ma=[255,216,255],pa=[[71,73,70,56,55,97],[71,73,70,56,57,97]],ya=[82,73,70,70],ha=[87,69,66,80],tt=(e,t,r)=>{if(e.byteLength<r+t.length)return!1;for(let[n,a]of t.entries())if(e[r+n]!==a)return!1;return!0},Vt=e=>{if(tt(e,da,0))return"png";if(tt(e,ma,0))return"jpeg";for(let t of pa)if(tt(e,t,0))return"gif";return tt(e,ya,0)&&tt(e,ha,8)?"webp":null},Mr=e=>{let t=JSON.stringify([e.rendererId,e.box.maxWidth,e.box.maxHeight,e.attachmentId,e.filePath,e.fileType,e.fileSize]);return{key:t,etag:et([t])}},Pr=(e,t)=>{if(!ua(e.contentType))return"content_type";if(!(e.bytes instanceof Uint8Array))return"bytes";if(e.bytes.byteLength===0)return"empty";if(e.bytes.byteLength>vr)return"too_large";let r=sa[e.contentType];if(Vt(e.bytes)!==r)return"signature";let n=Cr[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},Lr=e=>{Re("maxBytes",e.maxBytes,0),Re("maxEntries",e.maxEntries,0);let t=new Map,r=0,n=a=>{let o=t.get(a);o&&(t.delete(a),r-=o.weight)};return{get:a=>{let o=t.get(a);if(o)return t.delete(a),t.set(a,o),o.entry},set:(a,o)=>{n(a);let m=(o.kind==="thumbnail"?o.bytes.byteLength:0)+ca;if(m>e.maxBytes||e.maxEntries===0)return;let u=o.kind==="thumbnail"?{kind:"thumbnail",bytes:o.bytes.slice(),contentType:o.contentType}:o;t.set(a,{entry:u,weight:m}),r+=m;for(let R of t.keys()){if(r<=e.maxBytes&&t.size<=e.maxEntries)break;n(R)}}}};var kr=()=>{let e=new Map;return{join:(t,r,n)=>{let a=()=>{let R=new AbortController,l=()=>{e.get(t)?.controller===R&&e.delete(t)},d={promise:n(R.signal).finally(l),controller:R,waiters:0};return e.set(t,d),d},o=e.get(t)??a();o.waiters+=1;let m=()=>{o.waiters-=1,!(o.waiters>0)&&(o.controller.abort(),e.get(t)===o&&e.delete(t))};r.aborted?m():r.addEventListener("abort",m,{once:!0});let u=()=>{r.removeEventListener("abort",m)};return o.promise.finally(u)}}};var zt=e=>{let{budgetMs:t,flightSignal:r,call:n,onOverrun:a,onStuck:o}=e,m=Date.now(),u=new AbortController,R=!1,l,f,d=(H,b)=>{let v=setTimeout(H,b);return v.unref?.(),v},D=()=>{o(Date.now()-m)},S=H=>{l=d(()=>{R=!0,H({timedOut:!0}),f=d(D,t),u.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},I=new Promise(S),W=AbortSignal.any([r,u.signal]),$=H=>{H(n(W))},K=new Promise($),g=H=>{clearTimeout(l),clearTimeout(f),R&&a(Date.now()-m,H)},M=K.then(()=>g(null),H=>g({error:H}));return{outcome:Promise.race([K.then(H=>({timedOut:!1,value:H})),I]),settled:M}};var Pe={404:"Attachment not found",500:Fe,502:"Thumbnail unavailable",503:"Too many concurrent thumbnail requests"},Nr=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:a,recordObjectState:o,logger:m}=e,u=(f,d)=>{if(f.fileSize===null||(d.kind==="exact"?d.bytes===f.fileSize:f.fileSize>d.maxBytes))return"verified";let S=d.kind==="exact"?String(d.bytes):`>${d.maxBytes}`;return m.warn(`size_mismatch expected=${f.fileSize} got=${S} attachment=${f.attachmentId} viewer=${f.owner} variant=thumbnail`),"unverified"},R=(f,d)=>(D,S)=>{let I=S===null?"":` message=${S.error instanceof Error?S.error.message:"unknown"}`;m.warn(`${f}_overrun ms=${D} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail${I}`)},l=(f,d)=>D=>{m.warn(`${f}_stuck ms=${D} attachment=${d.attachmentId} viewer=${d.owner} variant=thumbnail`)};return async(f,d)=>{let D=await t.acquire(f.owner,d);if(!D)return{kind:"failure",status:503,reason:d.aborted?"aborted":"queue"};let S=null;try{if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let I=zt({budgetMs:_e.readMs,flightSignal:d,call:w=>f.readAttachment(f.filePath,{maxBytes:n,head:!1,principal:a(f.owner),signal:w}),onOverrun:R("read",f),onStuck:l("read",f)}),W=await I.outcome;if(W.timedOut)return S=I.settled,d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"read_timeout"};if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let $=W.value;if(!$.ok&&$.reason!=="too_large")return $.reason==="not_found"&&o(f.attachmentId,!1),{kind:"failure",status:ht($.reason)===404?404:502,reason:$.reason,code:$.code};if($.ok&&$.bytes.byteLength>n)return{kind:"failure",status:500,reason:"port_contract",code:"over_max_bytes"};let K=u(f,$.ok?{kind:"exact",bytes:$.bytes.byteLength}:{kind:"over",maxBytes:n}),g=w=>(K==="verified"&&r.set(f.key,w),{...w,identity:K});if(!$.ok)return g({kind:"unrenderable",reason:"too_large"});let M=Vt($.bytes);if(M===null)return g({kind:"unrenderable",reason:"signature"});let Y=zt({budgetMs:_e.renderMs,flightSignal:d,call:w=>f.renderer.render($.bytes,{format:M,maxWidth:f.box.maxWidth,maxHeight:f.box.maxHeight,signal:w}),onOverrun:R("render",f),onStuck:l("render",f)}),H=await Y.outcome;if(H.timedOut)return S=Y.settled,d.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};if(d.aborted)return{kind:"failure",status:503,reason:"aborted"};let b=H.value;if(!b.ok)return b.reason==="unsupported"?g({kind:"unrenderable",reason:"unsupported"}):b.reason==="failed"?{kind:"failure",status:502,reason:"render_failed"}:{kind:"failure",status:500,reason:"port_contract",code:"failure_reason"};let v=Pr(b,f.box);return v!==null?{kind:"failure",status:500,reason:"port_contract",code:v}:g({kind:"thumbnail",bytes:b.bytes,contentType:b.contentType})}finally{S===null?D():S.then(D)}}};var Ur=10,fa=1/Ur,Or=1-fa,ba=1024,ga=64,Ra=8,Br="private, no-cache",Sa="no-store",Ta=e=>{switch(e.status){case 404:case 502:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},$r=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:a,recordObjectState:o}=e,m=t.attachmentDelivery,u=Ze(e.rateLimitPerMinute),R=Ze(e.rateLimitPerMinute*Ur),l=bt({limit:e.concurrency,queue:{max:ga,maxPerOwner:Ra,maxWaitMs:_e.queueWaitMs}}),f=Lr({maxBytes:e.cacheBytes,maxEntries:ba}),d=kr(),D=Nr({gate:l,cache:f,maxBytes:m.maxBytes,encodeUserId:r,recordObjectState:o,logger:a}),S=(g,M,Y,H)=>{let b=`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail cache=${H}`;if(M.kind==="failure")return a[Ta(M)](`${M.status} ${b} reason=${M.reason} code=${M.code??"-"}`),g.fail(M.status,Pe[M.status],M.status===503?{"Retry-After":String(yt)}:{});let v=M.identity==="verified"?"":` identity=${M.identity}`;if(M.kind==="unrenderable")return a.info(`404 ${b} reason=${M.reason}${v}`),g.fail(404,Pe[404]);let w=M.identity==="verified"?{"Cache-Control":Br,ETag:Y}:{"Cache-Control":Sa},P=new Headers({"Content-Type":M.contentType,"Content-Length":String(M.bytes.byteLength),...w,"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox","X-Frame-Options":"SAMEORIGIN"});return g.cookie&&P.append("Set-Cookie",g.cookie),a.info(`200 ${b} type=${M.contentType} bytes=${M.bytes.byteLength}${v}`),new Response(M.bytes,{status:200,headers:P})},I=(g,M,Y)=>(M.firstDenial&&a.warn(`429 attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail reason=${Y}`),g.fail(429,"Too many requests",{"Retry-After":String(pt)})),W=(g,M,Y)=>{M.suppressedDenials>0&&a.warn(`${Y}_suppressed count=${M.suppressedDenials} viewer=${g.internalUserId} variant=thumbnail`)},$=g=>{let M=u.consume(g.internalUserId,Date.now());return M.allowed?(W(g,M,"rate_limit"),null):I(g,M,"rate_limit")},K=(g,M)=>{if(!M)return $(g);let Y=R.consume(g.internalUserId,Date.now());return Y.allowed?(W(g,Y,"revalidation_rate_limit"),null):I(g,Y,"revalidation_rate_limit")};return async(g,M)=>{let{request:Y,attachmentId:H,internalUserId:b,readAttachment:v,cookie:w,fail:P}=g,h=$t[M],C=m.thumbnailRenderer;if(!C)return P(404,Pe[404]);let F=Y.headers.get("If-None-Match"),N=F!==null,q=K(g,N);if(q)return q;let x=await n(Y),U=await t.getAttachmentForUser(x,H,b),z=U!==null&>(U,m.maxBytes)?Mr({rendererId:C.id,box:h,attachmentId:H,filePath:U.filePath,fileType:U.fileType,fileSize:U.fileSize}):null;if(z&&pr(F,z.etag)){let E=new Headers({"Cache-Control":Br,ETag:z.etag});return w&&E.append("Set-Cookie",w),a.info(`304 attachment=${H} viewer=${b} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:E})}if(N){let E=$(g);if(E)return E}if(!U)return a.warn(`404 attachment=${H} viewer=${b} variant=thumbnail reason=not_visible`),P(404,Pe[404]);if(!z)return u.refund(b,Date.now(),Or),a.info(`404 attachment=${H} viewer=${b} variant=thumbnail reason=not_eligible`),P(404,Pe[404]);let{key:V,etag:ee}=z,J=f.get(V);if(J)return u.refund(b,Date.now(),Or),S(g,{...J,identity:"verified"},ee,"hit");let Q=E=>D({key:V,attachmentId:H,filePath:U.filePath,fileSize:U.fileSize,box:h,owner:b,readAttachment:v,renderer:C},E),L;try{L=await d.join(V,Y.signal,Q)}catch(E){return a.error(`500 attachment=${H} viewer=${b} variant=thumbnail cache=miss reason=port_exception message=${E instanceof Error?E.message:"unknown"}`),P(500,Pe[500])}return S(g,L,ee,"miss")}};var Aa='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',Hr=e=>{let{authenticate:t,service:r,encodeUserId:n,resolveViewerScope:a,logger:o}=e,m=r.attachmentDelivery,u=Rr(e.tuning,m),R={service:r,encodeUserId:n,resolveViewerScope:a,logger:o,recordObjectState:mr(r,o)},l=Sr({...R,rateLimitPerMinute:u.originalRateLimitPerMinute,concurrency:u.originalConcurrency}),f=$r({...R,rateLimitPerMinute:u.thumbnailRateLimitPerMinute,concurrency:u.thumbnailConcurrency,cacheBytes:u.thumbnailCacheBytes});return async({request:d,params:D})=>{let S=null,I=(W,$,K={})=>{let g=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...K});return S&&g.append("Set-Cookie",S),new Response(JSON.stringify({error:{message:$}}),{status:W,headers:g})};try{let{user:W,cookie:$}=await t(d,{failureRedirect:null});if(S=$??null,!W)return I(401,"Unauthorized");let K=dr(new URL(d.url).searchParams);if(K.kind==="invalid")return I(400,"Invalid attachment request");if(K.kind==="thumbnail"&&d.method!=="GET")return I(405,"Method not allowed",{Allow:"GET"});if(d.method!=="GET"&&d.method!=="HEAD")return I(405,"Method not allowed",{Allow:"GET, HEAD"});let{idCodec:g,readAttachment:M}=m;if(!(g&&M))return I(404,"Attachment not found");if(D.token===void 0)throw new Error(Aa);let Y=g.decode(D.token);if(Y===null||!Number.isSafeInteger(Y)||Y<=0)return I(400,"Invalid attachment token");let H=await r.getUserIdByExternalId(W.id);if(!H)return I(403,"Forbidden");let b={request:d,delivery:K,attachmentId:Y,internalUserId:H,readAttachment:M,cookie:S,fail:I};return K.kind==="thumbnail"?await f(b,K.variant):await l(b)}catch(W){if(W instanceof Response)throw W;return o.error(`500 attachment=? viewer=? reason=unexpected message=${W instanceof Error?W.message:"unknown"}`),I(500,Fe)}}};var Da=fe(1,"[Response]"),be=(e,t,r,n=200,a=Da)=>{let o=et(r),m=e.headers.get("If-None-Match");a.info(`[jsonResponseWithETag] ETag: ${o}, If-None-Match: ${m}`);let u=new Headers({"Content-Type":"application/json","Cache-Control":"private, max-age=0, must-revalidate","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'",ETag:o});return t&&u.append("Set-Cookie",t),e.method==="GET"&&n===200&&m===o?new Response(null,{status:304,headers:u}):new Response(JSON.stringify(r),{status:n,headers:u})};import{systemSseRuntime as wa}from"@aiquants/sse";import{createSharedSource as _a}from"@aiquants/sse/shared-source";var Le=(e,t)=>{let[r,n]=e.split("-").map(Number),[a,o]=t.split("-").map(Number);return r!==a?r<a:n<=o},St="$",Ia=5e3,Ea=100,rt=class{constructor(t){this.config=t;this._lastId=St;this._positioning=null;this._generation=0;this._logger=t.logger??fe(1,"[SSE Reader]"),this._source=this._createSource()}ready(){if(this._lastId!==St)return Promise.resolve();if(this._positioning===null){let t=this._generation;this._positioning=this._readTail().then(r=>{t===this._generation&&(this._positioning=null,r!==null&&this._lastId===St&&(this._lastId=r))})}return this._positioning}subscribe(t,r){return this._source.subscribe({next:n=>{this._lastId=n.id,t(n)},error:n=>r(n instanceof Error?n:new Error(String(n)))})}async destroy(){await this._source.dispose(),this._generation+=1,this._positioning=null,this._lastId=St,this._source=this._createSource()}async _readTail(){try{let t=await this.config.redis?.getClient();if(!t)return null;let r=await t.xRevRange(this.config.streamKey,"+","-",{COUNT:1});return r.length>0?r[0].id:"0-0"}catch(t){return this._logger.warn("Failed to resolve stream tail anchor; falling back to $:",t),null}}_createSource(){return _a({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:wa,onListenerError:t=>this._logger.error("SSE reader subscriber threw:",t),onStopError:t=>this._logger.error("SSE reader failed to stop:",t)})}async _start(t){let r=await this.config.redis?.createClient();if(!r)throw new Error("Failed to create Redis client for SSE reader");r.on("error",o=>{this._logger.error("Redis client error:",o)}),await this.ready();let n=!1,a=this._readLoop(r,t,()=>n);return async()=>{if(n=!0,r.isOpen)try{await r.quit()}catch{}await a}}async _readLoop(t,r,n){let a=this._lastId;try{for(;!n()&&t.isOpen;){let o=await t.xRead([{key:this.config.streamKey,id:a}],{BLOCK:Ia,COUNT:Ea});if(o)for(let m of o)for(let u of m.messages)a=u.id,this._invalidateCaches(u.message),r.next({id:u.id,message:u.message})}}catch(o){n()||(this._logger.error("xRead loop error:",o),r.fail(o instanceof Error?o:new Error(String(o))));return}n()||r.fail(new Error("Redis client for SSE reader closed unexpectedly"))}_invalidateCaches(t){try{let r=t?.data?JSON.parse(t.data):null,n=r?.type;if((n==="report-create"||n==="report-delete"||n==="report-publish")&&this.config.cache.invalidatePrefix("daily-report:ids"),n==="comment-add"||n==="comment-delete"||n==="status-update"){let a=r?.reportHubId;typeof a=="number"&&(this.config.cache.invalidate(`daily-report:detail:${a}`),this.config.cache.invalidatePrefix(`daily-report:detail:${a}:user:`))}}catch{}}};import{inArray as Ca,sql as Fr}from"drizzle-orm";var xa="",va=64,Ma=e=>e.toLowerCase(),Pa=e=>e.trim().toLowerCase();function qr(e){if(e==null)return null;if(!Array.isArray(e))return new Set;let t=new Set;for(let r of e){if(typeof r!="string")continue;let n=Pa(r);n.length>0&&t.add(n)}return t}function De(e,t){return e===null?!0:t==null?!1:e.has(Ma(t))}function ke(e){return e!==null&&e.size===0}function Vr(e,t){if(t!==null)return t.size===0?Fr`1 = 0`:Ca(Fr`LOWER(${e})`,[...t])}var Ve,ze,nt=class nt{constructor(t,r){Et(this,Ve);Et(this,ze);Ct(this,Ve,t),Ct(this,ze,r)}get visible(){return Qe(this,Ve)===null?null:new Set(Qe(this,Ve))}get commentable(){return Qe(this,ze)===null?null:new Set(Qe(this,ze))}static restrictTo(t){let r=typeof t=="object"&&t!==null&&"read"in t,n=qr(r?t.read:t),a=r?t.comment:void 0;if(a===void 0)return new nt(n,n);let o=qr(a),m=new Set;for(let u of o??[])n.has(u)&&m.add(u);return new nt(n,m)}static unrestricted(t){return new nt(null,null)}};Ve=new WeakMap,ze=new WeakMap;var ge=nt;function at(e){let t=Yr(e.visible),r=Yr(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function Yr(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(xa);if(t.length<=va)return`s:${t}`;let r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return`sh:${(r>>>0).toString(16)}`}var Ua=(e,t)=>{let r=new Headers({"Content-Type":"application/json"});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Tt=30,Qr=4e3,$a="stream interrupted by server error",Ha=/^\d{4}-\d{2}-\d{2}$/,Fa=15e3,zr=Symbol("ids-stream-heartbeat"),jr=864e5,qa={baseMs:2e3,jitterMs:8e3},Xr=6e4,jt=1e3,Gr=JSON.stringify({type:"connected"}),Wr="0-0",Ya=/^[0-9a-f]{1,16}$/,Va=e=>{let t=e.searchParams.get("cursor_report_hub_id"),r=e.searchParams.get("cursor_business_date"),n=e.searchParams.get("cursor_snapshot"),a=n!==null&&Ya.test(n)?n:null;if(t===null)return r===null?{cursor:null,snapshot:a}:{invalid:!0};let o=Number.parseInt(t,10);return!Number.isSafeInteger(o)||String(o)!==t||o<=0?{invalid:!0}:r===null?{cursor:{businessDate:null,reportHubId:o},snapshot:a}:Ha.test(r)?{cursor:{businessDate:r,reportHubId:o},snapshot:a}:{invalid:!0}};async function*Jr(e,t,r,n){let a=t?ar(e,t):0,o=!0;for(;;){let m=e.slice(a,a+(o?r:Qr));a+=m.length;let u=a>=e.length,R=m[m.length-1];if(yield{kind:"chunk",items:m,nextCursor:u||!R?null:{businessDate:R.businessDate,reportHubId:R.reportHubId},isLast:u,...o?{total:e.length}:{},...o?{streamAnchor:n.streamAnchor}:{},snapshot:n.snapshot,...o&&n.restarted?{restarted:!0}:{}},o=!1,u)return}}var Kr=(e,t,r,n)=>{let a=new TextEncoder,o=!1,m=null,u=new ReadableStream({async pull(l){if(o||r.signal.aborted){await t.return(void 0).catch(()=>{});try{l.close()}catch{}return}let f=null;try{m===null&&(m=t.next());let d=new Promise(W=>{f=setTimeout(()=>W(zr),Fa)}),D=await Promise.race([m,d]);if(f!==null&&(clearTimeout(f),f=null),D===zr){if(o||r.signal.aborted){await t.return(void 0).catch(()=>{});try{l.close()}catch{}return}l.enqueue(a.encode(`
|
|
2
|
+
`));return}m=null;let{value:S,done:I}=D;if(I){l.close();return}if(o||r.signal.aborted){await t.return(void 0).catch(()=>{});try{l.close()}catch{}return}l.enqueue(a.encode(`${JSON.stringify(S)}
|
|
3
|
+
`))}catch(d){if(f!==null&&clearTimeout(f),m=null,o||r.signal.aborted)return;n.error(`ids-stream emission failed: ${d instanceof Error?d.message:String(d)}`);try{let D={kind:"error",error:$a};l.enqueue(a.encode(`${JSON.stringify(D)}
|
|
4
|
+
`)),l.close()}catch{}}},cancel(){o=!0,t.return(void 0).catch(()=>{})}}),R=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform","X-Content-Type-Options":"nosniff"});return e&&R.append("Set-Cookie",e),new Response(u,{status:200,headers:R})},za=(e,t,r,n)=>{if(r===null&&n===null)return!0;let a=typeof t.sourceType=="string"?t.sourceType:void 0;switch(e.type){case"connected":case"status-update":return!0;case"report-create":case"report-update":case"report-publish":return De(r,e.report.sourceType);case"comment-add":case"comment-delete":return De(n,a??"Internal");case"report-delete":return De(r,a)}},ja=["externalComments","postedComments"],Ga=(e,t,r)=>{if(r===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"||De(r,e.report.sourceType))return!1;let n=t.report;if(typeof n!="object"||n===null)return!1;let a=n;for(let o of ja)a[o]=[];return!0};function Gt(e){let{authenticate:t,service:r,encodeUserId:n,redis:a,sseReader:o,streamKey:m}=e,u=e.loginRedirectPath??"/auth/login",R=e.logger??fe(3,"[DailyReportAPI]"),l=e.logger??fe(3,"[DailyReportVisibility]"),f=e.logger??fe(1,"[DailyReportSSE]"),d=e.logger??fe(1,"[DailyReportAttachment]"),D=async(b,v="initial")=>{let w=e.resolveVisibleSourceTypes;if(!w)return ge.unrestricted("no visibility port injected: this deployment does not restrict by source type");try{let P=await w(b,{reason:v});return P==null?ge.unrestricted("visibility port returned null/undefined: this deployment opts out of source-type filtering"):ge.restrictTo(P)}catch(P){return l.error("resolveVisibleSourceTypes threw; failing closed (deny all)",P),ge.restrictTo([])}},S=async({request:b})=>{let{user:v,cookie:w}=await t(b,{failureRedirect:u}),P=new Headers;w&&P.append("Set-Cookie",w);let h=await r.getUserIdByExternalId(v.id),C=h?n(h):null;return{data:{user:v,userId:C},headers:P}},I={"business-date":async(b,v,w,P,h)=>{let C=me(b.searchParams.get("businessDate")),F=b.searchParams.get("forceRefresh")==="true";if(!C)return be(w,v,{error:{message:"Invalid business date"}},400);let N=await r.getDailyReportsByBusinessDateByExternalId(h,C,P.id,{forceRefresh:F});return be(w,v,{businessDate:C,reports:N},200)},"ids-stream":async(b,v,w,P,h)=>{let C=Va(b);if("invalid"in C)return be(w,v,{error:{message:"Invalid cursor"}},400);let F=b.searchParams.get("forceRefresh")==="true",N=!1,q=null,x=null,U=new Promise((V,ee)=>{q=V,x=ee});U.catch(()=>{});let oe=r.getDailyReportIdsByExternalId(h,P.id,{forceRefresh:F,onFetchStart:C.cursor?void 0:()=>{N=!0,r.readSseStreamAnchor().then(V=>r.getDailyReportIdsFirstPageByExternalId(h,P.id,Tt).then(ee=>({items:ee,streamAnchor:V}))).then(V=>q?.(V),V=>x?.(V))}});if(oe.catch(()=>{}),C.cursor){let{items:V,streamAnchor:ee}=await oe,J=vt(V),Q=C.snapshot!==null&&C.snapshot===J;return Kr(v,Jr(V,Q?C.cursor:null,Tt,{snapshot:J,restarted:!Q,streamAnchor:ee}),w,R)}let z=(async function*(){let V=await Promise.race([oe.then(Q=>({kind:"full",source:Q}),Q=>({kind:"full-error",error:Q})),U.then(Q=>({kind:"page",page:Q}),()=>({kind:"page-error"}))]),ee=null,J=!1;if(V.kind==="full")ee=V.source;else if(V.kind==="page"){let{items:Q,streamAnchor:L}=V.page;if(Q.length<Tt){yield{kind:"chunk",items:Q,nextCursor:null,isLast:!0,total:Q.length,streamAnchor:L};return}yield{kind:"chunk",items:Q,nextCursor:null,isLast:!1,provisional:!0},J=!0}else if(V.kind==="full-error"&&N){let Q=await U.catch(()=>null);Q&&Q.items.length>0&&(yield{kind:"chunk",items:Q.items,nextCursor:null,isLast:!1,provisional:!0})}ee===null&&(ee=await oe),yield*Jr(ee.items,null,J?Qr:Tt,{snapshot:vt(ee.items),streamAnchor:ee.streamAnchor})})();return Kr(v,z,w,R)},report:async(b,v,w,P,h)=>{let C=b.searchParams.get("reportHubId"),F=b.searchParams.get("forceRefresh")==="true",N=C?Number.parseInt(C,10):NaN;if(!Number.isFinite(N)||N<=0)return be(w,v,{error:{message:"Invalid reportHubId"}},400);let q=await r.getDailyReportDetailByIdByExternalId(h,N,P.id,{snapshot:!0,forceRefresh:F});return q?be(w,v,{report:q},200):be(w,v,{error:{message:"Report not found"}},404)}},W=async({request:b,params:v})=>{let{user:w,cookie:P}=await t(b,{failureRedirect:null}),h=P??null;if(!w)return be(b,h,{error:{message:"Unauthorized"}},401);if(b.method!=="GET")return be(b,h,{error:{message:"Method not allowed"}},405);let C=v.endpoint??"",F=I[C];if(!F)return be(b,h,{error:{message:"Unknown endpoint"}},404);let N=Date.now();try{let q=new URL(b.url),x=await D(b);return await F(q,h,b,w,x)}catch(q){let x=Date.now()-N,U=q instanceof Error?q:new Error(String(q));return R.error(`500 endpoint=${C} elapsed=${x}ms name=${U.name} code=${"code"in U?U.code:"N/A"} message=${U.message}`),R.error("Stack:",U.stack),be(b,h,{error:{message:"Internal Server Error"}},500)}},$=async({request:b,params:v})=>{let{user:w,cookie:P}=await t(b,{failureRedirect:null}),h=(F,N)=>Ua(F,{...N,setCookie:P});if(!w)return h({error:"Unauthorized"},{status:401});let C=Date.now();try{if(v.endpoint!=="action")return h({error:"Unknown endpoint"},{status:404});let N=await r.getUserIdByExternalId(w.id);if(!N)return h({error:"User not found"},{status:404});let q=await D(b),x=await b.formData(),U=x.get("intent"),oe=x.get("reportHubId"),z=oe?Number(oe):NaN,V=x.get("businessDate"),ee=Number(x.get("operationTimestamp")),J=x.get("clientTempId");if(U==="clearCache")return e.enableDevCacheClear?(await r.clearCache(),h({status:"OK",intent:"clearCache"})):h({error:"Invalid intent"},{status:400});if(!J)return h({error:"clientTempId required"},{status:400});if(U!=="create"&&(!z||Number.isNaN(z)))return h({error:"Invalid reportHubId"},{status:400});let Q=async(L,E,te)=>{let ye=x.get(E);if(ye===null)return h({error:`${E} required`},{status:400});try{let le=await te(ye==="true");return h({status:"OK",intent:L,updatedStatus:{isStarred:le.isStarred,isRead:le.isRead},operationTimestamp:ee,reportHubId:String(z),clientTempId:J})}catch(le){if(le instanceof Error&&le.message==="Not Found")return h({error:"Report not found"},{status:404});throw le}};switch(U){case"create":{if(!V)return h({error:"businessDate required"},{status:400});let L=await r.createDailyReport(N,V,J);return h({status:"OK",intent:"create",report:L,reportHubId:String(L.reportHubId),clientTempId:J})}case"update":{let L=x.get("title"),E=x.get("content");try{return await r.updateDailyReport(z,N,{title:L,content:E},J),h({status:"OK",intent:"update",reportHubId:String(z),clientTempId:J})}catch(te){if(te instanceof Error){if(te.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(te.message==="Not Found")return h({error:"Report not found"},{status:404})}throw te}}case"publish":try{let L=await r.publishDailyReport(z,N,J);return h({status:"OK",intent:"publish",reportHubId:String(z),clientTempId:J,report:L})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return h({error:"Report not found"},{status:404})}throw L}case"delete":try{return await r.deleteDailyReport(z,N,J),h({status:"OK",intent:"delete",reportHubId:String(z),clientTempId:J})}catch(L){if(L instanceof Error){if(L.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(L.message==="Not Found")return h({error:"Report not found"},{status:404})}throw L}case"toggleStar":return await Q("toggleStar","isStarred",L=>r.setStarStatus(q,N,z,V,L,J));case"toggleRead":return await Q("toggleRead","isRead",L=>r.setReadStatus(q,N,z,V,L,J));case"addComment":{let L=x.get("content");if(!L)return h({error:"Content required"},{status:400});try{let E=await r.addComment(q,N,z,L,V,J),te={...E,userId:E.userId};return h({status:"OK",intent:"addComment",newComment:te,reportHubId:String(z),clientTempId:J})}catch(E){if(E instanceof Error){if(E.message==="Not Found")return h({error:"Report not found"},{status:404});if(E.message.startsWith("Comments are restricted"))return h({error:"Comments are restricted for this report"},{status:403})}throw E}}case"deleteComment":{let L=Number(x.get("commentId"));if(!L||Number.isNaN(L))return h({error:"Invalid commentId"},{status:400});try{return await r.deleteComment(q,N,z,L,V,J),h({status:"OK",reportHubId:String(z),deletedCommentId:String(L),clientTempId:J})}catch(E){if(E instanceof Error){if(E.message==="Unauthorized")return h({error:"Unauthorized"},{status:403});if(E.message==="Not Found")return h({error:"Comment not found"},{status:404})}throw E}}default:return h({error:"Invalid intent"},{status:400})}}catch(F){if(F instanceof Response)throw F;let N=Date.now()-C,q=F instanceof Error?F:new Error(String(F));return R.error(`500 action elapsed=${N}ms name=${q.name} message=${q.message}`),R.error("Stack:",q.stack),h({error:"Internal Server Error"},{status:500})}},K=(b,v)=>{b.writeEvent({event:null,id:v,data:Gr})},g=(b,v,w,P)=>{if(w.data)try{let h=JSON.parse(w.data),C=ur.safeParse(h);if(!C.success){f.error("SSE message validation failed:",C.error.format());return}let F=C.data,N=typeof h.recipientRawUserId=="number"?h.recipientRawUserId:void 0;if((F.type==="status-update"||N!==void 0)&&N!==P.internalUserId||!za(F,h,P.visibleSet,P.commentableSet)){K(b,v);return}let x=Ga(F,h,P.commentableSet),U;if("recipientRawUserId"in h){let{recipientRawUserId:oe,...z}=h;U=JSON.stringify(z)}else x?U=JSON.stringify(h):U=w.data;b.writeEvent({event:null,id:v,data:U})}catch(h){f.error(`[SSE:${P.internalUserId}] processEntry error:`,h)}},M=async(b,v)=>{let{request:w,internalUserId:P,cursor:h}=v,C=v.initialScope.visible,F=v.initialScope.commentable,N=0,q=setInterval(()=>{let E=++N;D(w,"refresh").then(te=>{E===N&&(C=te.visible,F=te.commentable)})},Xr);b.onClose(()=>clearInterval(q));let x=h===null?Wr:h,U=h!==null&&a!==void 0,oe=[],z=null,V=E=>{Le(E.id,x)||(x=E.id,g(b,E.id,E.message,{internalUserId:P,visibleSet:C,commentableSet:F}))},ee=async(E,te)=>{let[ye]=await E.xRange(m,"-","+",{COUNT:1});return ye!==void 0&&!Le(ye.id,te)},J=async(E,te)=>{if(await ee(E,te))return!1;let ye=te;for(;;){let le=await E.xRange(m,ye,"+",{COUNT:jt}),Be=le[0];if(Be!==void 0&&Be.id!==ye&&await ee(E,ye))return!1;for(let ot of le){if(z!==null&&Le(z,ot.id))return!0;V(ot)}let it=le.at(-1);if(le.length<jt||it===void 0||b.isClosed())return!0;ye=it.id}},Q=o.subscribe(E=>{if(!U){V(E);return}Le(E.id,x)||(z===null&&(z=E.id),oe.push(E))},E=>{f.error(`[SSE:${P}] Fan-Out reader error:`,E),b.close()});if(b.onClose(Q),h===null){await o.ready();try{let E=await a?.getClient();if(E){let te=await E.xRevRange(m,"+","-",{COUNT:1});te.length>0&&!Le(te[0].id,x)&&(x=te[0].id)}}catch{}}if(b.writeEvent({event:null,id:x===Wr?null:x,data:Gr}),Oa(b,{intervalMs:ir,retry:qa,runtime:La}),h===null||a===void 0)return;await o.ready();let L=await a.getClient();if(L===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await J(L,h)){b.writeRetry(jr),b.writeEvent({event:"resync-required",id:null,data:""}),b.close();return}U=!1;for(let E of oe.splice(0))V(E)},Y=async({request:b,params:v})=>{let w,P=()=>{let C=new Headers;return w!==void 0&&C.append("Set-Cookie",w),C},h=C=>Ba(C,{data:"",retryMs:jr,headers:P()});try{let C=await t(b,{failureRedirect:null});w=C.cookie;let{user:F}=C;if(!F)return h("auth-required");let N=await r.getUserIdByExternalId(F.id);if(!N)return h("forbidden");if(v.endpoint!=="updates")return new Response("Not Found",{status:404,headers:P()});let q=Na(b,or);if(q!==null&&!sr(q))return f.warn(`[SSE:${N}] malformed resume cursor; asking the client to resync`),h("resync-required");let x=await D(b);return ka({requestSignal:b.signal,headers:P(),onError:(U,oe)=>f.error(`[SSE:${N}] ${oe} failed:`,U),produce:U=>M(U,{request:b,internalUserId:N,cursor:q,initialScope:x})})}catch(C){if(C instanceof Response)throw C;let F=C instanceof Error?C:new Error(String(C));return f.error(`500 sse name=${F.name} message=${F.message}`),new Response("Internal Server Error",{status:500,headers:P()})}},H=Hr({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:D,logger:d,tuning:e});return{index:{loader:S},api:{loader:W,action:$},sse:{loader:Y},attachment:{loader:H}}}import{runWithTransactionRetry as Wa}from"@aiquants/mssql";import{aliasedTable as je,and as ne,asc as At,desc as Ge,eq as _,getColumns as Ja,inArray as Se,isNull as he,or as We,sql as Zr}from"drizzle-orm";var Ne=e=>Ja(e),Ka=e=>{if(e!==void 0){if(typeof e!="object"||e===null)throw qe("attachmentThumbnailRenderer","an object with id and render",e);if(e.render===void 0)throw ft("attachmentThumbnailRenderer.render","a function");if(typeof e.render!="function")throw qe("attachmentThumbnailRenderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw qe("attachmentThumbnailRenderer.id","a non-blank string naming the rendering pipeline version",e.id);return e}},pe=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),a=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),o=String(r.getMonth()+1).padStart(2,"0"),m=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${a}-${o}-${m}`;let u=String(r.getHours()).padStart(2,"0"),R=String(r.getMinutes()).padStart(2,"0"),l=String(r.getSeconds()).padStart(2,"0");return`${a}-${o}-${m} ${u}:${R}:${l}`};function Wt(e){let{db:t,tables:r,userTable:n,resolveUserId:a,encodeUserId:o,redis:m,cache:u,epochs:R}=e,{hub:l,internal:f,comment:d,label:D,hubLabel:S,userStatus:I}=r,W=e.externalSources??[],$=e.draftLabelNames&&e.draftLabelNames.length>0?e.draftLabelNames:[e.draftLabelName??"\u4E0B\u66F8\u304D"],K=$[0]??"\u4E0B\u66F8\u304D",g=e.logger??fe(1,"[DailyReportService]");Ft({attachmentIdCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,attachmentThumbnailRenderer:e.attachmentThumbnailRenderer,attachmentMaxBytes:e.attachmentMaxBytes});let M=Object.freeze({idCodec:e.attachmentIdCodec,readAttachment:e.readAttachment,thumbnailRenderer:Ka(e.attachmentThumbnailRenderer),maxBytes:Me("attachmentMaxBytes",e.attachmentMaxBytes,1,gr)}),Y=i=>Wa(s=>t.transaction(c=>s(()=>i(c))),e.transactionRetry),H="daily-report:ids",b=e.idsTtlMs??18e4,v="daily-report:ids:epoch",w="daily-report:business-date:",P=e.businessDateTtlMs??3e5,h="daily-report:date-epoch:",C="daily-report:detail-epoch:",N=`${e.streamKey??"daily-report:sse-stream"}:v2`,q=e.streamMaxLen??1e4,x=i=>R.incrementEpoch(i),U=i=>Vr(l.sourceType,i),oe=(i,s)=>`${H}:user:${i}:st:${s}`,z=i=>`${H}:user:${i}:`,V=(i,s,c)=>`daily-report:date:${i}:user:${s}:st:${c}`,ee=(i,s)=>`daily-report:date:${i}:user:${s}:`,J=(i,s,c)=>`daily-report:detail:${i}:user:${s}:st:${c}`,Q=(i,s)=>`daily-report:detail:${i}:user:${s}:`,L=async(i,s)=>{let c=await m?.getClient();if(!c){g.warn(`[SSE] Redis client unavailable (${s})`);return}let p=Date.now();try{await c.xAdd(N,"*",{data:JSON.stringify(i)},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:q}});let T=Date.now()-p;T>1e3&&g.warn(`[SSE] Slow publish (${s}): ${T}ms`)}catch(T){g.error(`[SSE] Redis publish failed (${s}):`,T)}},E=async()=>{try{let i=await m?.getClient();if(i===void 0)return null;let[s]=await i.xRevRange(N,"+","-",{COUNT:1});return s===void 0?null:s.id}catch(i){return g.error("[DailyReportService] SSE stream anchor read failed",i),null}},te=i=>i==null||i===""?null:/^\d+$/.test(i)?o(Number(i)):i,ye=()=>{let i={};for(let s of W)i[`ext_${s.sourceType}`]=Ne(s.table);return i},le=i=>{let s=i;for(let c of W)s=s.leftJoin(c.table,ne(_(l.sourceType,c.sourceType),_(l.sourceIdNum,c.idColumn)));return s},Be=(i,s,c)=>{let{hub:p,internal:T}=s,O=p.summary,A=[],k=null,B=null,X=null,j=null,re=null,ue=null,$e=[],Ee=W.find(G=>G.sourceType===p.sourceType),He=Ee?s[`ext_${Ee.sourceType}`]:void 0;if(Ee&&He){let G=Ee.mapRow(He);G.content!==void 0&&(O=G.content),G.employeeName!==void 0&&(ue=G.employeeName),G.category!==void 0&&(k=G.category),G.creationCategory!==void 0&&(B=G.creationCategory),G.visitTimeFrom!==void 0&&(X=G.visitTimeFrom),G.visitTimeTo!==void 0&&(j=G.visitTimeTo),G.customerName!==void 0&&(re=G.customerName),G.interviewers!==void 0&&(A=G.interviewers),G.externalComments!==void 0&&($e=G.externalComments)}else p.sourceType==="Internal"&&T&&(O=T.body);let we=(s.labels??[]).map(G=>({id:G.id,name:G.name,color:G.color})),ce=s.postedCommentRows??[],ae=De(i.commentable,p.sourceType),de=B?$.includes(B):!1,It=Ue?.[0]??null;return de&&It&&!we.some(G=>G.id===It)&&we.push({id:It,name:K,color:null}),{reportHubId:p.id,date:pe(p.businessDate,"YYYY-MM-DD"),author:s.creatorName??te(p.createdBy)??"",userId:p.userId?o(p.userId):"",sourceType:p.sourceType??"Internal",createdAt:pe(p.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:pe(p.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:te(p.updatedBy),employeeName:ue??s.creatorName??te(p.createdBy),category:k,creationCategory:B,visitTimeFrom:X,visitTimeTo:j,customerName:re,interviewers:A,subject:p.title,content:O,externalComments:ae?$e:[],isRead:s.isRead??!1,isStarred:s.isStarred??!1,labels:we,postedComments:ce.filter(G=>ae||c!==void 0&&G.userId===c).map(G=>({...G,userId:o(G.userId),isMine:c?G.userId===c:!1})),attachments:s.attachments}},it=async(i,s)=>{let c=je(S,"draft_label"),p=await ve();return(await t.select({reportHubId:l.id,businessDate:l.businessDate,sourceType:l.sourceType}).from(l).leftJoin(c,ne(_(c.hubId,l.id),Se(c.labelId,p))).where(ne(he(l.deletedAt),We(_(l.userId,s),he(l.userId),he(c.hubId)),U(i.visible))).orderBy(Ge(l.businessDate),Ge(l.id))).map(O=>({...O,businessDate:pe(O.businessDate,"YYYY-MM-DD")}))},ot=async(i,s,c)=>{let p=await Je(s);if(!p)return[];if(ke(i.visible))return[];let T=je(S,"draft_label"),O=await ve();return(await t.select({reportHubId:l.id,businessDate:l.businessDate,sourceType:l.sourceType}).top(c).from(l).leftJoin(T,ne(_(T.hubId,l.id),Se(T.labelId,O))).where(ne(he(l.deletedAt),We(_(l.userId,p),he(l.userId),he(T.hubId)),U(i.visible))).orderBy(Ge(l.businessDate),Ge(l.id))).map(k=>({...k,businessDate:pe(k.businessDate,"YYYY-MM-DD")}))},dn=async(i,s)=>{let c=await le(t.select({hub:Ne(l),internal:Ne(f),creatorName:n.displayName,...ye()}).from(l)).leftJoin(f,_(l.id,f.hubId)).leftJoin(n,_(l.userId,n.id)).where(ne(_(l.businessDate,Zr`${s}`),he(l.deletedAt),U(i.visible))).orderBy(Ge(l.id)),p=await ut(c.map(T=>T.hub.id));return c.map(T=>Be(i,{...T,attachments:p.get(T.hub.id)??[]}))},mn=i=>`${w}${i}`,st=new Map,Je=async i=>{if(!e.disableUserIdCache&&st.has(i))return st.get(i)??null;let s=await a(i);return s!==null&&!e.disableUserIdCache&&st.set(i,s),s},pn=async(i,s,{forceRefresh:c=!1,snapshot:p=!1,ttlMsOverride:T,onFetchStart:O}={})=>{let A=await Je(s);if(!A)return{items:[],streamAnchor:null};if(ke(i.visible))return{items:[],streamAnchor:await E()};let k=oe(A,at(i)),[B]=await u.getOrFetch({cacheKey:k,fetcher:async()=>{let X=await E(),j=await it(i,A);return nr(j)?[{items:j,streamAnchor:X}]:(g.warn("[DailyReportService] ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)"),[{items:[...j].sort(dt),streamAnchor:X}])},onFetchStart:O,forceRefresh:c,snapshot:p,ttlMsOverride:T??b,epochKey:v,refreshAheadRatio:.5});if(B===void 0)throw new Error("[DailyReportService] ids cache returned no record");return B},yn=(i,s,{forceRefresh:c=!1,snapshot:p=!1,ttlMsOverride:T}={})=>{let O=me(s);return O?ke(i.visible)?Promise.resolve([]):u.getOrFetch({cacheKey:`${mn(O)}:st:${at(i)}`,fetcher:()=>dn(i,O),forceRefresh:c,snapshot:p,ttlMsOverride:T??P}):Promise.resolve([])},Ue=null,lt=async()=>(Ue!==null||(Ue=(await t.select({id:D.id}).from(D).where(Se(D.name,$)).orderBy(D.id)).map(s=>s.id)),Ue),ve=async()=>{let i=await lt();return i.length>0?i:[-1]},Dt=async()=>{let i=await lt();if(i.length===0)return null;let[s]=await t.select({id:D.id}).top(1).from(D).where(_(D.name,K));return s?.id??i[0]},hn=(i,s)=>s!=null?"absent":i!=null?"present":"unknown",ut=async i=>{let s=new Map,c=r.attachment,p=M.idCodec;if(i.length===0||!c||!p)return s;let T=M.thumbnailRenderer!==void 0&&M.readAttachment!==void 0,O=await t.select({id:c.id,hubId:c.hubId,fileName:c.fileName,fileType:c.fileType,fileSize:c.fileSize,createdAt:c.createdAt,objectCheckedAt:c.objectCheckedAt,objectMissingAt:c.objectMissingAt}).from(c).where(Se(c.hubId,i)).orderBy(At(c.createdAt),At(c.id));for(let A of O){let k=A.fileType?String(A.fileType):null,B=A.fileSize!=null?Number(A.fileSize):null,X=hn(A.objectCheckedAt,A.objectMissingAt),j={id:p.encode(Number(A.id)),fileName:String(A.fileName),fileType:k,fileSize:B,createdAt:pe(A.createdAt,"YYYY-MM-DD HH:mm:ss"),state:X,hasThumbnail:T&&X!=="absent"&>({fileType:k,fileSize:B},M.maxBytes)},re=s.get(Number(A.hubId));re?re.push(j):s.set(Number(A.hubId),[j])}return s},fn=async(i,s,c)=>{let p=r.attachment;if(!p||ke(i.visible))return null;let T=await ve(),O=je(S,"draft_label");return(await t.select({fileName:p.fileName,filePath:p.filePath,fileType:p.fileType,fileSize:p.fileSize}).top(1).from(p).innerJoin(l,_(l.id,p.hubId)).leftJoin(O,ne(_(O.hubId,l.id),Se(O.labelId,T))).where(ne(_(p.id,s),he(l.deletedAt),We(_(l.userId,c),he(O.hubId)),U(i.visible))))[0]??null},bn=async i=>{let s=r.attachment;if(!s)return;let c=new Date;try{await t.update(s).set({objectCheckedAt:c,objectMissingAt:c,updatedAt:c}).where(_(s.id,i))}catch(p){g.error("markAttachmentMissing failed",p)}},gn=async i=>{let s=r.attachment;if(!s)return;let c=new Date;try{await t.update(s).set({objectCheckedAt:c,objectMissingAt:null,updatedAt:c}).where(_(s.id,i))}catch(p){g.error("markAttachmentPresent failed",p)}},Rn=async(i,s,c,{forceRefresh:p=!1,snapshot:T=!1,ttlMsOverride:O}={})=>{let A=await Je(c);if(!A)return[];let k=me(s);if(!k)return[];if(ke(i.visible))return[];let B=V(k,A,at(i));return u.getOrFetch({cacheKey:B,fetcher:async()=>{let X=await ve(),j=je(S,"draft_label"),re=await le(t.select({hub:Ne(l),internal:Ne(f),isRead:I.isRead,isStarred:I.isStarred,creatorName:n.displayName,...ye()}).from(l)).leftJoin(f,_(l.id,f.hubId)).leftJoin(I,ne(_(l.id,I.hubId),_(I.userId,A))).leftJoin(j,ne(_(j.hubId,l.id),Se(j.labelId,X))).leftJoin(n,_(l.userId,n.id)).where(ne(_(l.businessDate,Zr`${k}`),he(l.deletedAt),We(_(l.userId,A),he(j.hubId)),U(i.visible))).orderBy(Ge(l.id));if(re.length===0)return[];let ue=re.map(ae=>ae.hub.id),$e=await t.select({hubId:S.hubId,id:D.id,name:D.name,color:D.color}).from(S).innerJoin(D,_(S.labelId,D.id)).where(Se(S.hubId,ue)),Ee=await t.select({hubId:d.hubId,id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,_(d.userId,n.id)).where(Se(d.hubId,ue)).orderBy(At(d.createdAt)),He=await ut(ue),we=new Map,ce=new Map;for(let ae of $e){let de=we.get(ae.hubId);de||(de=[],we.set(ae.hubId,de)),de.push({id:ae.id,name:ae.name,color:ae.color})}for(let ae of Ee){let de=ce.get(ae.hubId);de||(de=[],ce.set(ae.hubId,de)),de.push({id:ae.id,content:ae.body,createdAt:pe(ae.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ae.userId,userName:ae.userName||""})}return re.map(ae=>{let de=ae.hub.id;return Be(i,{...ae,attachments:He.get(de)??[],labels:we.get(de)||[],postedCommentRows:ce.get(de)||[]},A)})},forceRefresh:p,snapshot:T,ttlMsOverride:O??P,epochKey:`${h}${k}`})},Ke=async(i,s,c,{forceRefresh:p=!1,snapshot:T=!1,ttlMsOverride:O}={})=>{if(ke(i.visible))return null;let A=J(s,c,at(i));return(await u.getOrFetch({cacheKey:A,fetcher:async()=>{let B=await ve(),X=je(S,"draft_label"),j=await le(t.select({hub:Ne(l),internal:Ne(f),isRead:I.isRead,isStarred:I.isStarred,creatorName:n.displayName,...ye()}).from(l)).leftJoin(f,_(l.id,f.hubId)).leftJoin(I,ne(_(l.id,I.hubId),_(I.userId,c))).leftJoin(X,ne(_(X.hubId,l.id),Se(X.labelId,B))).leftJoin(n,_(l.userId,n.id)).where(ne(_(l.id,s),he(l.deletedAt),We(_(l.userId,c),he(X.hubId)),U(i.visible)));if(j.length===0)return[];let re=j[0].hub.id,ue=await t.select({id:D.id,name:D.name,color:D.color}).from(S).innerJoin(D,_(S.labelId,D.id)).where(_(S.hubId,re)),$e=await t.select({id:d.id,body:d.body,createdAt:d.createdAt,userId:d.userId,userName:n.displayName}).from(d).leftJoin(n,_(d.userId,n.id)).where(_(d.hubId,re)).orderBy(At(d.createdAt)),Ee=await ut([re]),He=ue.map(ce=>({id:ce.id,name:ce.name,color:ce.color})),we=$e.map(ce=>({id:ce.id,content:ce.body,createdAt:pe(ce.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ce.userId,userName:ce.userName||""}));return[Be(i,{...j[0],attachments:Ee.get(re)??[],labels:He,postedCommentRows:we},c)]},forceRefresh:p,snapshot:T,ttlMsOverride:O??P,epochKey:`${C}${s}`}))[0]??null},Sn=async(i,s,c,p={})=>{let T=await Je(c);return T?Ke(i,s,T,p):null},Tn=async(i,s)=>{let c=await ve(),p=je(S,"draft_label"),[T]=await t.select({sourceType:l.sourceType,deletedAt:l.deletedAt}).top(1).from(l).leftJoin(p,ne(_(p.hubId,l.id),Se(p.labelId,c))).where(ne(_(l.id,i),We(_(l.userId,s),he(p.hubId))));return T??null},wt=async(i,s,c)=>{let p=await Tn(s,c);if(!p||p.deletedAt||!De(i.visible,p.sourceType))throw new Error("Not Found")},An=async(i,s,c,p,T,O)=>{await wt(i,c,s);let A=await t.select().top(1).from(I).where(ne(_(I.hubId,c),_(I.userId,s))),k;if(A.length>0?A[0].isStarred!==T?k=(await t.update(I).set({isStarred:T,updatedAt:new Date,updatedBy:String(s)}).output().where(ne(_(I.hubId,c),_(I.userId,s))))[0]:k=A[0]:k=(await t.insert(I).output().values({hubId:c,userId:s,isStarred:T,isRead:!1,createdAt:new Date,createdBy:String(s),updatedAt:new Date,updatedBy:String(s)}))[0],p){let B=me(p);B&&(u.invalidatePrefix(ee(B,s)),await x(`${h}${B}`))}return u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(Q(c,s)),await x(`${C}${c}`),await L(mt.parse({type:"status-update",reportHubId:c,recipientRawUserId:s,statusType:"star",value:T,clientTempId:O}),"setStarStatus"),k},Dn=async(i,s,c,p,T,O)=>{await wt(i,c,s);let A=await t.select().top(1).from(I).where(ne(_(I.hubId,c),_(I.userId,s))),k;if(A.length>0?A[0].isRead!==T?k=(await t.update(I).set({isRead:T,updatedAt:new Date,updatedBy:String(s)}).output().where(ne(_(I.hubId,c),_(I.userId,s))))[0]:k=A[0]:k=(await t.insert(I).output().values({hubId:c,userId:s,isRead:T,isStarred:!1,createdAt:new Date,createdBy:String(s),updatedAt:new Date,updatedBy:String(s)}))[0],p){let B=me(p);B&&(u.invalidatePrefix(ee(B,s)),await x(`${h}${B}`))}return u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(Q(c,s)),await x(`${C}${c}`),await L(mt.parse({type:"status-update",reportHubId:c,recipientRawUserId:s,statusType:"read",value:T,clientTempId:O}),"setReadStatus"),k},Kt=async(i,s)=>{if(s===null)return;let c=await ve(),[p]=await t.select({hubId:S.hubId}).top(1).from(S).where(ne(_(S.hubId,i),Se(S.labelId,c)));return p?s:void 0},wn=async(i,s,c,p,T,O)=>{let[A]=await t.select({sourceType:l.sourceType,deletedAt:l.deletedAt,userId:l.userId}).top(1).from(l).where(_(l.id,c));if(!A||A.deletedAt)throw new Error("Not Found");if(await wt(i,c,s),!De(i.commentable,A.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(A.sourceType.toLowerCase()!=="internal")throw new Error("Comments are restricted for external daily report sources");let k=await Kt(c,A.userId),[B]=await t.insert(d).output().values({hubId:c,userId:s,body:p,createdAt:new Date,createdBy:String(s),updatedAt:new Date,updatedBy:String(s)}),[X]=await t.select({displayName:n.displayName}).top(1).from(n).where(_(n.id,s)),j=X?.displayName??"";if(T){let ue=me(T);ue&&(u.invalidatePrefix(`daily-report:date:${ue}:user:`),await x(`${h}${ue}`))}u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(`daily-report:detail:${c}:user:`),await x(`${C}${c}`);let re={id:B.id,userId:o(B.userId),userName:j,content:B.body,createdAt:pe(B.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await L(Lt.parse({type:"comment-add",reportHubId:c,comment:re,clientTempId:O,recipientRawUserId:k,sourceType:A.sourceType}),"addComment"),re},_n=async(i,s)=>await i.select().top(1).from(d).where(_(d.id,s)),In=async(i,s,c,p,T,O)=>{let A=await _n(t,p);if(A.length===0)throw new Error("Not Found");if(A[0].hubId!==c)throw new Error("Not Found");let[k]=await t.select({userId:l.userId,sourceType:l.sourceType}).top(1).from(l).where(_(l.id,A[0].hubId));if(!(k&&De(i.visible,k.sourceType)))throw new Error("Not Found");if(A[0].userId!==s)throw new Error("Unauthorized");let B=await Kt(c,k.userId);if(await t.delete(d).where(_(d.id,p)),T){let X=me(T);X&&(u.invalidatePrefix(`daily-report:date:${X}:user:`),await x(`${h}${X}`))}u.invalidate(`daily-report:detail:${c}`),u.invalidatePrefix(`daily-report:detail:${c}:user:`),await x(`${C}${c}`),await L(kt.parse({type:"comment-delete",reportHubId:c,commentId:p,clientTempId:O,recipientRawUserId:B,sourceType:k?.sourceType}),"deleteComment")},En=async(i,s,c)=>{g.info("createDailyReport called",{userId:i,businessDate:s});let[p]=await t.select({displayName:n.displayName}).from(n).where(_(n.id,i)),T=p?.displayName??o(i);try{let O=await Y(async B=>{g.info("Starting transaction");let X=`internal-temp-${Date.now()}-${Math.random()}`,[j]=await B.insert(l).output().values({sourceType:"Internal",sourceId:X,businessDate:new Date(s),userId:i,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)});await B.update(l).set({sourceId:String(j.id)}).where(_(l.id,j.id)),g.info("Hub created",j),await B.insert(f).values({hubId:j.id,body:"",createdAt:new Date,createdBy:String(i),updatedAt:new Date,updatedBy:String(i)}),g.info("Internal created"),g.info("Calling getDraftLabelId");let re=await Dt();g.info("draftLabelId",re);let ue=[];return re&&(await B.insert(S).values({hubId:j.id,labelId:re,createdAt:new Date,createdBy:String(i)}),ue.push({id:re,name:K,color:null})),g.info("Label assigned"),{reportHubId:j.id,date:s,createdAt:pe(j.createdAt,"YYYY-MM-DD HH:mm:ss"),author:T,userId:o(i),sourceType:"Internal",employeeName:T,updatedBy:o(i),updatedAt:pe(j.updatedAt,"YYYY-MM-DD HH:mm:ss"),category:null,creationCategory:null,visitTimeFrom:null,visitTimeTo:null,customerName:null,interviewers:[],subject:j.title,content:"",externalComments:[],isRead:!0,isStarred:!1,labels:ue,postedComments:[],attachments:[]}}),A=me(s);A&&u.invalidatePrefix(ee(A,i)),u.invalidatePrefix(w),u.invalidatePrefix(z(i)),await x(v),A&&await x(`${h}${A}`);let k=await Ke(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),O.reportHubId,i,{forceRefresh:!0});if(k){let B=await lt(),X=k.labels.some(j=>B.includes(j.id));await L(Nt.parse({type:"report-create",reportHubId:k.reportHubId,report:k,clientTempId:c,recipientRawUserId:X?i:void 0}),"createDailyReport")}return k??O}catch(O){throw g.error("Error in createDailyReport",O),O}},ct=async(i,s)=>await i.select().top(1).from(l).where(_(l.id,s)),_t=async(i,s,c)=>{await i.update(l).set(c).where(_(l.id,s))},Qt=async(i,s,c)=>{await i.update(f).set(c).where(_(f.hubId,s))},Xt=async(i,s,c)=>{await i.delete(S).where(ne(_(S.hubId,s),_(S.labelId,c)))};return{streamKey:N,streamMaxLen:q,attachmentDelivery:M,clearCache:async()=>{u.clearAll(),st.clear(),Ue=null,R&&await x(v),g.info("[DailyReportService] Server-side DB/SQL caches cleared successfully.")},invalidateHubReadCaches:async(i,s)=>{u.invalidatePrefix(w),u.invalidatePrefix(H),await x(v);for(let c of new Set(i))u.invalidatePrefix(`daily-report:detail:${c}:user:`),await x(`${C}${c}`);for(let c of new Set(s)){let p=me(c);p&&await x(`${h}${p}`)}},getUserIdByExternalId:Je,getDailyReportIdsByExternalId:pn,getDailyReportIdsFirstPageByExternalId:ot,readSseStreamAnchor:E,getDailyReportsByBusinessDate:yn,getDailyReportsByBusinessDateByExternalId:Rn,getDailyReportDetailById:Ke,getDailyReportDetailByIdByExternalId:Sn,getDraftLabelId:Dt,getAttachmentsByHubIds:ut,getAttachmentForUser:fn,markAttachmentMissing:bn,markAttachmentPresent:gn,setStarStatus:An,setReadStatus:Dn,addComment:wn,deleteComment:In,createDailyReport:En,updateDailyReport:async(i,s,c,p)=>{let T=await ct(t,i);if(!T.length||T[0].deletedAt)throw new Error("Not Found");if(T[0].userId!==s)throw new Error("Unauthorized");await Y(async k=>{c.title!==void 0&&await _t(k,i,{title:c.title,updatedAt:new Date,updatedBy:String(s)}),c.content!==void 0&&await Qt(k,i,{body:c.content,updatedAt:new Date,updatedBy:String(s)})}),u.invalidate(`daily-report:detail:${i}`),u.invalidatePrefix(`daily-report:detail:${i}:user:`),u.invalidatePrefix(w),await x(`${C}${i}`);let O=me(pe(T[0].businessDate,"YYYY-MM-DD"));O&&(u.invalidatePrefix(`daily-report:date:${O}:user:`),await x(`${h}${O}`));let A=await Ke(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,s,{forceRefresh:!0});if(A){let k=await lt(),B=A.labels.some(X=>k.includes(X.id));await L(Ot.parse({type:"report-update",reportHubId:A.reportHubId,report:A,clientTempId:p,recipientRawUserId:B?s:void 0}),"updateDailyReport")}},publishDailyReport:async(i,s,c)=>{let p=await ct(t,i);if(!p.length)throw new Error("Not Found");if(p[0].userId!==s)throw new Error("Unauthorized");let T=await Dt();if(!T)return null;if(await Xt(t,i,T),u.invalidatePrefix(`daily-report:detail:${i}:user:`),u.invalidatePrefix(w),u.invalidatePrefix(H),await x(v),p[0].businessDate){let k=me(pe(p[0].businessDate,"YYYY-MM-DD"));k&&await x(`${h}${k}`)}let O=me(pe(p[0].businessDate,"YYYY-MM-DD"));O&&u.invalidatePrefix(ee(O,s));let A=await Ke(ge.unrestricted("post-write self read: the writer always sees the row they just wrote"),i,s,{forceRefresh:!0});return A&&await L(Bt.parse({type:"report-publish",reportHubId:A.reportHubId,report:A,clientTempId:c}),"publishDailyReport"),A??null},deleteDailyReport:async(i,s,c)=>{let p=await ct(t,i);if(!p.length||p[0].deletedAt)throw new Error("Not Found");if(p[0].userId!==s)throw new Error("Unauthorized");if(await _t(t,i,{deletedAt:new Date,deletedBy:String(s),updatedAt:new Date,updatedBy:String(s)}),u.invalidatePrefix(`daily-report:detail:${i}:user:`),u.invalidatePrefix(w),u.invalidatePrefix(H),await x(v),p[0].businessDate){let T=me(pe(p[0].businessDate,"YYYY-MM-DD"));T&&await x(`${h}${T}`)}await L(Ut.parse({type:"report-delete",reportHubId:i,clientTempId:c,sourceType:p[0].sourceType}),"deleteDailyReport")},findDailyReportHubById:ct,updateDailyReportHub:_t,updateDailyReportInternal:Qt,deleteDailyReportLabel:Xt}}var Qa=fe(1,"[DailyReportExternalSource]"),Xa=(e,t,r,n=Qa)=>{if(!e)return[];try{let a=JSON.parse(e);return Array.isArray(a)?a.map(r).filter(o=>o!==null):(n.warn(`Unexpected ${t} format: not an array`),[])}catch(a){return n.warn(`Failed to parse ${t}:`,a),[]}};import{desc as en,sql as Za}from"drizzle-orm";import{bigint as ie,bit as tn,date as ei,datetime2 as se,foreignKey as Te,index as xe,int as ti,mssqlSchema as ri,nvarchar as Z,primaryKey as Oe,uniqueIndex as ni}from"drizzle-orm/mssql-core";function ai(e,t){let r=ri(e),n=t.userTable,a=r.table("DailyReportHub",{id:ie("id",{mode:"number"}).identity().notNull(),sourceType:Z("source_type",{length:20}).notNull(),sourceId:Z("source_id",{length:100}).notNull(),sourceIdNum:ie("source_id_num",{mode:"number"}).generatedAlwaysAs(Za`TRY_CAST(source_id AS BIGINT)`),businessDate:ei("business_date"),userId:ie("user_id",{mode:"number"}),title:Z("title",{length:200}),summary:Z("summary",{length:"max"}),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull(),deletedAt:se("deleted_at"),deletedBy:Z("deleted_by",{length:50})},d=>[Oe({name:`${e}_DailyReportHub_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportHub_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),xe(`${e}_DailyReportHub_business_date_index`).on(d.businessDate),xe(`${e}_DailyReportHub_updated_at_index`).on(d.updatedAt),xe(`${e}_DailyReportHub_source_index`).on(d.sourceType,d.sourceId),xe(`${e}_DailyReportHub_user_id_index`).on(d.userId),xe(`${e}_DailyReportHub_business_date_id_index`).on(en(d.businessDate),en(d.id)),xe(`${e}_DailyReportHub_deleted_at_index`).on(d.deletedAt)]),o=r.table("DailyReportInternal",{hubId:ie("hub_id",{mode:"number"}).notNull(),body:Z("body",{length:"max"}),metadata:Z("metadata",{length:"max"}),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportInternal_pk`,columns:[d.hubId]}),Te({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]})]),m=r.table("DailyReportComment",{id:ie("id",{mode:"number"}).identity().notNull(),hubId:ie("hub_id",{mode:"number"}).notNull(),userId:ie("user_id",{mode:"number"}).notNull(),body:Z("body",{length:"max"}).notNull(),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportComment_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportComment_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportComment_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]}),xe(`${e}_DailyReportComment_hub_id_index`).on(d.hubId)]),u=r.table("DailyReportLabel",{id:ie("id",{mode:"number"}).identity().notNull(),userId:ie("user_id",{mode:"number"}),name:Z("name",{length:50}).notNull(),color:Z("color",{length:20}),sortOrder:ti("sort_order"),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportLabel_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportLabel_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),R=r.table("DailyReportHub_Label",{hubId:ie("hub_id",{mode:"number"}).notNull(),labelId:ie("label_id",{mode:"number"}).notNull(),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportHub_Label_pk`,columns:[d.hubId,d.labelId]}),Te({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[d.labelId],foreignColumns:[u.id]})]),l=r.table("DailyReportUserStatus",{hubId:ie("hub_id",{mode:"number"}).notNull(),userId:ie("user_id",{mode:"number"}).notNull(),isRead:tn("is_read").default(!1).notNull(),isStarred:tn("is_starred").default(!1).notNull(),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportUserStatus_pk`,columns:[d.hubId,d.userId]}),Te({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[d.userId],foreignColumns:[n.id]})]),f=r.table("DailyReportAttachment",{id:ie("id",{mode:"number"}).identity().notNull(),hubId:ie("hub_id",{mode:"number"}).notNull(),uploadedBy:ie("uploaded_by",{mode:"number"}),sourceKey:Z("source_key",{length:200}).notNull(),fileName:Z("file_name",{length:255}).notNull(),filePath:Z("file_path",{length:"max"}).notNull(),fileType:Z("file_type",{length:100}),fileSize:ie("file_size",{mode:"number"}),objectCheckedAt:se("object_checked_at"),objectMissingAt:se("object_missing_at"),createdAt:se("created_at").notNull(),createdBy:Z("created_by",{length:50}).notNull(),updatedAt:se("updated_at").notNull(),updatedBy:Z("updated_by",{length:50}).notNull()},d=>[Oe({name:`${e}_DailyReportAttachment_pk`,columns:[d.id]}),Te({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[d.hubId],foreignColumns:[a.id]}),Te({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[d.uploadedBy],foreignColumns:[n.id]}),ni(`${e}_DailyReportAttachment_source_unique`).on(d.hubId,d.sourceKey),xe(`${e}_DailyReportAttachment_hub_id_index`).on(d.hubId,d.createdAt)]);return{hub:a,internal:o,comment:m,attachment:f,label:u,hubLabel:R,userStatus:l}}var ii=5e7,sn=2e8,oi=1,ln=Object.freeze({fixedBytes:4*1024*1024,pipelineRows:2048,wholeImageBuffer:Object.freeze({"jpeg-single-scan":Object.freeze({kind:"none"}),"jpeg-multi-scan":Object.freeze({kind:"jpeg-coefficients"}),png:Object.freeze({kind:"none"}),"png-interlaced":Object.freeze({kind:"decoded-raster"}),gif:Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-lossy":Object.freeze({kind:"none"}),"webp-lossy-alpha":Object.freeze({kind:"canvas",bytesPerPixel:5}),"webp-lossless":Object.freeze({kind:"canvas",bytesPerPixel:4}),"webp-animated":Object.freeze({kind:"canvas",bytesPerPixel:9})})}),si=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),rn=75,nn=4,an="#ffffff",li=1,ui={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},ci=[/out of memory/i,/insufficient memory/i,/memory allocation|allocation failed/i,/(?:cannot|could not|unable to|failed to) allocate/i,/picture memory error/i,/unable to create thread|error creating thread|resource temporarily unavailable/i,/too many open files|no space left on device/i,/\b(?:ENOMEM|EAGAIN|EMFILE|ENFILE|ENOSPC)\b/],Jt=Object.freeze({ok:!1,reason:"failed"}),on=Object.freeze({ok:!1,reason:"unsupported"}),un=(e,t)=>{switch(t){case"jpeg":{let r=Yt(e);return r===null?null:{layout:r.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:wr(r)}}case"png":{let r=Ir(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Er(e);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},cn=(e,t)=>{let r=si.get(t.depth);if(r===void 0)return null;let n=t.channels*r,a=ln,o=a.wholeImageBuffer[e.layout];return(o.kind==="none"?0:o.kind==="decoded-raster"?t.width*t.height*n:o.kind==="jpeg-coefficients"?e.coefficientBytes:t.width*t.height*o.bytesPerPixel)+a.pipelineRows*t.width*n+a.fixedBytes},di=(e,t,r)=>{let n=un(e,t);return n===null?null:cn(n,r)},mi=e=>e!==null&&e<=sn,pi=e=>{let t=e instanceof Error?e.message:"";return ci.some(r=>r.test(t))?"failed":"unsupported"},yi=e=>{e.cache(!1),e.concurrency(oi),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(ui)});let t=async(n,a,o,m,u)=>{let R=un(n,a);if(R===null)return on;try{let l=e(n,{limitInputPixels:ii,animated:!1});if(!mi(cn(R,await l.metadata())))return on;if(u.aborted)return Jt;let f=await l.rotate().resize({width:o,height:m,fit:"inside",withoutEnlargement:!0}).flatten({background:an}).webp({quality:rn,effort:nn}).toBuffer();return{ok:!0,bytes:new Uint8Array(f),contentType:"image/webp"}}catch(l){return{ok:!1,reason:pi(l)}}},r=async(n,{format:a,maxWidth:o,maxHeight:m,signal:u})=>{if(u.aborted)return Jt;let R=await t(n,a,o,m,u);return u.aborted?Jt:R};return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${rn}-e${nn}/flatten-${an}/v${li}`,render:r}};function ms(e){e.redis||(e.logger??console).warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.");let t=xt(e.redis),r=new Xe({defaultTtlMs:e.cacheDefaultTtlMs??6e4},t),n=Wt({...e,cache:r,epochs:t}),a=new rt({redis:e.redis,streamKey:n.streamKey,cache:r,logger:e.logger}),o=Gt({authenticate:e.authenticate,resolveVisibleSourceTypes:e.resolveVisibleSourceTypes,service:n,encodeUserId:e.encodeUserId,attachmentRateLimitPerMinute:e.attachmentRateLimitPerMinute,attachmentConcurrency:e.attachmentConcurrency,attachmentThumbnailRateLimitPerMinute:e.attachmentThumbnailRateLimitPerMinute,attachmentThumbnailConcurrency:e.attachmentThumbnailConcurrency,attachmentThumbnailCacheBytes:e.attachmentThumbnailCacheBytes,redis:e.redis,sseReader:a,streamKey:n.streamKey,loginRedirectPath:e.loginRedirectPath,enableDevCacheClear:e.enableDevCacheClear,logger:e.logger});return{service:n,cache:r,epochs:t,sseReader:a,streamKey:n.streamKey,knownSourceTypes:[...new Set(["Internal",...(e.externalSources??[]).map(m=>m.sourceType)])],...o}}export{vr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_MAX_OUTPUT_BYTES,xr as DAILY_REPORT_ATTACHMENT_THUMBNAIL_OUTPUT_MEDIA_TYPES,sn as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,ln as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,jt as DAILY_REPORT_SSE_CATCH_UP_BATCH,Xr as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,rt as DailyReportSseReader,ge as DailyReportViewerScope,Xe as SqlResultCache,Gt as createDailyReportHandlers,ms as createDailyReportServer,Wt as createDailyReportService,xt as createEpochStore,yi as createSharpThumbnailRenderer,ai as defineDailyReportSchema,et as generateETag,Le as isStreamIdLte,be as jsonResponseWithETag,di as predictSharpThumbnailWorkingSetBytes,Xa as transformJsonArray};
|
|
5
5
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiquants/daily-report",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.24.0",
|
|
4
4
|
"description": "Reusable daily-report feature package: shared types/schemas, React (Router v7 / v8) UI with virtual scrolling + optimistic updates + SSE sync, and a drizzle (mssql) server layer with DI ports (auth, user resolution, redis, external sources).",
|
|
5
5
|
"sideEffects": [
|
|
6
6
|
"**/*.css"
|