@stackone/olap 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -10,17 +10,27 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
10
10
  SELECT count() as total
11
11
  FROM ${C}(${T})
12
12
  ${E}
13
- `,params:buildViewParams(e)}),pe={id:`project_action_logs`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery},me={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},untypedFilter=(e,t)=>e[t];function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),policyResult:toArray(untypedFilter(e,`policyResult`)),status:toStatusCodes(untypedFilter(e,`status`))}}const he=[...`organizationId.projectSecureId.accountSecureId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.sourceType.sourceId.sourceValue.authType.authId.mode.httpMethod.originOwnerId.originOwnerName.logId.requestId.resource.service.subResource.childResource.action.actionRunId.actionId.actionType.category.path.accountId.riskLevel.policyResult.logType`.split(`.`).map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`status = {status:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),ge=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
13
+ `,params:buildViewParams(e)}),pe={id:`project_action_logs`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery},me=[`synced_field_listing`,`test_actions`];function buildActionsCountQuery(e){return{sql:`
14
+ SELECT count() AS actions_count
15
+ FROM actions FINAL
16
+ WHERE ({organizationId:Nullable(String)} IS NULL OR organizationId = {organizationId:Nullable(String)})
17
+ AND eventTime >= {startTime:DateTime64(3)}
18
+ AND eventTime < {endTime:DateTime64(3)}
19
+ AND success = 1
20
+ AND isBackground = 0
21
+ AND ifNull(sourceType, '') != {dataSyncV2:String}
22
+ AND ifNull(mode, '') NOT IN {nonBillableModes:Array(String)}
23
+ `,params:{organizationId:e.organizationId??null,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),dataSyncV2:_.DataSyncV2,nonBillableModes:me}}}const he={id:`actions_count`,buildQuery:buildActionsCountQuery},ge={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},untypedFilter=(e,t)=>e[t];function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),policyResult:toArray(untypedFilter(e,`policyResult`)),status:toStatusCodes(untypedFilter(e,`status`))}}const _e=[...`organizationId.projectSecureId.accountSecureId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.sourceType.sourceId.sourceValue.authType.authId.mode.httpMethod.originOwnerId.originOwnerName.logId.requestId.resource.service.subResource.childResource.action.actionRunId.actionId.actionType.category.path.accountId.riskLevel.policyResult.logType`.split(`.`).map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`status = {status:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),ve=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
14
24
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`,buildLogsViewSource=()=>`SELECT *
15
- FROM logs_filtered(${he})
16
- ${ge}`,buildLogsViewParams=e=>({...buildCommonLogParams(e),logType:toArray(e.logType)});function buildLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,me,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
25
+ FROM logs_filtered(${_e})
26
+ ${ve}`,buildLogsViewParams=e=>({...buildCommonLogParams(e),logType:toArray(e.logType)});function buildLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,ge,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
17
27
  ${buildLogsViewSource()}
18
28
  ORDER BY ${r} ${i}
19
29
  LIMIT {limit:UInt32}
20
30
  OFFSET {offset:UInt32}
21
31
  `,params:{...buildLogsViewParams(e),limit:t,offset:n}}}function buildLogsCountQuery(e){return{sql:`
22
32
  SELECT count() as total FROM (${buildLogsViewSource()})
23
- `,params:buildLogsViewParams(e)}}const _e={id:`project_logs`,buildQuery:buildLogsQuery,buildCountQuery:buildLogsCountQuery},D={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`},O={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},k={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(O,e)?O[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(k,e)?k[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(D,e)).map(e=>D[e]),s=r===m.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:`
33
+ `,params:buildLogsViewParams(e)}}const ye={id:`project_logs`,buildQuery:buildLogsQuery,buildCountQuery:buildLogsCountQuery},D={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`},O={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},k={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(O,e)?O[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(k,e)?k[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(D,e)).map(e=>D[e]),s=r===m.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:`
24
34
  WITH logs AS (
25
35
  ${buildLogsViewSource()}
26
36
  )
@@ -29,7 +39,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
29
39
  FROM logs
30
40
  ${u}
31
41
  ${d}
32
- `,params:buildLogsViewParams(e)}}const ve={id:`project_logs_aggregation`,buildQuery:buildAggregationQuery},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=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`,`authType`,`authId`,`policyResult`,`riskLevel`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(n.snakeToCamel),r=e.maxValues??100,i=t.filter(e=>Object.prototype.hasOwnProperty.call(A,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildLogsViewSource();return{sql:i.map(e=>{let t=A[e];return`
42
+ `,params:buildLogsViewParams(e)}}const be={id:`project_logs_aggregation`,buildQuery:buildAggregationQuery},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=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`,`authType`,`authId`,`policyResult`,`riskLevel`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(n.snakeToCamel),r=e.maxValues??100,i=t.filter(e=>Object.prototype.hasOwnProperty.call(A,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildLogsViewSource();return{sql:i.map(e=>{let t=A[e];return`
33
43
  SELECT
34
44
  '${e}' as dimension,
35
45
  arrayReverseSort(
@@ -51,7 +61,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
51
61
  ) AS facets
52
62
  `}).join(`
53
63
  UNION ALL
54
- `),params:{...buildLogsViewParams(e),maxValues:r}}}const ye={id:`project_logs_dimensions`,buildQuery:buildDimensionsQuery},narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=e[t],i=r.length===0?n:n.filter(e=>r.includes(e));return i.length===0?{}:{[t]:i}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!j.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
64
+ `),params:{...buildLogsViewParams(e),maxValues:r}}}const xe={id:`project_logs_dimensions`,buildQuery:buildDimensionsQuery},narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=e[t],i=r.length===0?n:n.filter(e=>r.includes(e));return i.length===0?{}:{[t]:i}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!j.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
55
65
  WITH logs AS (
56
66
  ${buildLogsViewSource()}
57
67
  )
@@ -59,10 +69,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
59
69
  WHERE ${t} IN {entityIds:Array(String)}
60
70
  ORDER BY eventTime DESC
61
71
  LIMIT 1 BY ${t}
62
- `,r=toArray(e.entities?.ids),i=buildLogsViewParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}},be={id:`project_last_logs`,buildQuery:buildLastLogsQuery},xe=[...[`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(`, `),M={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`},Se=new Set([`statusCode`,`success`,`isRead`]),Ce=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
72
+ `,r=toArray(e.entities?.ids),i=buildLogsViewParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}},Se={id:`project_last_logs`,buildQuery:buildLastLogsQuery},Ce=[...[`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(`, `),M={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`},we=new Set([`statusCode`,`success`,`isRead`]),Te=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
63
73
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`,buildPlatformViewSource=()=>`SELECT *
64
- FROM platform_filtered(${xe})
65
- ${Ce}`,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(M,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildPlatformViewSource();return{sql:i.map(e=>{let t=M[e];return`
74
+ FROM platform_filtered(${Ce})
75
+ ${Te}`,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(M,e));if(i.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let a=buildPlatformViewSource();return{sql:i.map(e=>{let t=M[e];return`
66
76
  SELECT
67
77
  '${e}' as dimension,
68
78
  arrayReverseSort(
@@ -77,14 +87,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
77
87
  ${a}
78
88
  ) AS platformLogs
79
89
  WHERE ${t} IS NOT NULL
80
- ${Se.has(e)?``:`AND ${t} != ''`}
90
+ ${we.has(e)?``:`AND ${t} != ''`}
81
91
  GROUP BY ${t}
82
92
  ORDER BY count DESC
83
93
  LIMIT {maxValues:UInt32}
84
94
  ) AS facets
85
95
  `}).join(`
86
96
  UNION ALL
87
- `),params:{...buildPlatformViewParams(e),maxValues:r}}}const we={id:`organization_platform_dimensions`,buildQuery:buildPlatformDimensionsQuery},Te={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
97
+ `),params:{...buildPlatformViewParams(e),maxValues:r}}}const Ee={id:`organization_platform_dimensions`,buildQuery:buildPlatformDimensionsQuery},De={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
88
98
  SELECT
89
99
  eventTime,
90
100
  startTime,
@@ -142,7 +152,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
142
152
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
143
153
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
144
154
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
145
- ORDER BY ${sanitizeOrderBy(e.orderBy,Te,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
155
+ ORDER BY ${sanitizeOrderBy(e.orderBy,De,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
146
156
  LIMIT {limit:UInt32}
147
157
  OFFSET {offset:UInt32}
148
158
  `,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:`
@@ -174,19 +184,19 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
174
184
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
175
185
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
176
186
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
177
- `,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)}}}const Ee={id:`organization_platform_logs`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery},De={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`)}
187
+ `,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)}}}const Oe={id:`organization_platform_logs`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery},ke={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`)}
178
188
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
179
189
  SELECT *
180
190
  FROM ${N}(${P})
181
191
  ${F}
182
- ORDER BY ${sanitizeOrderBy(e.orderBy,De,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
192
+ ORDER BY ${sanitizeOrderBy(e.orderBy,ke,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
183
193
  LIMIT {limit:UInt32}
184
194
  OFFSET {offset:UInt32}
185
195
  `,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:`
186
196
  SELECT count() as total
187
197
  FROM ${N}(${P})
188
198
  ${F}
189
- `,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)}}}const Oe={id:`project_provider_logs`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery};function buildSourceUsageQuery(e){return{sql:`
199
+ `,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)}}}const Ae={id:`project_provider_logs`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery};function buildSourceUsageQuery(e){return{sql:`
190
200
  SELECT
191
201
  sourceId,
192
202
  sourceType,
@@ -203,28 +213,28 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
203
213
  AND sourceId != ''
204
214
  GROUP BY sourceId, sourceType
205
215
  ORDER BY request_count DESC
206
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const ke={id:`project_source_usage`,buildQuery:buildSourceUsageQuery},Ae={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},I=`step_logs_filtered`,L=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`actionRunId = {actionRunId:Array(String)}`,`stepId = {stepId:Array(String)}`,`stepIndex = {stepIndex:Array(Int32)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),R=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
216
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const je={id:`project_source_usage`,buildQuery:buildSourceUsageQuery},Me={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},I=`step_logs_filtered`,L=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`actionRunId = {actionRunId:Array(String)}`,`stepId = {stepId:Array(String)}`,`stepIndex = {stepIndex:Array(Int32)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),R=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
207
217
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
208
218
  SELECT *
209
219
  FROM ${I}(${L})
210
220
  ${R}
211
- ORDER BY ${sanitizeOrderBy(e.orderBy,Ae,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
221
+ ORDER BY ${sanitizeOrderBy(e.orderBy,Me,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
212
222
  LIMIT {limit:UInt32}
213
223
  OFFSET {offset:UInt32}
214
224
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildStepLogsCountQuery(e){return{sql:`
215
225
  SELECT count() as total
216
226
  FROM ${I}(${L})
217
227
  ${R}
218
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const je={id:`project_step_logs`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery},Me={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},z=`unified_logs_filtered`,B=`organizationId = {organizationId:Array(String)}.projectSecureId = {projectSecureId:Array(String)}.accountSecureId = {accountSecureId:Array(String)}.requestId = {requestId:Array(String)}.connectorKey = {connectorKey:Array(String)}.connectorVersion = {connectorVersion:Array(String)}.connectorOwner = {connectorOwner:Array(String)}.connectorProfileId = {connectorProfileId:Array(String)}.mode = {mode:Array(String)}.httpMethod = {httpMethod:Array(String)}.resource = {resource:Array(String)}.subResource = {subResource:Array(String)}.childResource = {childResource:Array(String)}.service = {service:Array(String)}.action = {action:Array(String)}.sourceType = {sourceType:Array(String)}.sourceId = {sourceId:Array(String)}.sourceValue = {sourceValue:Array(String)}.authType = {authType:Array(String)}.authId = {authId:Array(String)}.userAgent = {userAgent:Array(String)}.ipAddress = {ipAddress:Array(String)}.sessionId = {sessionId:Array(String)}.agentId = {agentId:Array(String)}.transportType = {transportType:Array(String)}.streamType = {streamType:Array(String)}.originOwnerId = {originOwnerId:Array(String)}.originOwnerName = {originOwnerName:Array(String)}.statusCode = {statusCode:Array(Int16)}.isBackground = {isBackground:Nullable(UInt8)}.success = {success:Nullable(UInt8)}.startTime = {startTime:Nullable(DateTime64(3))}.endTime = {endTime:Nullable(DateTime64(3))}`.split(`.`).join(`, `),V=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
228
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Ne={id:`project_step_logs`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery},Pe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},z=`unified_logs_filtered`,B=`organizationId = {organizationId:Array(String)}.projectSecureId = {projectSecureId:Array(String)}.accountSecureId = {accountSecureId:Array(String)}.requestId = {requestId:Array(String)}.connectorKey = {connectorKey:Array(String)}.connectorVersion = {connectorVersion:Array(String)}.connectorOwner = {connectorOwner:Array(String)}.connectorProfileId = {connectorProfileId:Array(String)}.mode = {mode:Array(String)}.httpMethod = {httpMethod:Array(String)}.resource = {resource:Array(String)}.subResource = {subResource:Array(String)}.childResource = {childResource:Array(String)}.service = {service:Array(String)}.action = {action:Array(String)}.sourceType = {sourceType:Array(String)}.sourceId = {sourceId:Array(String)}.sourceValue = {sourceValue:Array(String)}.authType = {authType:Array(String)}.authId = {authId:Array(String)}.userAgent = {userAgent:Array(String)}.ipAddress = {ipAddress:Array(String)}.sessionId = {sessionId:Array(String)}.agentId = {agentId:Array(String)}.transportType = {transportType:Array(String)}.streamType = {streamType:Array(String)}.originOwnerId = {originOwnerId:Array(String)}.originOwnerName = {originOwnerName:Array(String)}.statusCode = {statusCode:Array(Int16)}.isBackground = {isBackground:Nullable(UInt8)}.success = {success:Nullable(UInt8)}.startTime = {startTime:Nullable(DateTime64(3))}.endTime = {endTime:Nullable(DateTime64(3))}`.split(`.`).join(`, `),V=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
219
229
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
220
230
  SELECT *
221
231
  FROM ${z}(${B})
222
232
  ${V}
223
- ORDER BY ${sanitizeOrderBy(e.orderBy,Me,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
233
+ ORDER BY ${sanitizeOrderBy(e.orderBy,Pe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
224
234
  LIMIT {limit:UInt32}
225
235
  OFFSET {offset:UInt32}
226
236
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),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),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildUnifiedLogsCountQuery(e){return{sql:`
227
237
  SELECT count() as total
228
238
  FROM ${z}(${B})
229
239
  ${V}
230
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),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),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Ne={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=(0,u.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){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}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){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};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=l.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 l.z.ZodError([{code:l.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},l.z.coerce.date()),U=l.z.object({logType:l.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:l.z.coerce.string(),projectSecureId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:l.z.literal(`action`),actionRunId:l.z.coerce.string(),actionId:l.z.coerce.string(),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string(),connectorOwner:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),actionType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:l.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:l.z.literal(`step`),actionRunId:l.z.coerce.string(),stepIndex:l.z.coerce.number(),stepId:l.z.coerce.string(),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),skipped:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:l.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:l.z.literal(`unified`),requestId:l.z.coerce.string(),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:l.z.literal(`provider`),requestId:l.z.coerce.string(),id:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string(),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string(),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string(),path:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),status:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:l.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),J=U.extend({logType:l.z.literal(`platform`),eventId:l.z.coerce.string(),eventType:l.z.coerce.string(),service:l.z.coerce.string(),organizationId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:l.z.undefined(),userId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:l.z.record(l.z.unknown()).optional().nullable().transform(e=>e??void 0)}),Pe=l.z.discriminatedUnion(`logType`,[W,G,K,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()]},Y=[`success`,`isWorker`,`isBackground`,`skipped`],X=15e3;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.#l()}async close(e=3e4){return this.#o??=this.#s(e),this.#o}#o;async#s(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#c(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#c(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#l(){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})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`connectivity probe timed out after ${X}ms`)),X),n.unref?.()})]),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}})}finally{n&&clearTimeout(n)}}))}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({query:_e,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({query:be,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({query:pe,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({query:je,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({query:Ne,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({query:Oe,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({query:we,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({query:Ee,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===m.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({query:ve,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,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r?.query({query:ye,params:c});if(!l)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)Y.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}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,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r?.query({query:ke,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}),[]}}#u(e){return(this.#n??g)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#u(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.#d(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#d(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,c.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 l.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,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 l.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 Z={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:{...Z.logs,...e?.logs},advanced:{...Z.advanced,...e?.advanced},defender:{...Z.defender,...e?.defender},policy:{...Z.policy,...e?.policy},datasets:{...Z.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const Q=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, policy sink will not function`,category:Q});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(!t?.enabled){r.push(null);continue}if(!this.#e&&!this.#t){r.push(null);continue}if((0,n.isMissing)(a.policyContext)){r.push(null);continue}if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);r.push(await this.send(this.#e,i,a))}return r}async getAction(e,t,n,r){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:Q});return}if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:Q,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:Q,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,Ie=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Ie}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Ie}${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`),Le=__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=Le(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=Le(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})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),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`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;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}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket?(0,t.createStorage)((0,t.storageConfigFromEnv)()):void 0;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,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}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 close(e){await this.#r?.close?.(e)}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 storage: ${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 storage: ${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 storage: ${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 storage: ${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 storage: ${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 storage: ${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 storage: ${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,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};exports.AuthType=re,exports.DEFAULT_TOPIC_CLUSTER_MAP=g,exports.Dimension=h,exports.IntervalType=m,exports.LogType=d,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=f,exports.OrderDirection=p,exports.PlatformDimension=ee,exports.PolicySink=PolicySink,exports.SourceType=_,exports.StreamType=ne,exports.TransportType=te,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries;
240
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),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),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Fe={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=(0,u.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){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}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){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};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=l.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 l.z.ZodError([{code:l.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},l.z.coerce.date()),U=l.z.object({logType:l.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:l.z.coerce.string(),projectSecureId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:l.z.literal(`action`),actionRunId:l.z.coerce.string(),actionId:l.z.coerce.string(),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string(),connectorOwner:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),actionType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:l.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:l.z.literal(`step`),actionRunId:l.z.coerce.string(),stepIndex:l.z.coerce.number(),stepId:l.z.coerce.string(),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),skipped:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:l.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:l.z.literal(`unified`),requestId:l.z.coerce.string(),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:l.z.literal(`provider`),requestId:l.z.coerce.string(),id:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string(),mode:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:l.z.coerce.string(),originOwnerId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:l.z.coerce.string(),path:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:l.z.coerce.string(),connectorVersion:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:l.z.coerce.string(),accountSecureId:l.z.coerce.string(),status:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:l.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),J=U.extend({logType:l.z.literal(`platform`),eventId:l.z.coerce.string(),eventType:l.z.coerce.string(),service:l.z.coerce.string(),organizationId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:l.z.undefined(),userId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:l.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:l.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:l.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:l.z.record(l.z.unknown()).optional().nullable().transform(e=>e??void 0)}),Ie=l.z.discriminatedUnion(`logType`,[W,G,K,q]),Le=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`],X=15e3;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.#l()}async close(e=3e4){return this.#o??=this.#s(e),this.#o}#o;async#s(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#c(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#c(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#l(){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})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`connectivity probe timed out after ${X}ms`)),X),n.unref?.()})]),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}})}finally{n&&clearTimeout(n)}}))}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({query:ye,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({query:Se,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({query:pe,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({query:Ne,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({query:Fe,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({query:Ae,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({query:Ee,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]=Le.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({query:Oe,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===m.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({query:be,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,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r?.query({query:xe,params:c});if(!l)return this.#i?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)Y.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}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 getActionsCount(e){let t=this.#a();if(!t)throw Error(`Cannot count actions: no ClickHouse query client is configured and ready`);let[n]=await t.query({query:he,params:e});return Number(n?.actions_count??0)}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,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r?.query({query:je,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}),[]}}#u(e){return(this.#n??g)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#u(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.#d(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#d(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,c.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 l.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,Ie)}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 l.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 Z={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:{...Z.logs,...e?.logs},advanced:{...Z.advanced,...e?.advanced},defender:{...Z.defender,...e?.defender},policy:{...Z.policy,...e?.policy},datasets:{...Z.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const Q=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, policy sink will not function`,category:Q});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(!t?.enabled){r.push(null);continue}if(!this.#e&&!this.#t){r.push(null);continue}if((0,n.isMissing)(a.policyContext)){r.push(null);continue}if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);r.push(await this.send(this.#e,i,a))}return r}async getAction(e,t,n,r){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:Q});return}if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:Q,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:Q,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,$=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${$}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${$}${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=__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=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})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),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`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;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}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket?(0,t.createStorage)((0,t.storageConfigFromEnv)()):void 0;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,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}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 close(e){await this.#r?.close?.(e)}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 storage: ${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 storage: ${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 storage: ${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 storage: ${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 storage: ${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 storage: ${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 storage: ${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)??[]}async getActionsCount(e){if(!this.#r)throw Error(`Cannot count actions: the logs sink is not configured`);return this.#r.getActionsCount(e)}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>ze.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};exports.AuthType=re,exports.DEFAULT_TOPIC_CLUSTER_MAP=g,exports.Dimension=h,exports.IntervalType=m,exports.LogType=d,exports.OlapClient=ze,exports.OlapClientManager=OlapClientManager,exports.OrderBy=f,exports.OrderDirection=p,exports.PlatformDimension=ee,exports.PolicySink=PolicySink,exports.SourceType=_,exports.StreamType=ne,exports.TransportType=te,exports.getPolicySink=getPolicySink,exports.hasErrorEntries=hasErrorEntries;
package/dist/index.d.cts CHANGED
@@ -212,6 +212,7 @@ interface IOlapClient {
212
212
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery): Promise<AggregateResult>;
213
213
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery): Promise<DimensionsResult>;
214
214
  getSourceUsage(organizationId: string, projectSecureId: string, query: SourceQuery): Promise<SourceResult>;
215
+ getActionsCount(query: ActionsCountQuery): Promise<number>;
215
216
  close?(timeoutMs?: number): Promise<void>;
216
217
  }
217
218
  type PolicyResult = 'skipped' | 'allowed' | 'partial' | 'monitored' | 'denied' | 'error';
@@ -793,6 +794,11 @@ type PlatformDimensionsQuery = Partial<PlatformQuery> & {
793
794
  maxValues?: number;
794
795
  };
795
796
  type SourceQuery = Partial<Query>;
797
+ type ActionsCountQuery = {
798
+ organizationId?: string;
799
+ startTime: Date;
800
+ endTime: Date;
801
+ };
796
802
  type SourceResult = Array<{
797
803
  sourceId: string;
798
804
  sourceType: string;
@@ -1090,6 +1096,7 @@ declare class OlapClient implements IOlapClient {
1090
1096
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery): Promise<AggregateResult>;
1091
1097
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery): Promise<DimensionsResult>;
1092
1098
  getSourceUsage(organizationId: string, projectSecureId: string, query: SourceQuery): Promise<SourceResult>;
1099
+ getActionsCount(query: ActionsCountQuery): Promise<number>;
1093
1100
  }
1094
1101
  //#endregion
1095
1102
  //#region src/olap/olapClientManager.d.ts
@@ -1171,4 +1178,4 @@ declare class PolicySink implements IPolicySink {
1171
1178
  //#region src/utils/stepErrors.d.ts
1172
1179
  declare const hasErrorEntries: (errors: unknown) => boolean;
1173
1180
  //#endregion
1174
- 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, 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 FieldLabelProvenance, type ILog, type IOlapClient, type IPolicySink, 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 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 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, getPolicySink, hasErrorEntries };
1181
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsCountQuery, type ActionsQuery, type ActionsQueryResult, type AdvancedLogMetadata, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, 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 FieldLabelProvenance, type ILog, type IOlapClient, type IPolicySink, 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 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 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, getPolicySink, hasErrorEntries };
package/dist/index.d.mts CHANGED
@@ -211,6 +211,7 @@ interface IOlapClient {
211
211
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery): Promise<AggregateResult>;
212
212
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery): Promise<DimensionsResult>;
213
213
  getSourceUsage(organizationId: string, projectSecureId: string, query: SourceQuery): Promise<SourceResult>;
214
+ getActionsCount(query: ActionsCountQuery): Promise<number>;
214
215
  close?(timeoutMs?: number): Promise<void>;
215
216
  }
216
217
  type PolicyResult = 'skipped' | 'allowed' | 'partial' | 'monitored' | 'denied' | 'error';
@@ -792,6 +793,11 @@ type PlatformDimensionsQuery = Partial<PlatformQuery> & {
792
793
  maxValues?: number;
793
794
  };
794
795
  type SourceQuery = Partial<Query>;
796
+ type ActionsCountQuery = {
797
+ organizationId?: string;
798
+ startTime: Date;
799
+ endTime: Date;
800
+ };
795
801
  type SourceResult = Array<{
796
802
  sourceId: string;
797
803
  sourceType: string;
@@ -1089,6 +1095,7 @@ declare class OlapClient implements IOlapClient {
1089
1095
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery): Promise<AggregateResult>;
1090
1096
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery): Promise<DimensionsResult>;
1091
1097
  getSourceUsage(organizationId: string, projectSecureId: string, query: SourceQuery): Promise<SourceResult>;
1098
+ getActionsCount(query: ActionsCountQuery): Promise<number>;
1092
1099
  }
1093
1100
  //#endregion
1094
1101
  //#region src/olap/olapClientManager.d.ts
@@ -1170,4 +1177,4 @@ declare class PolicySink implements IPolicySink {
1170
1177
  //#region src/utils/stepErrors.d.ts
1171
1178
  declare const hasErrorEntries: (errors: unknown) => boolean;
1172
1179
  //#endregion
1173
- 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, 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 FieldLabelProvenance, type ILog, type IOlapClient, type IPolicySink, 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 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 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, getPolicySink, hasErrorEntries };
1180
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsCountQuery, type ActionsQuery, type ActionsQueryResult, type AdvancedLogMetadata, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, 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 FieldLabelProvenance, type ILog, type IOlapClient, type IPolicySink, 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 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 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, getPolicySink, hasErrorEntries };