@stackone/olap 1.75.0 → 1.76.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/README.md CHANGED
@@ -54,7 +54,17 @@ $ pnpm lint:fix
54
54
  Platform logs are the audit trail of operations on StackOne itself — creating an account, deleting
55
55
  an integration, minting a session — as opposed to requests proxied to a provider.
56
56
 
57
- They are read through `getPlatformLogs` and **only** through it.
57
+ They are read through `getPlatformLogs` for rows, and `getPlatformLogDimensions` for the distinct
58
+ values behind a filter dropdown — and **only** through those two. Both take the organization as a
59
+ positional argument that overrides whatever the query carries, `undefined` included, so an unscoped
60
+ read has to be asked for rather than inherited.
61
+
62
+ `getPlatformLogDimensions` returns `{ [facet]: Array<{ value, count }> }`, capped at `maxValues`
63
+ (100 by default) per facet and narrowed by whatever filters the query already applies, so the counts
64
+ describe the rows the caller would actually see. It offers every filterable column except the
65
+ identifiers (`eventId`, `sessionId`, `resourceId`, `authId`, `ipAddress`), free text (`userAgent`),
66
+ `userId` — which `userEmail` covers in a readable form — and `projectSecureId`, which is a scope
67
+ the caller already supplies rather than a facet to choose from.
58
68
 
59
69
  They are also deliberately **not** part of the `getLogs` feed: including platform rows
60
70
  meant classifying every filter and dimension the `platform` table lacks, per arm. `CombinedLogType`
package/dist/index.cjs CHANGED
@@ -74,7 +74,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
74
74
  WHERE ${t} IN {entityIds:Array(String)}
75
75
  ORDER BY eventTime DESC
76
76
  LIMIT 1 BY ${t}
77
- `,r=toArray(e.entities?.ids),i=buildLogsViewParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const T={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),E={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},D={Asc:`asc`,Desc:`desc`},O={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},ae={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},k={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===T.Platform,A={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},j={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},M={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(j,e)?j[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(M,e)?M[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(n.snakeToCamel),r=e.intervalType??`hour`,i=Math.floor(Number(e.intervalPeriod??1)),a=Number.isFinite(i)&&i>0?i:1,o=t.filter(e=>Object.prototype.hasOwnProperty.call(A,e)).map(e=>A[e]),s=r===O.None?void 0:buildTimeBucket(r,a),c=[...s?[`${s} as startTime`]:[],`count() as count`,...o].join(`, `),l=[...s?[`startTime`]:[],...o],u=l.length>0?`GROUP BY ${l.join(`, `)}`:``,d=s?`ORDER BY startTime ASC`:``;return{sql:`
77
+ `,r=toArray(e.entities?.ids),i=buildLogsViewParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const T={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),ae={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},oe={Asc:`asc`,Desc:`desc`},E={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},se={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},ce={EventType:`eventType`,Action:`action`,Resource:`resource`,Service:`service`,SourceType:`sourceType`,SourceId:`sourceId`,AuthType:`authType`,UserEmail:`userEmail`,StatusCode:`statusCode`,Success:`success`,IsRead:`isRead`,AgentId:`agentId`,TransportType:`transportType`,StreamType:`streamType`},D={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===T.Platform,O={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},k={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},A={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(k,e)?k[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(A,e)?A[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(n.snakeToCamel),r=e.intervalType??`hour`,i=Math.floor(Number(e.intervalPeriod??1)),a=Number.isFinite(i)&&i>0?i:1,o=t.filter(e=>Object.prototype.hasOwnProperty.call(O,e)).map(e=>O[e]),s=r===E.None?void 0:buildTimeBucket(r,a),c=[...s?[`${s} as startTime`]:[],`count() as count`,...o].join(`, `),l=[...s?[`startTime`]:[],...o],u=l.length>0?`GROUP BY ${l.join(`, `)}`:``,d=s?`ORDER BY startTime ASC`:``;return{sql:`
78
78
  WITH logs AS (
79
79
  ${buildLogsViewSource()}
80
80
  )
@@ -83,19 +83,44 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
83
83
  FROM logs
84
84
  ${u}
85
85
  ${d}
86
- `,params:buildLogsViewParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const oe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},N=`provider_logs_filtered`,P=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),F=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
86
+ `,params:buildLogsViewParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const le={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},j=`provider_logs_filtered`,M=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),N=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
87
87
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
88
88
  SELECT *
89
- FROM ${N}(${P})
90
- ${F}
91
- ORDER BY ${sanitizeOrderBy(e.orderBy,oe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
89
+ FROM ${j}(${M})
90
+ ${N}
91
+ ORDER BY ${sanitizeOrderBy(e.orderBy,le,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
92
92
  LIMIT {limit:UInt32}
93
93
  OFFSET {offset:UInt32}
94
94
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildProviderLogsCountQuery(e){return{sql:`
95
95
  SELECT count() as total
96
- FROM ${N}(${P})
97
- ${F}
98
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const se={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
96
+ FROM ${j}(${M})
97
+ ${N}
98
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const ue=[...[`organizationId`,`projectSecureId`,`eventId`,`eventType`,`service`,`userId`,`userEmail`,`action`,`resource`,`resourceId`,`sourceType`,`sourceId`,`authType`,`authId`,`userAgent`,`ipAddress`,`sessionId`,`agentId`,`transportType`,`streamType`].map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isRead = {isRead:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),P={eventType:`eventType`,action:`action`,resource:`resource`,service:`service`,sourceType:`sourceType`,sourceId:`sourceId`,authType:`authType`,userEmail:`userEmail`,statusCode:`statusCode`,success:`success`,isRead:`isRead`,agentId:`agentId`,transportType:`transportType`,streamType:`streamType`},de=new Set([`statusCode`,`success`,`isRead`]),fe=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
99
+ AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`,buildPlatformViewSource=()=>`SELECT *
100
+ FROM platform_filtered(${ue})
101
+ ${fe}`,buildPlatformViewParams=e=>({organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)});function buildPlatformDimensionsQuery(e){let t=toArray(e.dimensions).map(n.snakeToCamel),r=e.maxValues??100,i=t.filter(e=>Object.prototype.hasOwnProperty.call(P,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildPlatformViewSource();return{sql:i.map(e=>{let t=P[e];return`
102
+ SELECT
103
+ '${e}' as dimension,
104
+ arrayReverseSort(
105
+ facet -> facet.2,
106
+ groupArray(CAST((value, count), 'Tuple(value String, count UInt64)'))
107
+ ) as \`values\`
108
+ FROM (
109
+ SELECT
110
+ toString(${t}) as value,
111
+ count() as count
112
+ FROM (
113
+ ${a}
114
+ ) AS platformLogs
115
+ WHERE ${t} IS NOT NULL
116
+ ${de.has(e)?``:`AND ${t} != ''`}
117
+ GROUP BY ${t}
118
+ ORDER BY count DESC
119
+ LIMIT {maxValues:UInt32}
120
+ ) AS facets
121
+ `}).join(`
122
+ UNION ALL
123
+ `),params:{...buildPlatformViewParams(e),maxValues:r}}}registerQuery({id:`organization_platform_dimensions.json`,buildQuery:buildPlatformDimensionsQuery});const pe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
99
124
  SELECT
100
125
  eventTime,
101
126
  startTime,
@@ -153,7 +178,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
153
178
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
154
179
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
155
180
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
156
- ORDER BY ${sanitizeOrderBy(e.orderBy,se,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
181
+ ORDER BY ${sanitizeOrderBy(e.orderBy,pe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
157
182
  LIMIT {limit:UInt32}
158
183
  OFFSET {offset:UInt32}
159
184
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildPlatformLogsCountQuery(e){return{sql:`
@@ -202,4 +227,4 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
202
227
  AND sourceId != ''
203
228
  GROUP BY sourceId, sourceType
204
229
  ORDER BY request_count DESC
205
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=(0,t.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}};function createOlapQueryClient(e,t){return new ClickHouseClient(e.clickhouse,t)}function createConfigFromEnv(){let e=process.env.CLICKHOUSE_URL;return{clickhouse:e?{url:e,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0}}const I={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},L={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},ce={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},le={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},ue=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],de=[I.Scheduler,I.DataSync,I.DataSyncV2,I.Internal],fe=[`data_sync`],R=[I.DataSync,I.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&ue.includes(e)||t&&de.includes(t))}function isDataSync(e,t){return!!(e&&fe.includes(e)||t&&R.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>(0,n.isMissing)(e)?!1:Array.isArray(e)||(0,n.isString)(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,z=64*1024,B=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],V=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>(0,n.isObject)(e)?e[t]:void 0,e),withPath=(e,t,r)=>{let[i,...a]=t.split(`.`);if(a.length===0)return{...e,[i]:r};let o=e[i];return(0,n.isObject)(o)?{...e,[i]:withPath(o,a.join(`.`),r)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+(0,n.calculateSize)(r);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,r):e},fitObject=(e,t)=>{let r=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+(0,n.calculateSize)(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let r=(0,n.calculateSize)(e);return r<=t?e:((0,n.isString)(e)||Array.isArray(e)||(0,n.isObject)(e)&&!(0,n.isDate)(e))&&t<=0?marker(r):(0,n.isString)(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):(0,n.isObject)(e)&&!(0,n.isDate)(e)?fitObject(e,t):e},payloadFields=e=>B.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!(0,n.isMissing)(e)).map(e=>({...e,size:(0,n.calculateSize)(e.value)})),byRetentionPriority=e=>[...e.filter(e=>V.includes(e.path)),...e.filter(e=>!V.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*z;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(z,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>B.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),pe=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],me=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],he=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed, content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`,error:e})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&(0,n.calculateSize)(e)>this.#n)return e;try{return await(0,r.scrubObjectAsync)(e,this.#a)}catch(t){return this.#i?.warning({message:`PII content scrub failed, storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`,error:t}),e}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(i.mode,i.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&a.success&&!a.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${i.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e={...i,body:await this.scrubPii((0,r.redactFields)(i.body,r.CensorType.PARTIAL,!0),t)},o={...a,body:await this.scrubPii((0,r.redactFields)(a.body,r.CensorType.PARTIAL,!0),t)},s=this.createActionS3(e,o,t),c=await this.send(s,t?.ttl);n.push(c)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let i={...e,inputs:await this.scrubPii((0,r.redactFields)(e.inputs,r.CensorType.PARTIAL,!0),n)},a={...t,outputs:await this.scrubPii((0,r.redactFields)(t.outputs,r.CensorType.PARTIAL,!0),n),errors:await this.scrubPii((0,r.redactFields)(t.errors,r.CensorType.PARTIAL,!0),n)},o=this.createStepS3(i,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let i={...e,body:await this.scrubPii((0,r.redactFields)(e.body,r.CensorType.PARTIAL,!0),n)},a={...t,body:await this.scrubPii((0,r.redactFields)(t.body,r.CensorType.PARTIAL,!0),n)},o=this.createUnifiedS3(i,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let i={...e,body:await this.scrubPii((0,r.redactFields)(e.body,r.CensorType.PARTIAL,!0),n)},a={...t,body:await this.scrubPii((0,r.redactFields)(t.body,r.CensorType.PARTIAL,!0),n)},o=this.createProviderS3(i,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let a=new i.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let a=this.requireBucket();try{let o=new i.GetObjectCommand({Bucket:a,Key:`${e}/${t}/${n}/steps/${r}.json`}),s=await this.#e.send(o);if(!s.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let c=await s.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(c)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let a=new i.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let a=this.requireBucket();try{let o=new i.GetObjectCommand({Bucket:a,Key:`${e}/${t}/${n}/provider/${r}.json`}),s=await this.#e.send(o);if(!s.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let c=await s.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(c)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let a=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,o=new Date(a*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:o.toISOString()}});try{return await this.#e.send(new i.PutObjectCommand({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:o,Tagging:r})),{expiresAt:o}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new i.HeadObjectCommand({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new i.GetObjectCommand({Bucket:n,Key:platformKey(e,t)}),a=await this.#e.send(r);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{Key:i,ContentType:`application/json`,Expires:new Date(a*1e3),Body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let i=(0,r.redactFields)(e.data,r.CensorType.PARTIAL,!0),a={...e.metadata,expirationTime:t,sizeBytes:(0,n.calculateSize)(i)};return this.stringifyPlatform({data:i,metadata:a},a)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,i,a){let o=(0,r.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},r.CensorType.PARTIAL),s=o.req?.headers,c=o.res?.headers,l=this.processContent(s,e.body,`upload`),u=this.processContent(c,t.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,p={};if(e.url)try{f=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(f);p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let m={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:f,path:e.pathParams,queryParams:p},body:l},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(c),body:u},...d?{isBackgroundLog:!0}:{}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,i,isErrorResult(t),a)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,i,a){let o=(0,r.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},r.CensorType.PARTIAL),s=o.req?.headers,c=o.res?.headers,l=this.processContent(s,e.body,`upload`),u=this.processContent(c,t.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=`/`,p=e.url,m={};if(e.url)try{p=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(p);f=t.pathname,m=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let h={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:p,path:f,queryParams:m},body:l},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(c),body:u}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(h,i,isErrorResult(t),a)}serializeProviderResult(e,t,n,i,a){let o=(0,r.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},r.CensorType.PARTIAL),s=o.req?.headers,c=o.res?.headers,l=this.processContent(s,e.body,`upload`),u=this.processContent(c,t.body,`download`),d,f=``,p=`/`,m={};if(e.url)try{d=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(d);f=t.hostname,p=t.pathname,m=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let h={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:d,hostname:f,path:p,queryParams:m},body:l},response:{statusCode:t.statusCode,headers:this.filterHeaders(c),body:u}},metadata:{expirationTime:n}};return this.serializeAndLimit(h,i,isErrorResult(t),a)}serializeAndLimit(e,t,r,i){let a=(0,n.calculateSize)(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?t*this.#r:t;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=pe.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return me.includes(i)||he.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,n.isMissing)(e)){if(!(0,n.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new a.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[c.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new s.BasicTracerProvider({resource:(0,o.resourceFromAttributes)(n),spanProcessors:[new s.BatchSpanProcessor(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let r=0;for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),(0,n.isMissing)(i.body)&&(0,n.isMissing)(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,a);if((0,n.isMissing)(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if((0,n.exceedsSize)(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}this.send(i,e),r++}r>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${r} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let r=(0,n.isMissing)(e.body)?void 0:(0,n.extractSchema)(e.body),i=(0,n.isMissing)(t.body)?void 0:(0,n.extractSchema)(t.body);if(!((0,n.isMissing)(r)&&(0,n.isMissing)(i)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:r,result:i}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),r.push(null);continue}if((0,n.isMissing)(a.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:i.actionRunId}}),r.push(null);continue}let e=this.createDefenderS3(i,a),o=await this.send(e);r.push(o)}return r}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let a=new i.GetObjectCommand({Bucket:r,Key:this.generateS3Key(e,t,n)}),o=await this.#e.send(a);if(!o.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let s=await o.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),a=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:a,expiresAt:r.toISOString()}});try{return await this.#e.send(new i.PutObjectCommand({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:a})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},H=u.z.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new u.z.ZodError([{code:u.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},u.z.coerce.date()),U=u.z.object({logType:u.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:u.z.coerce.string(),projectSecureId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:u.z.literal(`action`),actionRunId:u.z.coerce.string(),actionId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string(),connectorOwner:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),actionType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),G=U.extend({logType:u.z.literal(`step`),actionRunId:u.z.coerce.string(),stepIndex:u.z.coerce.number(),stepId:u.z.coerce.string(),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),skipped:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:u.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:u.z.literal(`unified`),requestId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:u.z.literal(`provider`),requestId:u.z.coerce.string(),id:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string(),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string(),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),status:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:u.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),J=U.extend({logType:u.z.literal(`platform`),eventId:u.z.coerce.string(),eventType:u.z.coerce.string(),service:u.z.coerce.string(),organizationId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:u.z.undefined(),userId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:u.z.record(u.z.unknown()).optional().nullable().transform(e=>e??void 0)}),ge=u.z.discriminatedUnion(`logType`,[W,G,K,q]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Y=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a(){return this.#r?.isReady()?this.#r:void 0}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#o()}async#o(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#r;if(!r?.isReady())return this.#i?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#i?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,W),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,q),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,J),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,t,r){let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r}});let{dimensions:a,startTime:o,endTime:s,...c}=r,l=r.intervalType===O.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,n.convertKeysToCamelCase)(e,!0)).map(e=>{let t={...e};for(let e of Y)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){return i?.isReady()?this.#i?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,maxValues:s,...c}=n,l={organizationId:e,projectSecureId:t,...c,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()},...s&&{maxValuesPerDim:s}},u=await r?.query({endpoint:`project_logs_dimensions.json`,params:l});if(!u)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${u.length} dimension facets`,category:`LogsSink`});let d={};for(let e of u)Y.includes(e.dimension)?d[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):d[e.dimension]=e.values;return d}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,...o&&{sourceType:Array.isArray(o)?o.join(`,`):o},...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r?.query({endpoint:`project_source_usage.json`,params:s});return c?(this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#s(e){return(this.#n??k)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#s(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#c(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#c(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??(0,l.randomUUID)(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof u.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,ge)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof u.ZodError?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return W;case`step`:return G;case`unified`:return K;case`provider`:return q;case`platform`:return J}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...X.logs,...e?.logs},advanced:{...X.advanced,...e?.advanced},defender:{...X.defender,...e?.defender},policy:{...X.policy,...e?.policy},datasets:{...X.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Policy sink bucket is not configured`);return this.#t}async initialize(){this.#e||this.#r?.warning({message:`No s3 client provided, policy sink will not function`,category:`PolicySink`})}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e){if(!t?.enabled){r.push(null);continue}if(!this.#t){r.push(null);continue}if((0,n.isMissing)(a.policyContext)){r.push(null);continue}let e=await this.send(this.createPolicyS3(i,a));r.push(e)}return r}async getAction(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from policy sink`,category:`PolicySink`});return}if(this.#t)try{let a=await this.#e.send(new i.GetObjectCommand({Bucket:this.requireBucket(),Key:this.generateS3Key(e,t,n,r)}));if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get policy log from S3 for actionRunId ${r}`,category:`PolicySink`});return}return JSON.parse(await a.Body.transformToString())}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Policy log not found in S3 for actionRunId ${r}`,category:`PolicySink`});return}throw this.#r?.error({message:`Error when getting policy log from S3 for actionRunId ${r}`,error:e,code:`PolicyLogReadError`,category:`PolicySink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to policy sink`);let t=new Date(Date.now()+this.#n*24*60*60*1e3);try{return await this.#e.send(new i.PutObjectCommand({Bucket:this.requireBucket(),Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:t,Tagging:`ttl=${this.#n}d`})),{expiresAt:t}}catch(t){throw this.#r?.error({message:`Failed to write policy log to S3 at ${e.Key}`,error:t,code:`PolicyLogWriteError`,category:`PolicySink`}),t}}generateS3Key(e,t,n,r){return`${e}/${t}/${n}/${r}/policy.json`}createPolicyS3(e,t){return{Key:this.generateS3Key(e.organizationId,e.projectSecureId,e.accountSecureId,e.actionRunId),Body:JSON.stringify(t.policyContext),ContentType:`application/json`}}};const Z=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Z}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Z}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),Q=__name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=Q(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=Q(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new i.S3Client(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=c,this.#p=l,this.#t=n(s,u),this.#n=u}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){let d=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});return await d.initialize(),d}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:r,advanced:i,defender:a,policy:o,datasets:s}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:r,advanced:i,defender:a,policy:o,datasets:s}}});for(let t of e)(0,n.isMissing)(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=o?.enabled&&this.#o?this.#o.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs s3: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=s?.enabled&&this.#s?this.#s.sendActions(e,s).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([i?.enabled&&this.#i?this.#i.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),a?.enabled&&this.#a?this.#a.sendActions(e,a).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=r?.enabled&&this.#r?this.#r.sendActions(f,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,r){let{logs:i,advanced:a}=resolveOlapOptions(r);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:r,resolvedOptions:{logs:i,advanced:a}}}),(0,n.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={advancedExpiresAt:(a?.enabled&&this.#i?await this.#i.sendUnified(e,t,a).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};i?.enabled&&this.#r&&await this.#r.sendUnified(e,t,o,i).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,r){let i=await this.#r?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,r,i){let a=await this.#r?.getStep(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,r){let i=await this.#r?.getUnifiedLog(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,r,i){let a=await this.#r?.getProviderLog(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,r){let i=await this.#i?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepAdvancedLog(e,t,r,i){let a=await this.#i?.getStep(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedAdvancedLog(e,t,r){let i=await this.#i?.getUnified(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderAdvancedLog(e,t,r,i){let a=await this.#i?.getProvider(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getPlatformAdvancedLog(e,t){let r=await this.#i?.getPlatform(e,t);if((0,n.isMissing)(r)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return r}async getPolicyLog(e,t,r,i){let a=await this.#o?.getAction(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${i}`,category:`OlapClient`});return}return a}async getDefenderLog(e,t,r){let i=await this.#a?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u,getOlapClient:d=buildOlapClientInstance}){return this.olapClientPromise||=d({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};exports.AuthType=le,exports.ClickHouseClient=ClickHouseClient,exports.DEFAULT_TOPIC_CLUSTER_MAP=k,exports.Dimension=ae,exports.IntervalType=O,exports.LogType=T,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=E,exports.OrderDirection=D,exports.PolicySink=PolicySink,exports.SourceType=I,exports.StreamType=ce,exports.TransportType=L,exports.createConfigFromEnv=createConfigFromEnv,exports.createOlapQueryClient=createOlapQueryClient,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries;
230
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=(0,t.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}};function createOlapQueryClient(e,t){return new ClickHouseClient(e.clickhouse,t)}function createConfigFromEnv(){let e=process.env.CLICKHOUSE_URL;return{clickhouse:e?{url:e,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0}}const F={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},me={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},he={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},I={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},L=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],ge=[F.Scheduler,F.DataSync,F.DataSyncV2,F.Internal],_e=[`data_sync`],ve=[F.DataSync,F.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&L.includes(e)||t&&ge.includes(t))}function isDataSync(e,t){return!!(e&&_e.includes(e)||t&&ve.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>(0,n.isMissing)(e)?!1:Array.isArray(e)||(0,n.isString)(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,R=64*1024,z=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],B=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>(0,n.isObject)(e)?e[t]:void 0,e),withPath=(e,t,r)=>{let[i,...a]=t.split(`.`);if(a.length===0)return{...e,[i]:r};let o=e[i];return(0,n.isObject)(o)?{...e,[i]:withPath(o,a.join(`.`),r)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+(0,n.calculateSize)(r);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,r):e},fitObject=(e,t)=>{let r=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+(0,n.calculateSize)(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let r=(0,n.calculateSize)(e);return r<=t?e:((0,n.isString)(e)||Array.isArray(e)||(0,n.isObject)(e)&&!(0,n.isDate)(e))&&t<=0?marker(r):(0,n.isString)(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):(0,n.isObject)(e)&&!(0,n.isDate)(e)?fitObject(e,t):e},payloadFields=e=>z.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!(0,n.isMissing)(e)).map(e=>({...e,size:(0,n.calculateSize)(e.value)})),byRetentionPriority=e=>[...e.filter(e=>B.includes(e.path)),...e.filter(e=>!B.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*R;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(R,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>z.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),ye=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],be=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],xe=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed, content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`,error:e})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&(0,n.calculateSize)(e)>this.#n)return e;try{return await(0,r.scrubObjectAsync)(e,this.#a)}catch(t){return this.#i?.warning({message:`PII content scrub failed, storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`,error:t}),e}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(i.mode,i.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&a.success&&!a.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${i.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e={...i,body:await this.scrubPii((0,r.redactFields)(i.body,r.CensorType.PARTIAL,!0),t)},o={...a,body:await this.scrubPii((0,r.redactFields)(a.body,r.CensorType.PARTIAL,!0),t)},s=this.createActionS3(e,o,t),c=await this.send(s,t?.ttl);n.push(c)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let i={...e,inputs:await this.scrubPii((0,r.redactFields)(e.inputs,r.CensorType.PARTIAL,!0),n)},a={...t,outputs:await this.scrubPii((0,r.redactFields)(t.outputs,r.CensorType.PARTIAL,!0),n),errors:await this.scrubPii((0,r.redactFields)(t.errors,r.CensorType.PARTIAL,!0),n)},o=this.createStepS3(i,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let i={...e,body:await this.scrubPii((0,r.redactFields)(e.body,r.CensorType.PARTIAL,!0),n)},a={...t,body:await this.scrubPii((0,r.redactFields)(t.body,r.CensorType.PARTIAL,!0),n)},o=this.createUnifiedS3(i,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let i={...e,body:await this.scrubPii((0,r.redactFields)(e.body,r.CensorType.PARTIAL,!0),n)},a={...t,body:await this.scrubPii((0,r.redactFields)(t.body,r.CensorType.PARTIAL,!0),n)},o=this.createProviderS3(i,a,n);try{return await this.send(o,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let a=new i.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let a=this.requireBucket();try{let o=new i.GetObjectCommand({Bucket:a,Key:`${e}/${t}/${n}/steps/${r}.json`}),s=await this.#e.send(o);if(!s.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let c=await s.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(c)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let a=new i.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let a=this.requireBucket();try{let o=new i.GetObjectCommand({Bucket:a,Key:`${e}/${t}/${n}/provider/${r}.json`}),s=await this.#e.send(o);if(!s.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let c=await s.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(c)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let a=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,o=new Date(a*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:o.toISOString()}});try{return await this.#e.send(new i.PutObjectCommand({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:o,Tagging:r})),{expiresAt:o}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new i.HeadObjectCommand({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new i.GetObjectCommand({Bucket:n,Key:platformKey(e,t)}),a=await this.#e.send(r);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{Key:i,ContentType:`application/json`,Expires:new Date(a*1e3),Body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let i=(0,r.redactFields)(e.data,r.CensorType.PARTIAL,!0),a={...e.metadata,expirationTime:t,sizeBytes:(0,n.calculateSize)(i)};return this.stringifyPlatform({data:i,metadata:a},a)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,i,a){let o=(0,r.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},r.CensorType.PARTIAL),s=o.req?.headers,c=o.res?.headers,l=this.processContent(s,e.body,`upload`),u=this.processContent(c,t.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,p={};if(e.url)try{f=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(f);p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let m={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:f,path:e.pathParams,queryParams:p},body:l},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(c),body:u},...d?{isBackgroundLog:!0}:{}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,i,isErrorResult(t),a)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,i,a){let o=(0,r.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},r.CensorType.PARTIAL),s=o.req?.headers,c=o.res?.headers,l=this.processContent(s,e.body,`upload`),u=this.processContent(c,t.body,`download`),d=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=`/`,p=e.url,m={};if(e.url)try{p=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(p);f=t.pathname,m=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let h={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:p,path:f,queryParams:m},body:l},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(c),body:u}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(h,i,isErrorResult(t),a)}serializeProviderResult(e,t,n,i,a){let o=(0,r.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},r.CensorType.PARTIAL),s=o.req?.headers,c=o.res?.headers,l=this.processContent(s,e.body,`upload`),u=this.processContent(c,t.body,`download`),d,f=``,p=`/`,m={};if(e.url)try{d=(0,r.redactUrl)(e.url,r.CensorType.PARTIAL);let t=new URL(d);f=t.hostname,p=t.pathname,m=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let h={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(s),url:{url:d,hostname:f,path:p,queryParams:m},body:l},response:{statusCode:t.statusCode,headers:this.filterHeaders(c),body:u}},metadata:{expirationTime:n}};return this.serializeAndLimit(h,i,isErrorResult(t),a)}serializeAndLimit(e,t,r,i){let a=(0,n.calculateSize)(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?t*this.#r:t;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=ye.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return be.includes(i)||xe.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,n.isMissing)(e)){if(!(0,n.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new a.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[c.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new s.BasicTracerProvider({resource:(0,o.resourceFromAttributes)(n),spanProcessors:[new s.BatchSpanProcessor(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let r=0;for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),(0,n.isMissing)(i.body)&&(0,n.isMissing)(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,a);if((0,n.isMissing)(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if((0,n.exceedsSize)(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}this.send(i,e),r++}r>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${r} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let r=(0,n.isMissing)(e.body)?void 0:(0,n.extractSchema)(e.body),i=(0,n.isMissing)(t.body)?void 0:(0,n.extractSchema)(t.body);if(!((0,n.isMissing)(r)&&(0,n.isMissing)(i)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:r,result:i}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),r.push(null);continue}if((0,n.isMissing)(a.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:i.actionRunId}}),r.push(null);continue}let e=this.createDefenderS3(i,a),o=await this.send(e);r.push(o)}return r}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let a=new i.GetObjectCommand({Bucket:r,Key:this.generateS3Key(e,t,n)}),o=await this.#e.send(a);if(!o.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let s=await o.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),a=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:a,expiresAt:r.toISOString()}});try{return await this.#e.send(new i.PutObjectCommand({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:a})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},V=u.z.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new u.z.ZodError([{code:u.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},u.z.coerce.date()),H=u.z.object({logType:u.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:V,startTime:V,endTime:V.optional().nullable().transform(e=>e??void 0),durationMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:u.z.coerce.string(),projectSecureId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),U=H.extend({logType:u.z.literal(`action`),actionRunId:u.z.coerce.string(),actionId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string(),connectorOwner:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),actionType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:V.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:V.optional().nullable().transform(e=>e??void 0)}),W=H.extend({logType:u.z.literal(`step`),actionRunId:u.z.coerce.string(),stepIndex:u.z.coerce.number(),stepId:u.z.coerce.string(),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),skipped:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:u.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),G=H.extend({logType:u.z.literal(`unified`),requestId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:V.optional().nullable().transform(e=>e??void 0),duration:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:V.optional().nullable().transform(e=>e??void 0)}),K=H.extend({logType:u.z.literal(`provider`),requestId:u.z.coerce.string(),id:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string(),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string(),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),status:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:V.optional().nullable().transform(e=>e??void 0),duration:u.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),q=H.extend({logType:u.z.literal(`platform`),eventId:u.z.coerce.string(),eventType:u.z.coerce.string(),service:u.z.coerce.string(),organizationId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:u.z.undefined(),userId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:u.z.record(u.z.unknown()).optional().nullable().transform(e=>e??void 0)}),J=u.z.discriminatedUnion(`logType`,[U,W,G,K]),Se=new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Y=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a(){return this.#r?.isReady()?this.#r:void 0}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#o()}async#o(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#r;if(!r?.isReady())return this.#i?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#i?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,U),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,W),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t?.query({endpoint:`organization_platform_dimensions.json`,params:e});if(!n)return this.#i?.warning({message:`Platform log dimensions were requested but the ClickHouse client is not available`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=Se.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,q),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,t,r){let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r}});let{dimensions:a,startTime:o,endTime:s,...c}=r,l=r.intervalType===E.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,n.convertKeysToCamelCase)(e,!0)).map(e=>{let t={...e};for(let e of Y)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){return i?.isReady()?this.#i?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,maxValues:s,...c}=n,l={organizationId:e,projectSecureId:t,...c,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()},...s&&{maxValuesPerDim:s}},u=await r?.query({endpoint:`project_logs_dimensions.json`,params:l});if(!u)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${u.length} dimension facets`,category:`LogsSink`});let d={};for(let e of u)Y.includes(e.dimension)?d[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):d[e.dimension]=e.values;return d}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,...o&&{sourceType:Array.isArray(o)?o.join(`,`):o},...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r?.query({endpoint:`project_source_usage.json`,params:s});return c?(this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#s(e){return(this.#n??D)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#s(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#c(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#c(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??(0,l.randomUUID)(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof u.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,J)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof u.ZodError?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return U;case`step`:return W;case`unified`:return G;case`provider`:return K;case`platform`:return q}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...X.logs,...e?.logs},advanced:{...X.advanced,...e?.advanced},defender:{...X.defender,...e?.defender},policy:{...X.policy,...e?.policy},datasets:{...X.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Policy sink bucket is not configured`);return this.#t}async initialize(){this.#e||this.#r?.warning({message:`No s3 client provided, policy sink will not function`,category:`PolicySink`})}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let r=[];for(let{input:i,result:a}of e){if(!t?.enabled){r.push(null);continue}if(!this.#t){r.push(null);continue}if((0,n.isMissing)(a.policyContext)){r.push(null);continue}let e=await this.send(this.createPolicyS3(i,a));r.push(e)}return r}async getAction(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from policy sink`,category:`PolicySink`});return}if(this.#t)try{let a=await this.#e.send(new i.GetObjectCommand({Bucket:this.requireBucket(),Key:this.generateS3Key(e,t,n,r)}));if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get policy log from S3 for actionRunId ${r}`,category:`PolicySink`});return}return JSON.parse(await a.Body.transformToString())}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Policy log not found in S3 for actionRunId ${r}`,category:`PolicySink`});return}throw this.#r?.error({message:`Error when getting policy log from S3 for actionRunId ${r}`,error:e,code:`PolicyLogReadError`,category:`PolicySink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to policy sink`);let t=new Date(Date.now()+this.#n*24*60*60*1e3);try{return await this.#e.send(new i.PutObjectCommand({Bucket:this.requireBucket(),Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:t,Tagging:`ttl=${this.#n}d`})),{expiresAt:t}}catch(t){throw this.#r?.error({message:`Failed to write policy log to S3 at ${e.Key}`,error:t,code:`PolicyLogWriteError`,category:`PolicySink`}),t}}generateS3Key(e,t,n,r){return`${e}/${t}/${n}/${r}/policy.json`}createPolicyS3(e,t){return{Key:this.generateS3Key(e.organizationId,e.projectSecureId,e.accountSecureId,e.actionRunId),Body:JSON.stringify(t.policyContext),ContentType:`application/json`}}};const Z=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Z}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Z}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),Q=__name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=Q(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=Q(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new i.S3Client(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=c,this.#p=l,this.#t=n(s,u),this.#n=u}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){let d=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});return await d.initialize(),d}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:r,advanced:i,defender:a,policy:o,datasets:s}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:r,advanced:i,defender:a,policy:o,datasets:s}}});for(let t of e)(0,n.isMissing)(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=o?.enabled&&this.#o?this.#o.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs s3: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=s?.enabled&&this.#s?this.#s.sendActions(e,s).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([i?.enabled&&this.#i?this.#i.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),a?.enabled&&this.#a?this.#a.sendActions(e,a).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=r?.enabled&&this.#r?this.#r.sendActions(f,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,r){let{logs:i,advanced:a}=resolveOlapOptions(r);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:r,resolvedOptions:{logs:i,advanced:a}}}),(0,n.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={advancedExpiresAt:(a?.enabled&&this.#i?await this.#i.sendUnified(e,t,a).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};i?.enabled&&this.#r&&await this.#r.sendUnified(e,t,o,i).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,r){let i=await this.#r?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,r,i){let a=await this.#r?.getStep(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,r){let i=await this.#r?.getUnifiedLog(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,t,r,i){let a=await this.#r?.getProviderLog(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,r){let i=await this.#i?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepAdvancedLog(e,t,r,i){let a=await this.#i?.getStep(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedAdvancedLog(e,t,r){let i=await this.#i?.getUnified(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderAdvancedLog(e,t,r,i){let a=await this.#i?.getProvider(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getPlatformAdvancedLog(e,t){let r=await this.#i?.getPlatform(e,t);if((0,n.isMissing)(r)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return r}async getPolicyLog(e,t,r,i){let a=await this.#o?.getAction(e,t,r,i);if((0,n.isMissing)(a)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${i}`,category:`OlapClient`});return}return a}async getDefenderLog(e,t,r){let i=await this.#a?.getAction(e,t,r);if((0,n.isMissing)(i)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u,getOlapClient:d=buildOlapClientInstance}){return this.olapClientPromise||=d({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};exports.AuthType=I,exports.ClickHouseClient=ClickHouseClient,exports.DEFAULT_TOPIC_CLUSTER_MAP=D,exports.Dimension=se,exports.IntervalType=E,exports.LogType=T,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=ae,exports.OrderDirection=oe,exports.PlatformDimension=ce,exports.PolicySink=PolicySink,exports.SourceType=F,exports.StreamType=he,exports.TransportType=me,exports.createConfigFromEnv=createConfigFromEnv,exports.createOlapQueryClient=createOlapQueryClient,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries;
package/dist/index.d.cts CHANGED
@@ -205,6 +205,7 @@ interface IOlapClient {
205
205
  getProviderLogs(organizationId: string, projectSecureId: string, query: ProviderQuery): Promise<ProviderQueryResult>;
206
206
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
207
207
  getPlatformLogs(organizationId: string | undefined, query: PlatformQuery): Promise<PlatformQueryResult>;
208
+ getPlatformLogDimensions(organizationId: string | undefined, query: PlatformDimensionsQuery): Promise<DimensionsResult>;
208
209
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
209
210
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
210
211
  getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
@@ -755,6 +756,27 @@ type DimensionsResult = {
755
756
  count: number;
756
757
  }>;
757
758
  };
759
+ declare const PlatformDimension: {
760
+ readonly EventType: "eventType";
761
+ readonly Action: "action";
762
+ readonly Resource: "resource";
763
+ readonly Service: "service";
764
+ readonly SourceType: "sourceType";
765
+ readonly SourceId: "sourceId";
766
+ readonly AuthType: "authType";
767
+ readonly UserEmail: "userEmail";
768
+ readonly StatusCode: "statusCode";
769
+ readonly Success: "success";
770
+ readonly IsRead: "isRead";
771
+ readonly AgentId: "agentId";
772
+ readonly TransportType: "transportType";
773
+ readonly StreamType: "streamType";
774
+ };
775
+ type PlatformDimension = (typeof PlatformDimension)[keyof typeof PlatformDimension];
776
+ type PlatformDimensionsQuery = Partial<PlatformQuery> & {
777
+ dimensions: PlatformDimension[];
778
+ maxValues?: number;
779
+ };
758
780
  type SourceQuery = Partial<Query>;
759
781
  type SourceResult = Array<{
760
782
  sourceId: string;
@@ -1103,6 +1125,7 @@ declare class OlapClient implements IOlapClient {
1103
1125
  getUnifiedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedLog | undefined>;
1104
1126
  getProviderLogs(organizationId: string, projectSecureId: string, query: ProviderQuery): Promise<ProviderQueryResult>;
1105
1127
  getPlatformLogs(organizationId: string | undefined, query: PlatformQuery): Promise<PlatformQueryResult>;
1128
+ getPlatformLogDimensions(organizationId: string | undefined, query: PlatformDimensionsQuery): Promise<DimensionsResult>;
1106
1129
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
1107
1130
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
1108
1131
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
@@ -1199,4 +1222,4 @@ declare class PolicySink implements IPolicySink {
1199
1222
  //#region src/utils/stepErrors.d.ts
1200
1223
  declare const hasErrorEntries: (errors: unknown) => boolean;
1201
1224
  //#endregion
1202
- export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedLogMetadata, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, type CombinedLogType, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IPolicySink, type IQueryClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type OlapQueryClientConfig, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformAdvancedLog, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type PolicyContext, type PolicyLog, type PolicyObservation, type PolicyOptions, type PolicyRecord, type PolicyResult, PolicySink, type PolicySinkConfig, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type TruncationMode, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, getPolicySink, hasErrorEntries };
1225
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedLogMetadata, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, type CombinedLogType, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IPolicySink, type IQueryClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type OlapQueryClientConfig, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformAdvancedLog, PlatformDimension, type PlatformDimension as PlatformDimensionValues, type PlatformDimensionsQuery, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type PolicyContext, type PolicyLog, type PolicyObservation, type PolicyOptions, type PolicyRecord, type PolicyResult, PolicySink, type PolicySinkConfig, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type TruncationMode, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, getPolicySink, hasErrorEntries };
package/dist/index.d.mts CHANGED
@@ -204,6 +204,7 @@ interface IOlapClient {
204
204
  getProviderLogs(organizationId: string, projectSecureId: string, query: ProviderQuery): Promise<ProviderQueryResult>;
205
205
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
206
206
  getPlatformLogs(organizationId: string | undefined, query: PlatformQuery): Promise<PlatformQueryResult>;
207
+ getPlatformLogDimensions(organizationId: string | undefined, query: PlatformDimensionsQuery): Promise<DimensionsResult>;
207
208
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
208
209
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
209
210
  getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
@@ -754,6 +755,27 @@ type DimensionsResult = {
754
755
  count: number;
755
756
  }>;
756
757
  };
758
+ declare const PlatformDimension: {
759
+ readonly EventType: "eventType";
760
+ readonly Action: "action";
761
+ readonly Resource: "resource";
762
+ readonly Service: "service";
763
+ readonly SourceType: "sourceType";
764
+ readonly SourceId: "sourceId";
765
+ readonly AuthType: "authType";
766
+ readonly UserEmail: "userEmail";
767
+ readonly StatusCode: "statusCode";
768
+ readonly Success: "success";
769
+ readonly IsRead: "isRead";
770
+ readonly AgentId: "agentId";
771
+ readonly TransportType: "transportType";
772
+ readonly StreamType: "streamType";
773
+ };
774
+ type PlatformDimension = (typeof PlatformDimension)[keyof typeof PlatformDimension];
775
+ type PlatformDimensionsQuery = Partial<PlatformQuery> & {
776
+ dimensions: PlatformDimension[];
777
+ maxValues?: number;
778
+ };
757
779
  type SourceQuery = Partial<Query>;
758
780
  type SourceResult = Array<{
759
781
  sourceId: string;
@@ -1102,6 +1124,7 @@ declare class OlapClient implements IOlapClient {
1102
1124
  getUnifiedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedLog | undefined>;
1103
1125
  getProviderLogs(organizationId: string, projectSecureId: string, query: ProviderQuery): Promise<ProviderQueryResult>;
1104
1126
  getPlatformLogs(organizationId: string | undefined, query: PlatformQuery): Promise<PlatformQueryResult>;
1127
+ getPlatformLogDimensions(organizationId: string | undefined, query: PlatformDimensionsQuery): Promise<DimensionsResult>;
1105
1128
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
1106
1129
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
1107
1130
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
@@ -1198,4 +1221,4 @@ declare class PolicySink implements IPolicySink {
1198
1221
  //#region src/utils/stepErrors.d.ts
1199
1222
  declare const hasErrorEntries: (errors: unknown) => boolean;
1200
1223
  //#endregion
1201
- export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedLogMetadata, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, type CombinedLogType, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IPolicySink, type IQueryClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type OlapQueryClientConfig, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformAdvancedLog, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type PolicyContext, type PolicyLog, type PolicyObservation, type PolicyOptions, type PolicyRecord, type PolicyResult, PolicySink, type PolicySinkConfig, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type TruncationMode, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, getPolicySink, hasErrorEntries };
1224
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedLogMetadata, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, type CombinedLogType, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IPolicySink, type IQueryClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type OlapQueryClientConfig, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformAdvancedLog, PlatformDimension, type PlatformDimension as PlatformDimensionValues, type PlatformDimensionsQuery, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type PolicyContext, type PolicyLog, type PolicyObservation, type PolicyOptions, type PolicyRecord, type PolicyResult, PolicySink, type PolicySinkConfig, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type TruncationMode, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, getPolicySink, hasErrorEntries };
package/dist/index.mjs CHANGED
@@ -74,7 +74,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
74
74
  WHERE ${t} IN {entityIds:Array(String)}
75
75
  ORDER BY eventTime DESC
76
76
  LIMIT 1 BY ${t}
77
- `,r=toArray(e.entities?.ids),i=buildLogsViewParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const P={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),pe={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},me={Asc:`asc`,Desc:`desc`},F={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},he={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},I={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===P.Platform,L={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},R={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},z={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(R,e)?R[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(z,e)?z[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(u),n=e.intervalType??`hour`,r=Math.floor(Number(e.intervalPeriod??1)),i=Number.isFinite(r)&&r>0?r:1,a=t.filter(e=>Object.prototype.hasOwnProperty.call(L,e)).map(e=>L[e]),o=n===F.None?void 0:buildTimeBucket(n,i),s=[...o?[`${o} as startTime`]:[],`count() as count`,...a].join(`, `),c=[...o?[`startTime`]:[],...a],l=c.length>0?`GROUP BY ${c.join(`, `)}`:``,d=o?`ORDER BY startTime ASC`:``;return{sql:`
77
+ `,r=toArray(e.entities?.ids),i=buildLogsViewParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const P={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),pe={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},me={Asc:`asc`,Desc:`desc`},F={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},he={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},ge={EventType:`eventType`,Action:`action`,Resource:`resource`,Service:`service`,SourceType:`sourceType`,SourceId:`sourceId`,AuthType:`authType`,UserEmail:`userEmail`,StatusCode:`statusCode`,Success:`success`,IsRead:`isRead`,AgentId:`agentId`,TransportType:`transportType`,StreamType:`streamType`},I={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===P.Platform,L={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},R={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},z={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(R,e)?R[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(z,e)?z[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(u),n=e.intervalType??`hour`,r=Math.floor(Number(e.intervalPeriod??1)),i=Number.isFinite(r)&&r>0?r:1,a=t.filter(e=>Object.prototype.hasOwnProperty.call(L,e)).map(e=>L[e]),o=n===F.None?void 0:buildTimeBucket(n,i),s=[...o?[`${o} as startTime`]:[],`count() as count`,...a].join(`, `),c=[...o?[`startTime`]:[],...a],l=c.length>0?`GROUP BY ${c.join(`, `)}`:``,d=o?`ORDER BY startTime ASC`:``;return{sql:`
78
78
  WITH logs AS (
79
79
  ${buildLogsViewSource()}
80
80
  )
@@ -83,19 +83,44 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
83
83
  FROM logs
84
84
  ${l}
85
85
  ${d}
86
- `,params:buildLogsViewParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const ge={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},B=`provider_logs_filtered`,V=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),H=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
86
+ `,params:buildLogsViewParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const _e={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},B=`provider_logs_filtered`,V=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),H=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
87
87
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
88
88
  SELECT *
89
89
  FROM ${B}(${V})
90
90
  ${H}
91
- ORDER BY ${sanitizeOrderBy(e.orderBy,ge,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
91
+ ORDER BY ${sanitizeOrderBy(e.orderBy,_e,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
92
92
  LIMIT {limit:UInt32}
93
93
  OFFSET {offset:UInt32}
94
94
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildProviderLogsCountQuery(e){return{sql:`
95
95
  SELECT count() as total
96
96
  FROM ${B}(${V})
97
97
  ${H}
98
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const _e={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
98
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const ve=[...[`organizationId`,`projectSecureId`,`eventId`,`eventType`,`service`,`userId`,`userEmail`,`action`,`resource`,`resourceId`,`sourceType`,`sourceId`,`authType`,`authId`,`userAgent`,`ipAddress`,`sessionId`,`agentId`,`transportType`,`streamType`].map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isRead = {isRead:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),ye={eventType:`eventType`,action:`action`,resource:`resource`,service:`service`,sourceType:`sourceType`,sourceId:`sourceId`,authType:`authType`,userEmail:`userEmail`,statusCode:`statusCode`,success:`success`,isRead:`isRead`,agentId:`agentId`,transportType:`transportType`,streamType:`streamType`},be=new Set([`statusCode`,`success`,`isRead`]),xe=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
99
+ AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`,buildPlatformViewSource=()=>`SELECT *
100
+ FROM platform_filtered(${ve})
101
+ ${xe}`,buildPlatformViewParams=e=>({organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)});function buildPlatformDimensionsQuery(e){let t=toArray(e.dimensions).map(u),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(ye,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildPlatformViewSource();return{sql:r.map(e=>{let t=ye[e];return`
102
+ SELECT
103
+ '${e}' as dimension,
104
+ arrayReverseSort(
105
+ facet -> facet.2,
106
+ groupArray(CAST((value, count), 'Tuple(value String, count UInt64)'))
107
+ ) as \`values\`
108
+ FROM (
109
+ SELECT
110
+ toString(${t}) as value,
111
+ count() as count
112
+ FROM (
113
+ ${i}
114
+ ) AS platformLogs
115
+ WHERE ${t} IS NOT NULL
116
+ ${be.has(e)?``:`AND ${t} != ''`}
117
+ GROUP BY ${t}
118
+ ORDER BY count DESC
119
+ LIMIT {maxValues:UInt32}
120
+ ) AS facets
121
+ `}).join(`
122
+ UNION ALL
123
+ `),params:{...buildPlatformViewParams(e),maxValues:n}}}registerQuery({id:`organization_platform_dimensions.json`,buildQuery:buildPlatformDimensionsQuery});const Se={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
99
124
  SELECT
100
125
  eventTime,
101
126
  startTime,
@@ -153,7 +178,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
153
178
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
154
179
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
155
180
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
156
- ORDER BY ${sanitizeOrderBy(e.orderBy,_e,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
181
+ ORDER BY ${sanitizeOrderBy(e.orderBy,Se,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
157
182
  LIMIT {limit:UInt32}
158
183
  OFFSET {offset:UInt32}
159
184
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildPlatformLogsCountQuery(e){return{sql:`
@@ -202,4 +227,4 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
202
227
  AND sourceId != ''
203
228
  GROUP BY sourceId, sourceType
204
229
  ORDER BY request_count DESC
205
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=t({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}};function createOlapQueryClient(e,t){return new ClickHouseClient(e.clickhouse,t)}function createConfigFromEnv(){let e=process.env.CLICKHOUSE_URL;return{clickhouse:e?{url:e,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0}}const U={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},ve={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},ye={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},be={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},xe=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],Se=[U.Scheduler,U.DataSync,U.DataSyncV2,U.Internal],Ce=[`data_sync`],we=[U.DataSync,U.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&xe.includes(e)||t&&Se.includes(t))}function isDataSync(e,t){return!!(e&&Ce.includes(e)||t&&we.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>s(e)?!1:Array.isArray(e)||l(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,W=64*1024,G=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],K=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>c(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return c(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+n(r);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,r):e},fitObject=(e,t)=>{let r=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+n(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let r=n(e);return r<=t?e:(l(e)||Array.isArray(e)||c(e)&&!o(e))&&t<=0?marker(r):l(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):c(e)&&!o(e)?fitObject(e,t):e},payloadFields=e=>G.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!s(e)).map(e=>({...e,size:n(e.value)})),byRetentionPriority=e=>[...e.filter(e=>K.includes(e.path)),...e.filter(e=>!K.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*W;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(W,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>G.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),Te=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],Ee=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],De=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed, content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`,error:e})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&n(e)>this.#n)return e;try{return await h(e,this.#a)}catch(t){return this.#i?.warning({message:`PII content scrub failed, storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`,error:t}),e}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e={...r,body:await this.scrubPii(f(r.body,d.PARTIAL,!0),t)},a={...i,body:await this.scrubPii(f(i.body,d.PARTIAL,!0),t)},o=this.createActionS3(e,a,t),s=await this.send(o,t?.ttl);n.push(s)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r={...e,inputs:await this.scrubPii(f(e.inputs,d.PARTIAL,!0),n)},i={...t,outputs:await this.scrubPii(f(t.outputs,d.PARTIAL,!0),n),errors:await this.scrubPii(f(t.errors,d.PARTIAL,!0),n)},a=this.createStepS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(f(e.body,d.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(f(t.body,d.PARTIAL,!0),n)},a=this.createUnifiedS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(f(e.body,d.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(f(t.body,d.PARTIAL,!0),n)},a=this.createProviderS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new v({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new _({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new g({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{Key:i,ContentType:`application/json`,Expires:new Date(a*1e3),Body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let r=f(e.data,d.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:n(r)};return this.stringifyPlatform({data:r,metadata:i},i)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=p({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},d.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,h={};if(e.url)try{f=m(e.url,d.PARTIAL);let t=new URL(f);h=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let g={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:f,path:e.pathParams,queryParams:h},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l},...u?{isBackgroundLog:!0}:{}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=p({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},d.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=`/`,h=e.url,g={};if(e.url)try{h=m(e.url,d.PARTIAL);let t=new URL(h);f=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let _={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:h,path:f,queryParams:g},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=p({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},d.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u,f=``,h=`/`,g={};if(e.url)try{u=m(e.url,d.PARTIAL);let t=new URL(u);f=t.hostname,h=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let _={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:u,hostname:f,path:h,queryParams:g},body:c},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeAndLimit(e,t,r,i){let a=n(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?t*this.#r:t;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=Te.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return Ee.includes(i)||De.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!s(e)){if(!l(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new te({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[ae]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new re({resource:ne(n),spanProcessors:[new ie(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),s(r.body)&&s(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,a);if(s(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(i(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=s(e.body)?void 0:a(e.body),r=s(t.body)?void 0:a(t.body);if(!(s(n)&&s(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(s(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new v({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},q=b.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new b.ZodError([{code:b.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},b.coerce.date()),J=b.object({logType:b.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:q,startTime:q,endTime:q.optional().nullable().transform(e=>e??void 0),durationMs:b.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:b.coerce.string(),projectSecureId:b.coerce.string().optional().nullable().transform(e=>e??void 0)}),Y=J.extend({logType:b.literal(`action`),actionRunId:b.coerce.string(),actionId:b.coerce.string(),connectorKey:b.coerce.string(),connectorVersion:b.coerce.string(),connectorOwner:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:b.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),actionType:b.coerce.string().optional().nullable().transform(e=>e??void 0),mode:b.coerce.string().optional().nullable().transform(e=>e??void 0),category:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:b.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:b.coerce.string().optional().nullable().transform(e=>e??void 0),url:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:b.coerce.string().optional().nullable().transform(e=>e??void 0),authType:b.coerce.string().optional().nullable().transform(e=>e??void 0),authId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:b.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:b.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:b.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:b.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:b.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:b.coerce.string().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:b.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:b.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:b.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:b.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:b.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:q.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:q.optional().nullable().transform(e=>e??void 0)}),X=J.extend({logType:b.literal(`step`),actionRunId:b.coerce.string(),stepIndex:b.coerce.number(),stepId:b.coerce.string(),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),skipped:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),message:b.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:b.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:b.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:b.coerce.number().optional().nullable().transform(e=>e??void 0)}),Z=J.extend({logType:b.literal(`unified`),requestId:b.coerce.string(),connectorKey:b.coerce.string(),connectorVersion:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:b.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),mode:b.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:b.coerce.string().optional().nullable().transform(e=>e??void 0),url:b.coerce.string().optional().nullable().transform(e=>e??void 0),path:b.coerce.string().optional().nullable().transform(e=>e??void 0),resource:b.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),service:b.coerce.string().optional().nullable().transform(e=>e??void 0),action:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:b.coerce.string().optional().nullable().transform(e=>e??void 0),authType:b.coerce.string().optional().nullable().transform(e=>e??void 0),authId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:b.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:b.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:b.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:b.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:b.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:b.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:b.coerce.number().optional().nullable().transform(e=>e??void 0),provider:b.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:q.optional().nullable().transform(e=>e??void 0),duration:b.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:q.optional().nullable().transform(e=>e??void 0)}),Q=J.extend({logType:b.literal(`provider`),requestId:b.coerce.string(),id:b.coerce.string().optional().nullable().transform(e=>e??void 0),action:b.coerce.string(),mode:b.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:b.coerce.string(),originOwnerId:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:b.coerce.string().optional().nullable().transform(e=>e??void 0),url:b.coerce.string(),path:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:b.coerce.string(),connectorVersion:b.coerce.string().optional().nullable().transform(e=>e??void 0),resource:b.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),service:b.coerce.string().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),status:b.coerce.number().optional().nullable().transform(e=>e??void 0),provider:b.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:q.optional().nullable().transform(e=>e??void 0),duration:b.coerce.number().optional().nullable().transform(e=>e??void 0)}),Oe=J.extend({logType:b.literal(`platform`),eventId:b.coerce.string(),eventType:b.coerce.string(),service:b.coerce.string(),organizationId:b.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:b.undefined(),userId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:b.coerce.string().optional().nullable().transform(e=>e??void 0),action:b.coerce.string().optional().nullable().transform(e=>e??void 0),resource:b.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),authType:b.coerce.string().optional().nullable().transform(e=>e??void 0),authId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:b.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:b.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:b.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:b.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:b.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:b.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:b.record(b.unknown()).optional().nullable().transform(e=>e??void 0)}),ke=b.discriminatedUnion(`logType`,[Y,X,Z,Q]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Ae=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a(){return this.#r?.isReady()?this.#r:void 0}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#o()}async#o(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#r;if(!r?.isReady())return this.#i?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#i?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,Y),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,X),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,Z),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,Q),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,Oe),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,t,n){let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n}});let{dimensions:a,startTime:o,endTime:s,...c}=n,l=n.intervalType===F.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>r(e,!0)).map(e=>{let t={...e};for(let e of Ae)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){return i?.isReady()?this.#i?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,maxValues:s,...c}=n,l={organizationId:e,projectSecureId:t,...c,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()},...s&&{maxValuesPerDim:s}},u=await r?.query({endpoint:`project_logs_dimensions.json`,params:l});if(!u)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${u.length} dimension facets`,category:`LogsSink`});let d={};for(let e of u)Ae.includes(e.dimension)?d[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):d[e.dimension]=e.values;return d}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,...o&&{sourceType:Array.isArray(o)?o.join(`,`):o},...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r?.query({endpoint:`project_source_usage.json`,params:s});return c?(this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#s(e){return(this.#n??I)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#s(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#c(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#c(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??oe(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof y){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,ke)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof y?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return Y;case`step`:return X;case`unified`:return Z;case`provider`:return Q;case`platform`:return Oe}}};const $={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...$.logs,...e?.logs},advanced:{...$.advanced,...e?.advanced},defender:{...$.defender,...e?.defender},policy:{...$.policy,...e?.policy},datasets:{...$.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Policy sink bucket is not configured`);return this.#t}async initialize(){this.#e||this.#r?.warning({message:`No s3 client provided, policy sink will not function`,category:`PolicySink`})}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(!t?.enabled){n.push(null);continue}if(!this.#t){n.push(null);continue}if(s(i.policyContext)){n.push(null);continue}let e=await this.send(this.createPolicyS3(r,i));n.push(e)}return n}async getAction(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from policy sink`,category:`PolicySink`});return}if(this.#t)try{let i=await this.#e.send(new g({Bucket:this.requireBucket(),Key:this.generateS3Key(e,t,n,r)}));if(!i.Body){this.#r?.warning({message:`Received empty body when trying to get policy log from S3 for actionRunId ${r}`,category:`PolicySink`});return}return JSON.parse(await i.Body.transformToString())}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Policy log not found in S3 for actionRunId ${r}`,category:`PolicySink`});return}throw this.#r?.error({message:`Error when getting policy log from S3 for actionRunId ${r}`,error:e,code:`PolicyLogReadError`,category:`PolicySink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to policy sink`);let t=new Date(Date.now()+this.#n*24*60*60*1e3);try{return await this.#e.send(new v({Bucket:this.requireBucket(),Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:t,Tagging:`ttl=${this.#n}d`})),{expiresAt:t}}catch(t){throw this.#r?.error({message:`Failed to write policy log to S3 at ${e.Key}`,error:t,code:`PolicyLogWriteError`,category:`PolicySink`}),t}}generateS3Key(e,t,n,r){return`${e}/${t}/${n}/${r}/policy.json`}createPolicyS3(e,t){return{Key:this.generateS3Key(e.organizationId,e.projectSecureId,e.accountSecureId,e.actionRunId),Body:JSON.stringify(t.policyContext),ContentType:`application/json`}}};const je=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${je}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${je}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),Me=e(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=Me(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=Me(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new ee(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var Ne=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=c,this.#p=l,this.#t=n(s,u),this.#n=u}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){let d=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});return await d.initialize(),d}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,policy:a,datasets:o}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,policy:a,datasets:o}}});for(let t of e)s(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=a?.enabled&&this.#o?this.#o.sendActions(e,a).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs s3: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=o?.enabled&&this.#s?this.#s.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([r?.enabled&&this.#i?this.#i.sendActions(e,r).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#a?this.#a.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=n?.enabled&&this.#r?this.#r.sendActions(f,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}}),s(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#i?await this.#i.sendUnified(e,t,i).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#r&&await this.#r.sendUnified(e,t,a,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n){let r=await this.#r?.getAction(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,r){let i=await this.#r?.getStep(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n){let r=await this.#r?.getUnifiedLog(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,n,r){let i=await this.#r?.getProviderLog(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getActionAdvancedLog(e,t,n){let r=await this.#i?.getAction(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#i?.getStep(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#i?.getUnified(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#i?.getProvider(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#i?.getPlatform(e,t);if(s(n)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getPolicyLog(e,t,n,r){let i=await this.#o?.getAction(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u})=>Ne.create({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u,getOlapClient:d=buildOlapClientInstance}){return this.olapClientPromise||=d({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{be as AuthType,ClickHouseClient,I as DEFAULT_TOPIC_CLUSTER_MAP,he as Dimension,F as IntervalType,P as LogType,Ne as OlapClient,OlapClientManager,pe as OrderBy,me as OrderDirection,PolicySink,U as SourceType,ye as StreamType,ve as TransportType,createConfigFromEnv,createOlapQueryClient,getPolicySink,hasErrorEntries};
230
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=t({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}};function createOlapQueryClient(e,t){return new ClickHouseClient(e.clickhouse,t)}function createConfigFromEnv(){let e=process.env.CLICKHOUSE_URL;return{clickhouse:e?{url:e,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0}}const U={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},Ce={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},we={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},Te={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},Ee=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],De=[U.Scheduler,U.DataSync,U.DataSyncV2,U.Internal],Oe=[`data_sync`],ke=[U.DataSync,U.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&Ee.includes(e)||t&&De.includes(t))}function isDataSync(e,t){return!!(e&&Oe.includes(e)||t&&ke.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>s(e)?!1:Array.isArray(e)||l(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,W=64*1024,G=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],K=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>c(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return c(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+n(r);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,r):e},fitObject=(e,t)=>{let r=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+n(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let r=n(e);return r<=t?e:(l(e)||Array.isArray(e)||c(e)&&!o(e))&&t<=0?marker(r):l(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):c(e)&&!o(e)?fitObject(e,t):e},payloadFields=e=>G.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!s(e)).map(e=>({...e,size:n(e.value)})),byRetentionPriority=e=>[...e.filter(e=>K.includes(e.path)),...e.filter(e=>!K.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*W;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(W,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>G.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),Ae=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],je=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],Me=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed, content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`,error:e})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&n(e)>this.#n)return e;try{return await h(e,this.#a)}catch(t){return this.#i?.warning({message:`PII content scrub failed, storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`,error:t}),e}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e={...r,body:await this.scrubPii(f(r.body,d.PARTIAL,!0),t)},a={...i,body:await this.scrubPii(f(i.body,d.PARTIAL,!0),t)},o=this.createActionS3(e,a,t),s=await this.send(o,t?.ttl);n.push(s)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r={...e,inputs:await this.scrubPii(f(e.inputs,d.PARTIAL,!0),n)},i={...t,outputs:await this.scrubPii(f(t.outputs,d.PARTIAL,!0),n),errors:await this.scrubPii(f(t.errors,d.PARTIAL,!0),n)},a=this.createStepS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(f(e.body,d.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(f(t.body,d.PARTIAL,!0),n)},a=this.createUnifiedS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(f(e.body,d.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(f(t.body,d.PARTIAL,!0),n)},a=this.createProviderS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new g({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new v({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new _({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new g({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{Key:i,ContentType:`application/json`,Expires:new Date(a*1e3),Body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let r=f(e.data,d.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:n(r)};return this.stringifyPlatform({data:r,metadata:i},i)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=p({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},d.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=e.url,h={};if(e.url)try{f=m(e.url,d.PARTIAL);let t=new URL(f);h=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let g={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:f,path:e.pathParams,queryParams:h},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l},...u?{isBackgroundLog:!0}:{}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=p({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},d.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),f=`/`,h=e.url,g={};if(e.url)try{h=m(e.url,d.PARTIAL);let t=new URL(h);f=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let _={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:h,path:f,queryParams:g},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=p({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},d.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u,f=``,h=`/`,g={};if(e.url)try{u=m(e.url,d.PARTIAL);let t=new URL(u);f=t.hostname,h=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let _={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:u,hostname:f,path:h,queryParams:g},body:c},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeAndLimit(e,t,r,i){let a=n(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?t*this.#r:t;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=Ae.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return je.includes(i)||Me.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!s(e)){if(!l(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new te({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[ae]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new re({resource:ne(n),spanProcessors:[new ie(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),s(r.body)&&s(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,a);if(s(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(i(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=s(e.body)?void 0:a(e.body),r=s(t.body)?void 0:a(t.body);if(!(s(n)&&s(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(s(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new g({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new v({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},q=b.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new b.ZodError([{code:b.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},b.coerce.date()),J=b.object({logType:b.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:q,startTime:q,endTime:q.optional().nullable().transform(e=>e??void 0),durationMs:b.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:b.coerce.string(),projectSecureId:b.coerce.string().optional().nullable().transform(e=>e??void 0)}),Y=J.extend({logType:b.literal(`action`),actionRunId:b.coerce.string(),actionId:b.coerce.string(),connectorKey:b.coerce.string(),connectorVersion:b.coerce.string(),connectorOwner:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:b.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),actionType:b.coerce.string().optional().nullable().transform(e=>e??void 0),mode:b.coerce.string().optional().nullable().transform(e=>e??void 0),category:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:b.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:b.coerce.string().optional().nullable().transform(e=>e??void 0),url:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:b.coerce.string().optional().nullable().transform(e=>e??void 0),authType:b.coerce.string().optional().nullable().transform(e=>e??void 0),authId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:b.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:b.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:b.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:b.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:b.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:b.coerce.string().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:b.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:b.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:b.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:b.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:b.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:b.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:q.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:q.optional().nullable().transform(e=>e??void 0)}),X=J.extend({logType:b.literal(`step`),actionRunId:b.coerce.string(),stepIndex:b.coerce.number(),stepId:b.coerce.string(),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),skipped:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),message:b.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:b.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:b.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:b.coerce.number().optional().nullable().transform(e=>e??void 0)}),Z=J.extend({logType:b.literal(`unified`),requestId:b.coerce.string(),connectorKey:b.coerce.string(),connectorVersion:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:b.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),mode:b.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:b.coerce.string().optional().nullable().transform(e=>e??void 0),url:b.coerce.string().optional().nullable().transform(e=>e??void 0),path:b.coerce.string().optional().nullable().transform(e=>e??void 0),resource:b.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),service:b.coerce.string().optional().nullable().transform(e=>e??void 0),action:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:b.coerce.string().optional().nullable().transform(e=>e??void 0),authType:b.coerce.string().optional().nullable().transform(e=>e??void 0),authId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:b.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:b.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:b.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:b.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:b.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:b.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:b.coerce.number().optional().nullable().transform(e=>e??void 0),provider:b.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:q.optional().nullable().transform(e=>e??void 0),duration:b.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:q.optional().nullable().transform(e=>e??void 0)}),Q=J.extend({logType:b.literal(`provider`),requestId:b.coerce.string(),id:b.coerce.string().optional().nullable().transform(e=>e??void 0),action:b.coerce.string(),mode:b.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:b.coerce.string(),originOwnerId:b.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:b.coerce.string().optional().nullable().transform(e=>e??void 0),url:b.coerce.string(),path:b.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:b.coerce.string(),connectorVersion:b.coerce.string().optional().nullable().transform(e=>e??void 0),resource:b.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:b.coerce.string().optional().nullable().transform(e=>e??void 0),service:b.coerce.string().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:b.coerce.string(),accountSecureId:b.coerce.string(),status:b.coerce.number().optional().nullable().transform(e=>e??void 0),provider:b.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:q.optional().nullable().transform(e=>e??void 0),duration:b.coerce.number().optional().nullable().transform(e=>e??void 0)}),Ne=J.extend({logType:b.literal(`platform`),eventId:b.coerce.string(),eventType:b.coerce.string(),service:b.coerce.string(),organizationId:b.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:b.undefined(),userId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:b.coerce.string().optional().nullable().transform(e=>e??void 0),action:b.coerce.string().optional().nullable().transform(e=>e??void 0),resource:b.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:b.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:b.coerce.string().optional().nullable().transform(e=>e??void 0),authType:b.coerce.string().optional().nullable().transform(e=>e??void 0),authId:b.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:b.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:b.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:b.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:b.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:b.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:b.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:b.coerce.number().optional().nullable().transform(e=>e??void 0),success:b.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:b.record(b.unknown()).optional().nullable().transform(e=>e??void 0)}),Pe=b.discriminatedUnion(`logType`,[Y,X,Z,Q]),Fe=new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Ie=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a(){return this.#r?.isReady()?this.#r:void 0}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#o()}async#o(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#r;if(!r?.isReady())return this.#i?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#i?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,Y),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,X),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,Z),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,Q),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t?.query({endpoint:`organization_platform_dimensions.json`,params:e});if(!n)return this.#i?.warning({message:`Platform log dimensions were requested but the ClickHouse client is not available`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=Fe.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,Ne),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):(this.#i?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(n){return t?.isReady()?this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async getAggregate(e,t,n){let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n}});let{dimensions:a,startTime:o,endTime:s,...c}=n,l=n.intervalType===F.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>r(e,!0)).map(e=>{let t={...e};for(let e of Ie)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){return i?.isReady()?this.#i?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,maxValues:s,...c}=n,l={organizationId:e,projectSecureId:t,...c,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()},...s&&{maxValuesPerDim:s}},u=await r?.query({endpoint:`project_logs_dimensions.json`,params:l});if(!u)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${u.length} dimension facets`,category:`LogsSink`});let d={};for(let e of u)Ie.includes(e.dimension)?d[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):d[e.dimension]=e.values;return d}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,...o&&{sourceType:Array.isArray(o)?o.join(`,`):o},...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r?.query({endpoint:`project_source_usage.json`,params:s});return c?(this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return r?.isReady()?this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#s(e){return(this.#n??I)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#s(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#c(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#c(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??oe(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof y){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,Pe)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof y?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#i?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return Y;case`step`:return X;case`unified`:return Z;case`provider`:return Q;case`platform`:return Ne}}};const $={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...$.logs,...e?.logs},advanced:{...$.advanced,...e?.advanced},defender:{...$.defender,...e?.defender},policy:{...$.policy,...e?.policy},datasets:{...$.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Policy sink bucket is not configured`);return this.#t}async initialize(){this.#e||this.#r?.warning({message:`No s3 client provided, policy sink will not function`,category:`PolicySink`})}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(!t?.enabled){n.push(null);continue}if(!this.#t){n.push(null);continue}if(s(i.policyContext)){n.push(null);continue}let e=await this.send(this.createPolicyS3(r,i));n.push(e)}return n}async getAction(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from policy sink`,category:`PolicySink`});return}if(this.#t)try{let i=await this.#e.send(new g({Bucket:this.requireBucket(),Key:this.generateS3Key(e,t,n,r)}));if(!i.Body){this.#r?.warning({message:`Received empty body when trying to get policy log from S3 for actionRunId ${r}`,category:`PolicySink`});return}return JSON.parse(await i.Body.transformToString())}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Policy log not found in S3 for actionRunId ${r}`,category:`PolicySink`});return}throw this.#r?.error({message:`Error when getting policy log from S3 for actionRunId ${r}`,error:e,code:`PolicyLogReadError`,category:`PolicySink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to policy sink`);let t=new Date(Date.now()+this.#n*24*60*60*1e3);try{return await this.#e.send(new v({Bucket:this.requireBucket(),Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:t,Tagging:`ttl=${this.#n}d`})),{expiresAt:t}}catch(t){throw this.#r?.error({message:`Failed to write policy log to S3 at ${e.Key}`,error:t,code:`PolicyLogWriteError`,category:`PolicySink`}),t}}generateS3Key(e,t,n,r){return`${e}/${t}/${n}/${r}/policy.json`}createPolicyS3(e,t){return{Key:this.generateS3Key(e.organizationId,e.projectSecureId,e.accountSecureId,e.actionRunId),Body:JSON.stringify(t.policyContext),ContentType:`application/json`}}};const Le=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Le}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Le}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),Re=e(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=Re(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=Re(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new ee(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var ze=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=c,this.#p=l,this.#t=n(s,u),this.#n=u}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}){let d=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});return await d.initialize(),d}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,policy:a,datasets:o}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,policy:a,datasets:o}}});for(let t of e)s(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=a?.enabled&&this.#o?this.#o.sendActions(e,a).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs s3: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=o?.enabled&&this.#s?this.#s.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([r?.enabled&&this.#i?this.#i.sendActions(e,r).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#a?this.#a.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=n?.enabled&&this.#r?this.#r.sendActions(f,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#n?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}}),s(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#i?await this.#i.sendUnified(e,t,i).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#r&&await this.#r.sendUnified(e,t,a,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n){let r=await this.#r?.getAction(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,r){let i=await this.#r?.getStep(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n){let r=await this.#r?.getUnifiedLog(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,t,n,r){let i=await this.#r?.getProviderLog(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getActionAdvancedLog(e,t,n){let r=await this.#i?.getAction(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#i?.getStep(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#i?.getUnified(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#i?.getProvider(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#i?.getPlatform(e,t);if(s(n)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getPolicyLog(e,t,n,r){let i=await this.#o?.getAction(e,t,n,r);if(s(i)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(s(r)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u})=>ze.create({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u,getOlapClient:d=buildOlapClientInstance}){return this.olapClientPromise||=d({getKafkaClient:e,getInternalKafkaClient:t,getS3Client:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,s3ClientConfig:s,clickhouseConfig:c,sinkConfig:l,logger:u}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{Te as AuthType,ClickHouseClient,I as DEFAULT_TOPIC_CLUSTER_MAP,he as Dimension,F as IntervalType,P as LogType,ze as OlapClient,OlapClientManager,pe as OrderBy,me as OrderDirection,ge as PlatformDimension,PolicySink,U as SourceType,we as StreamType,Ce as TransportType,createConfigFromEnv,createOlapQueryClient,getPolicySink,hasErrorEntries};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/olap",
3
- "version": "1.75.0",
3
+ "version": "1.76.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",