@stackone/olap 1.67.0 → 1.69.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
@@ -1,7 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@clickhouse/client"),s=require("@stackone/utils"),c=require("node:http");c=__toESM(c);let l=require("@stackone/redaction"),u=require("@aws-sdk/client-s3"),d=require("@opentelemetry/exporter-trace-otlp-proto"),f=require("@opentelemetry/resources"),p=require("@opentelemetry/sdk-trace-base"),m=require("@opentelemetry/semantic-conventions"),h=require("crypto"),g=require("zod"),_=require("@stackone/transport");const v=new Map;function registerQuery(e){v.set(e.id,e)}function getQueryDefinition(e){return v.get(e)}function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}function buildDateRangeFilter(e,t,n){return`
2
- ({${t}:Nullable(DateTime64(3))} IS NULL OR ${e} >= {${t}:Nullable(DateTime64(3))})
3
- AND ({${n}:Nullable(DateTime64(3))} IS NULL OR ${e} <= {${n}:Nullable(DateTime64(3))})
4
- `.trim()}function buildBooleanFilter(e,t){return`({${t}:Nullable(UInt8)} IS NULL OR ${e} = {${t}:Nullable(UInt8)})`}const y={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildActionLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@clickhouse/client"),s=require("@stackone/utils"),c=require("node:http");c=__toESM(c);let l=require("@stackone/redaction"),u=require("@aws-sdk/client-s3"),d=require("@opentelemetry/exporter-trace-otlp-proto"),f=require("@opentelemetry/resources"),p=require("@opentelemetry/sdk-trace-base"),m=require("@opentelemetry/semantic-conventions"),h=require("crypto"),g=require("zod"),_=require("@stackone/transport");const v=new Map;function registerQuery(e){v.set(e.id,e)}function getQueryDefinition(e){return v.get(e)}function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toStatusCodes(e){let t=toArray(e);if(t.length===0)return[];let n=t.map(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length===0?NaN:Number(t)}).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return n.length>0?n:[-1]}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}const ee={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildActionLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
5
2
  SELECT
6
3
  eventTime,
7
4
  startTime,
@@ -76,7 +73,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
76
73
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
77
74
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
78
75
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
79
- ORDER BY ${sanitizeOrderBy(e.orderBy,y,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
76
+ ORDER BY ${sanitizeOrderBy(e.orderBy,ee,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
80
77
  LIMIT {limit:UInt32}
81
78
  OFFSET {offset:UInt32}
82
79
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),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),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),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 buildActionLogsCountQuery(e){return{sql:`
@@ -114,7 +111,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
114
111
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
115
112
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
116
113
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
117
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),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),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_action_logs.json`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery});const ee={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
114
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),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),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_action_logs.json`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery});const y={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
118
115
  SELECT
119
116
  eventTime,
120
117
  startTime,
@@ -145,7 +142,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
145
142
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
146
143
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
147
144
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
148
- ORDER BY ${sanitizeOrderBy(e.orderBy,ee,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
145
+ ORDER BY ${sanitizeOrderBy(e.orderBy,y,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
149
146
  LIMIT {limit:UInt32}
150
147
  OFFSET {offset:UInt32}
151
148
  `,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:`
@@ -161,7 +158,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
161
158
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
162
159
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
163
160
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
164
- `,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)}}}registerQuery({id:`project_step_logs.json`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery});const te={startTime:`startTime`,endTime:`endTime`,eventTime:`eventDatetime`,durationMs:`duration`};function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
161
+ `,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)}}}registerQuery({id:`project_step_logs.json`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery});const b={startTime:`startTime`,endTime:`endTime`,eventTime:`eventDatetime`,durationMs:`duration`};function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
165
162
  SELECT
166
163
  eventDatetime as eventTime,
167
164
  startTime,
@@ -239,7 +236,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
239
236
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
240
237
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
241
238
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
242
- ORDER BY ${sanitizeOrderBy(e.orderBy,te,`eventDatetime`)} ${sanitizeOrderDirection(e.orderDirection)}
239
+ ORDER BY ${sanitizeOrderBy(e.orderBy,b,`eventDatetime`)} ${sanitizeOrderDirection(e.orderDirection)}
243
240
  LIMIT {limit:UInt32}
244
241
  OFFSET {offset:UInt32}
245
242
  `,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:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),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:`
@@ -279,7 +276,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
279
276
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
280
277
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
281
278
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
282
- `,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:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_unified_logs.json`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery});const ne={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},b=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],re=[`service`,`action`],x=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`],S=[`eventId`,`eventType`,`userId`,`subAction`],C=[...b.filter(e=>!re.includes(e)),...x,`connectorKey`,`connectorVersion`,`connectorOwner`,`connectorProfileId`,`provider`,`mode`,`httpMethod`,`statusCode`,`sourceValue`,`originOwnerId`,`originOwnerName`,`isBackground`,`isWorker`],hasAnyFilter=(e,t)=>{let n=e;return t.some(e=>n[e]!==void 0)},untypedFilter=(e,t)=>e[t],toInt16Filter=e=>{let t=toArray(e),n=t.map(e=>typeof e==`string`&&e.trim()===``?NaN:Number(e)).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return{values:n,unsatisfiable:t.length>0&&n.length===0}},hasUnsatisfiableFilter=e=>toInt16Filter(e.statusCode).unsatisfiable||toInt16Filter(untypedFilter(e,`status`)).unsatisfiable;function shouldIncludeUnified(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`unified`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,[...x,...S])}function shouldIncludeActions(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`action`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,[...b,...S])}function shouldIncludePlatform(e){return!toArray(e.logType).includes(`platform`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,C)}function buildUnifiedFilters(){return`
279
+ `,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:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_unified_logs.json`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery});const te={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},ne=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],re=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`],hasAnyFilter=(e,t)=>{let n=e;return t.some(e=>n[e]!==void 0)},untypedFilter=(e,t)=>e[t],toInt16Filter=e=>{let t=toArray(e),n=t.map(e=>typeof e==`string`&&e.trim()===``?NaN:Number(e)).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return{values:n,unsatisfiable:t.length>0&&n.length===0}},hasUnsatisfiableFilter=e=>toInt16Filter(e.statusCode).unsatisfiable||toInt16Filter(untypedFilter(e,`status`)).unsatisfiable;function shouldIncludeUnified(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`unified`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,re)}function shouldIncludeActions(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`action`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,ne)}function buildUnifiedFilters(){return`
283
280
  AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
284
281
  AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
285
282
  AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
@@ -331,13 +328,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
331
328
  AND ${buildArrayFilter(`actionType`,`actionType`)}
332
329
  AND ${buildArrayFilter(`category`,`category`)}
333
330
  AND ${buildArrayFilter(`riskLevel`,`riskLevel`)}
334
- `.trim()}function buildPlatformFilters(){return[...[`organizationId`,`projectSecureId`,`accountSecureId`,`sourceType`,`sourceId`,`service`,`action`,`authType`,`authId`,`userAgent`,`ipAddress`,`sessionId`,`agentId`,`transportType`,`streamType`,`eventId`,`eventType`,`userId`,`subAction`].map(e=>`AND ${buildArrayFilter(e,e)}`),`AND ${buildArrayFilter(`eventId`,`logId`)}`,`AND ${buildBooleanFilter(`success`,`success`)}`].join(`
335
- `)}const w=`
336
- CAST(NULL AS Nullable(String)) as eventId,
337
- CAST(NULL AS Nullable(String)) as eventType,
338
- CAST(NULL AS Nullable(String)) as userId,
339
- CAST(NULL AS Nullable(String)) as subAction,
340
- CAST(NULL AS Nullable(String)) as details`;function buildUnifiedSelect(){return`
331
+ `.trim()}function buildUnifiedSelect(){return`
341
332
  SELECT
342
333
  eventDatetime as eventTime,
343
334
  startTime,
@@ -390,7 +381,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
390
381
  statusCode,
391
382
  CAST(NULL AS Nullable(String)) as message,
392
383
  CAST(NULL AS Nullable(String)) as riskLevel,
393
- CAST(NULL AS Nullable(Float32)) as tier2Score,${w},
384
+ CAST(NULL AS Nullable(Float32)) as tier2Score,
394
385
  'unified' as logType
395
386
  FROM unified_requests
396
387
  WHERE 1=1
@@ -450,78 +441,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
450
441
  statusCode,
451
442
  message,
452
443
  riskLevel,
453
- tier2Score,${w},
444
+ tier2Score,
454
445
  'action' as logType
455
446
  FROM actions
456
447
  WHERE 1=1
457
448
  ${buildActionsFilters()}
458
449
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
459
450
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
460
- `}function buildPlatformSelect(){return`
461
- SELECT
462
- eventTime,
463
- startTime,
464
- endTime,
465
- durationMs,
466
- organizationId,
467
- projectSecureId,
468
- accountSecureId,
469
- CAST(NULL AS Nullable(String)) as connectorKey,
470
- CAST(NULL AS Nullable(String)) as connectorVersion,
471
- CAST(NULL AS Nullable(String)) as connectorOwner,
472
- CAST(NULL AS Nullable(String)) as connectorProfileId,
473
- toLowCardinality(sourceType) as sourceType,
474
- toLowCardinality(sourceId) as sourceId,
475
- toLowCardinality(authType) as authType,
476
- authId,
477
- sessionId,
478
- agentId,
479
- userAgent,
480
- ipAddress,
481
- toLowCardinality(transportType) as transportType,
482
- toLowCardinality(streamType) as streamType,
483
- CAST(NULL AS Nullable(String)) as sourceValue,
484
- CAST(NULL AS Nullable(String)) as originOwnerId,
485
- CAST(NULL AS Nullable(String)) as originOwnerName,
486
- CAST(NULL AS LowCardinality(Nullable(String))) as mode,
487
- CAST(NULL AS LowCardinality(Nullable(String))) as httpMethod,
488
- CAST(NULL AS Nullable(String)) as url,
489
- success,
490
- eventId as logId,
491
- CAST(NULL AS Nullable(DateTime64(3))) as advancedExpiresAt,
492
- CAST(NULL AS Nullable(DateTime64(3))) as defenderExpiresAt,
493
- -- non-common fields
494
- CAST(NULL AS Nullable(String)) as requestId,
495
- CAST(NULL AS Nullable(String)) as path,
496
- CAST(NULL AS Nullable(String)) as resource,
497
- CAST(NULL AS Nullable(String)) as subResource,
498
- CAST(NULL AS Nullable(String)) as childResource,
499
- service,
500
- action,
501
- CAST(NULL AS Nullable(Int16)) as status,
502
- CAST(NULL AS Nullable(String)) as accountId,
503
- CAST(NULL AS Nullable(String)) as provider,
504
- CAST(NULL AS Nullable(UInt8)) as isWorker,
505
- CAST(NULL AS Nullable(UInt8)) as isBackground,
506
- CAST(NULL AS Nullable(String)) as actionRunId,
507
- CAST(NULL AS Nullable(String)) as actionId,
508
- CAST(NULL AS Nullable(String)) as actionType,
509
- CAST(NULL AS Nullable(String)) as category,
510
- CAST(NULL AS Nullable(Int16)) as statusCode,
511
- CAST(NULL AS Nullable(String)) as message,
512
- CAST(NULL AS Nullable(String)) as riskLevel,
513
- CAST(NULL AS Nullable(Float32)) as tier2Score,
514
- eventId,
515
- eventType,
516
- userId,
517
- subAction,
518
- details,
519
- 'platform' as logType
520
- FROM platform
521
- WHERE 1=1
522
- ${buildPlatformFilters()}
523
- AND ${buildDateRangeFilter(`eventTime`,`startTime`,`endTime`)}
524
- `}function buildCombinedSourceSql(e){let t=[shouldIncludeUnified(e)?buildUnifiedSelect():void 0,shouldIncludeActions(e)?buildActionsSelect():void 0,shouldIncludePlatform(e)?buildPlatformSelect():void 0].filter(e=>e!==void 0);return t.length===0?`${buildUnifiedSelect()} AND 1 = 0`:t.join(` UNION ALL `)}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),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toInt16Filter(e.statusCode).values,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),service:toArray(e.service),action:toArray(e.action),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),eventId:toArray(e.eventId),eventType:toArray(e.eventType),userId:toArray(e.userId),subAction:toArray(e.subAction),requestId:toArray(e.requestId),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),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`)),status:toInt16Filter(untypedFilter(e,`status`)).values}}function buildCombinedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,ne,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
451
+ `}function buildCombinedSourceSql(e){let t=[shouldIncludeUnified(e)?buildUnifiedSelect():void 0,shouldIncludeActions(e)?buildActionsSelect():void 0].filter(e=>e!==void 0);return t.length===0?`${buildUnifiedSelect()} AND 1 = 0`:t.join(` UNION ALL `)}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),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toInt16Filter(e.statusCode).values,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`)),status:toInt16Filter(untypedFilter(e,`status`)).values}}function buildCombinedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,te,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
525
452
  WITH combined AS (
526
453
  ${buildCombinedSourceSql(e)}
527
454
  )
@@ -543,13 +470,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
543
470
  ${buildActionsFilters()}
544
471
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
545
472
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
546
- `),shouldIncludePlatform(e)&&t.push(`
547
- SELECT count() as cnt
548
- FROM platform
549
- WHERE 1=1
550
- ${buildPlatformFilters()}
551
- AND ${buildDateRangeFilter(`eventTime`,`startTime`,`endTime`)}
552
- `),{sql:t.length>0?`SELECT sum(cnt) as total FROM (${t.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const T={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`,isBackground:`isBackground`},E=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(s.snakeToCamel),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(T,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=T[e];return`
473
+ `),{sql:t.length>0?`SELECT sum(cnt) as total FROM (${t.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const x={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`,isBackground:`isBackground`},S=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(s.snakeToCamel),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(x,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=x[e];return`
553
474
  SELECT
554
475
  '${e}' as dimension,
555
476
  arrayReverseSort(
@@ -564,14 +485,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
564
485
  ${i}
565
486
  ) AS combined
566
487
  WHERE ${t} IS NOT NULL
567
- ${E.has(e)?`AND ${t} != ''`:``}
488
+ ${S.has(e)?`AND ${t} != ''`:``}
568
489
  GROUP BY ${t}
569
490
  ORDER BY count DESC
570
491
  LIMIT {maxValues:UInt32}
571
492
  ) AS facets
572
493
  `}).join(`
573
494
  UNION ALL
574
- `),params:{...buildCommonLogParams(e),maxValues:n}}}registerQuery({id:`project_logs_dimensions.json`,buildQuery:buildDimensionsQuery});const 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||!E.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
495
+ `),params:{...buildCommonLogParams(e),maxValues:n}}}registerQuery({id:`project_logs_dimensions.json`,buildQuery:buildDimensionsQuery});const 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||!S.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
575
496
  WITH combined AS (
576
497
  ${buildCombinedSourceSql(e)}
577
498
  )
@@ -579,7 +500,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
579
500
  WHERE ${t} IN {entityIds:Array(String)}
580
501
  ORDER BY eventTime DESC
581
502
  LIMIT 1 BY ${t}
582
- `,r=toArray(e.entities?.ids),i=buildCommonLogParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const D={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),O={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},k={Asc:`asc`,Desc:`desc`},A={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},ie={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`,IsBackground:`isBackground`},j={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===D.Platform,M={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`,isBackground:`isBackground`},N={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},P={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(N,e)?N[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(P,e)?P[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(s.snakeToCamel),n=e.intervalType??`hour`,r=Math.floor(Number(e.intervalPeriod??1)),i=Number.isFinite(r)&&r>0?r:1,a=t.filter(e=>Object.prototype.hasOwnProperty.call(M,e)).map(e=>M[e]),o=n===A.None?void 0:buildTimeBucket(n,i),c=[...o?[`${o} as startTime`]:[],`count() as count`,...a].join(`, `),l=[...o?[`startTime`]:[],...a],u=l.length>0?`GROUP BY ${l.join(`, `)}`:``,d=o?`ORDER BY startTime ASC`:``;return{sql:`
503
+ `,r=toArray(e.entities?.ids),i=buildCommonLogParams(e);return{sql:n,params:{...i,...narrowScanFilter(i,t,r),entityIds:r}}};registerQuery({id:`project_last_logs.json`,buildQuery:buildLastLogsQuery});const C={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),ie={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},w={Asc:`asc`,Desc:`desc`},T={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},E={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`,IsBackground:`isBackground`},D={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===C.Platform,O={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,isBackground:`isBackground`},k={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},A={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(k,e)?k[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(A,e)?A[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(s.snakeToCamel),n=e.intervalType??`hour`,r=Math.floor(Number(e.intervalPeriod??1)),i=Number.isFinite(r)&&r>0?r:1,a=t.filter(e=>Object.prototype.hasOwnProperty.call(O,e)).map(e=>O[e]),o=n===T.None?void 0:buildTimeBucket(n,i),c=[...o?[`${o} as startTime`]:[],`count() as count`,...a].join(`, `),l=[...o?[`startTime`]:[],...a],u=l.length>0?`GROUP BY ${l.join(`, `)}`:``,d=o?`ORDER BY startTime ASC`:``;return{sql:`
583
504
  WITH combined AS (
584
505
  ${buildCombinedSourceSql(e)}
585
506
  )
@@ -588,7 +509,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
588
509
  FROM combined
589
510
  ${u}
590
511
  ${d}
591
- `,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const ae={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
512
+ `,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const j={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
592
513
  SELECT
593
514
  eventDatetime as eventTime,
594
515
  startTime,
@@ -628,7 +549,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
628
549
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
629
550
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
630
551
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
631
- ORDER BY ${sanitizeOrderBy(e.orderBy,ae,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
552
+ ORDER BY ${sanitizeOrderBy(e.orderBy,j,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
632
553
  LIMIT {limit:UInt32}
633
554
  OFFSET {offset:UInt32}
634
555
  `,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:`
@@ -643,7 +564,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
643
564
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
644
565
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
645
566
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
646
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const oe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
567
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_provider_logs.json`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery});const M={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
647
568
  SELECT
648
569
  eventTime,
649
570
  startTime,
@@ -651,13 +572,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
651
572
  durationMs,
652
573
  organizationId,
653
574
  projectSecureId,
654
- accountSecureId,
655
575
  eventId,
656
576
  eventType,
657
577
  service,
658
578
  userId,
579
+ userEmail,
659
580
  action,
660
- subAction,
581
+ resource,
582
+ resourceId,
661
583
  sourceType,
662
584
  sourceId,
663
585
  authType,
@@ -668,20 +590,23 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
668
590
  agentId,
669
591
  transportType,
670
592
  streamType,
593
+ isRead,
671
594
  success,
595
+ statusCode,
672
596
  details,
673
597
  'platform' as logType
674
598
  FROM platform
675
599
  WHERE 1=1
676
600
  AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
677
601
  AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
678
- AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
679
602
  AND ({eventId:Array(String)} = [] OR eventId IN {eventId:Array(String)})
680
603
  AND ({eventType:Array(String)} = [] OR eventType IN {eventType:Array(String)})
681
604
  AND ({service:Array(String)} = [] OR service IN {service:Array(String)})
682
605
  AND ({userId:Array(String)} = [] OR userId IN {userId:Array(String)})
606
+ AND ({userEmail:Array(String)} = [] OR userEmail IN {userEmail:Array(String)})
683
607
  AND ({action:Array(String)} = [] OR action IN {action:Array(String)})
684
- AND ({subAction:Array(String)} = [] OR subAction IN {subAction:Array(String)})
608
+ AND ({resource:Array(String)} = [] OR resource IN {resource:Array(String)})
609
+ AND ({resourceId:Array(String)} = [] OR resourceId IN {resourceId:Array(String)})
685
610
  AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
686
611
  AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
687
612
  AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
@@ -692,25 +617,28 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
692
617
  AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
693
618
  AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
694
619
  AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
620
+ AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
621
+ AND ({isRead:Nullable(UInt8)} IS NULL OR isRead = {isRead:Nullable(UInt8)})
695
622
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
696
623
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
697
624
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
698
- ORDER BY ${sanitizeOrderBy(e.orderBy,oe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
625
+ ORDER BY ${sanitizeOrderBy(e.orderBy,M,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
699
626
  LIMIT {limit:UInt32}
700
627
  OFFSET {offset:UInt32}
701
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),action:toArray(e.action),subAction:toArray(e.subAction),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),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:`
628
+ `,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:`
702
629
  SELECT count() as total
703
630
  FROM platform
704
631
  WHERE 1=1
705
632
  AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
706
633
  AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
707
- AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
708
634
  AND ({eventId:Array(String)} = [] OR eventId IN {eventId:Array(String)})
709
635
  AND ({eventType:Array(String)} = [] OR eventType IN {eventType:Array(String)})
710
636
  AND ({service:Array(String)} = [] OR service IN {service:Array(String)})
711
637
  AND ({userId:Array(String)} = [] OR userId IN {userId:Array(String)})
638
+ AND ({userEmail:Array(String)} = [] OR userEmail IN {userEmail:Array(String)})
712
639
  AND ({action:Array(String)} = [] OR action IN {action:Array(String)})
713
- AND ({subAction:Array(String)} = [] OR subAction IN {subAction:Array(String)})
640
+ AND ({resource:Array(String)} = [] OR resource IN {resource:Array(String)})
641
+ AND ({resourceId:Array(String)} = [] OR resourceId IN {resourceId:Array(String)})
714
642
  AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
715
643
  AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
716
644
  AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
@@ -721,10 +649,12 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
721
649
  AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
722
650
  AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
723
651
  AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
652
+ AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
653
+ AND ({isRead:Nullable(UInt8)} IS NULL OR isRead = {isRead:Nullable(UInt8)})
724
654
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
725
655
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
726
656
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
727
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),action:toArray(e.action),subAction:toArray(e.subAction),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),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`organization_platform_logs.json`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery});function buildSourceUsageQuery(e){return{sql:`
657
+ `,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)}}}registerQuery({id:`organization_platform_logs.json`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery});function buildSourceUsageQuery(e){return{sql:`
728
658
  SELECT
729
659
  sourceId,
730
660
  sourceType,
@@ -741,4 +671,4 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
741
671
  AND sourceId != ''
742
672
  GROUP BY sourceId, sourceType
743
673
  ORDER BY request_count DESC
744
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError$1=class extends Error{static{__name(this,`SchemaValidationError`)}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,o.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError$1(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}},SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new c.default.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(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:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};function createOlapQueryClient(e,t,n){switch(e.type){case`clickhouse`:if(!e.clickhouse)throw Error(`ClickHouse config required when type is "clickhouse"`);return new ClickHouseClient(e.clickhouse,n);default:return new TinybirdClient(t,e.tinybird,n)}}function createConfigFromEnv(){let e=process.env.TINYBIRD_BASE_URL,t=process.env.TINYBIRD_TOKEN,n=e&&t?{baseUrl:e,token:t,allowHttp:process.env.TINYBIRD_ALLOW_HTTP===`true`}:void 0,r=process.env.CLICKHOUSE_URL,i=r?{url:r,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0;return{type:n?`tinybird`:i?`clickhouse`:`tinybird`,tinybird:n,clickhouse:i}}const F={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},se={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},ce={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},le={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},ue=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],I=[F.Scheduler,F.DataSync,F.DataSyncV2,F.Internal],L=[`data_sync`],R=[F.DataSync,F.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&ue.includes(e)||t&&I.includes(t))}function isDataSync(e,t){return!!(e&&L.includes(e)||t&&R.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},hasErrorEntries=e=>(0,s.isMissing)(e)?!1:Array.isArray(e)||(0,s.isString)(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,z=64*1024,B=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],V=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>(0,s.isObject)(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return(0,s.isObject)(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:n,total:r}=e.reduce((e,n)=>{if(e.total>t)return e;let r=e.total+(0,s.calculateSize)(n);return r>t?{kept:e.kept,total:r}:{kept:e.kept+1,total:r}},{kept:0,total:0});return r>t?e.slice(0,n):e},fitObject=(e,t)=>{let n=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+(0,s.calculateSize)(t)})).sort((e,t)=>e.size-t.size),{kept:r,remaining:i}=n.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),a=n.filter(e=>!r.includes(e.key)),o=a.length===0?0:Math.floor(i/a.length);return Object.fromEntries(n.map(e=>[e.key,r.includes(e.key)?e.value:fitValue(e.value,o)]))},fitValue=(e,t)=>{let n=(0,s.calculateSize)(e);return n<=t?e:((0,s.isString)(e)||Array.isArray(e)||(0,s.isObject)(e)&&!(0,s.isDate)(e))&&t<=0?marker(n):(0,s.isString)(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):(0,s.isObject)(e)&&!(0,s.isDate)(e)?fitObject(e,t):e},payloadFields=e=>B.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!(0,s.isMissing)(e)).map(e=>({...e,size:(0,s.calculateSize)(e.value)})),byRetentionPriority=e=>[...e.filter(e=>V.includes(e.path)),...e.filter(e=>!V.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*z;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(z,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>B.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),H=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],de=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],fe=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e=this.createActionS3(r,i,t),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r=this.createStepS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new u.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new u.GetObjectCommand({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new u.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new u.GetObjectCommand({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new u.PutObjectCommand({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new u.HeadObjectCommand({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new u.GetObjectCommand({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n){let r=platformKey(e.organizationId,e.eventId),i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,ContentType:`application/json`,Expires:new Date(i*1e3),Body:this.serializePlatformAdvanced(t,i)}}serializePlatformAdvanced(e,t){let n=(0,l.redactFields)(e.data,l.CensorType.PARTIAL,!0),r={...e.metadata,expirationTime:t,sizeBytes:(0,s.calculateSize)(n)};return this.stringifyPlatform({data:n,metadata:r},r)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),u=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),d=this.processContent(o,c,`upload`),f=this.processContent(s,u,`download`),p=e.isBackground??isBackgroundLog(e.mode,e.sourceType),m=e.url,h={};if(e.url)try{m=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(m);h=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let g={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:m,path:e.pathParams,queryParams:h},body:d},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:f},...p?{isBackgroundLog:!0}:{}},metadata:{...p?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),u=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),d=this.processContent(o,c,`upload`),f=this.processContent(s,u,`download`),p=e.isBackground??isBackgroundLog(e.mode,e.sourceType),m=`/`,h=e.url,g={};if(e.url)try{h=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(h);m=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let _={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:h,path:m,queryParams:g},body:d},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:f}},metadata:{...p?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),u=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),d=this.processContent(o,c,`upload`),f=this.processContent(s,u,`download`),p,m=``,h=`/`,g={};if(e.url)try{p=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(p);m=t.hostname,h=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let _={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:p,hostname:m,path:h,queryParams:g},body:d},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:f}},metadata:{expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeAndLimit(e,t,n,r){let i=(0,s.calculateSize)(e);if(r===`complete`)return this.stringifyLog(e,{sizeBytes:i});let a=n&&r===`truncate`?t*this.#r:t;if(i<=a)return this.stringifyLog(e,{sizeBytes:i});if(r===`drop`)return this.#i?.warning({message:`Advanced log of ${i} bytes exceeds ${a}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:i,maxSizeBytes:a,isErrorResult:n}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:i,maxSizeBytes:a,truncated:!0});let{data:o,truncatedPaths:c}=truncateToLimit(e,a);return this.#i?.warning({message:`Advanced log of ${i} bytes exceeds ${a}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:i,maxSizeBytes:a,isErrorResult:n,truncatedPaths:c}}),this.stringifyLog(o,{sizeBytes:i,maxSizeBytes:a,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=H.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return de.includes(i)||fe.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,s.isMissing)(e)){if(!(0,s.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new d.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[m.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new p.BasicTracerProvider({resource:(0,f.resourceFromAttributes)(n),spanProcessors:[new p.BatchSpanProcessor(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,includeBackground:t.includeBackground}}),(0,s.isMissing)(r.body)&&(0,s.isMissing)(i.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,i);if((0,s.isMissing)(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if((0,s.exceedsSize)(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=(0,s.isMissing)(e.body)?void 0:(0,s.extractSchema)(e.body),r=(0,s.isMissing)(t.body)?void 0:(0,s.extractSchema)(t.body);if(!((0,s.isMissing)(n)&&(0,s.isMissing)(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if((0,s.isMissing)(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new u.GetObjectCommand({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new u.PutObjectCommand({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},U=g.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 g.z.ZodError([{code:g.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},g.z.coerce.date()),W=g.z.object({logType:g.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:U,startTime:U,endTime:U.optional().nullable().transform(e=>e??void 0),durationMs:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:g.z.coerce.string(),projectSecureId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),G=W.extend({logType:g.z.literal(`action`),actionRunId:g.z.coerce.string(),actionId:g.z.coerce.string(),connectorKey:g.z.coerce.string(),connectorVersion:g.z.coerce.string(),connectorOwner:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),actionType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),K=W.extend({logType:g.z.literal(`step`),actionRunId:g.z.coerce.string(),stepIndex:g.z.coerce.number(),stepId:g.z.coerce.string(),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),skipped:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:g.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),q=W.extend({logType:g.z.literal(`unified`),requestId:g.z.coerce.string(),connectorKey:g.z.coerce.string(),connectorVersion:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),mode:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),J=W.extend({logType:g.z.literal(`provider`),requestId:g.z.coerce.string(),id:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:g.z.coerce.string(),mode:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:g.z.coerce.string(),originOwnerId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:g.z.coerce.string(),path:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:g.z.coerce.string(),connectorVersion:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),status:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:g.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),Y=W.extend({logType:g.z.literal(`platform`),eventId:g.z.coerce.string(),eventType:g.z.coerce.string(),service:g.z.coerce.string(),userId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),subAction:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:g.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),pe=g.z.discriminatedUnion(`logType`,[G,K,q,J,Y]),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()]},requestsPlatformLogs=e=>toArray(e.logType).includes(D.Platform);var LogsSink=class{#e;#t;#n;#r;#i;#a;#o(e){if(e===`clickhouse`&&this.#i?.isReady())return this.#i;if(this.#r?.isReady())return this.#r;if(this.#i?.isReady())return this.#i}#s(e,t){if(!requestsPlatformLogs(e))return this.#o(t);if(this.#i?.isReady())return this.#i;this.#a?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`})}constructor(e,t,n,r,i,a,o){this.#e=e,this.#t=a,this.#n=o,this.#a=r,n&&(this.#r=new TinybirdClient(t,n,r)),i&&(this.#i=new ClickHouseClient(i,r));let s=[];this.#r&&s.push(`tinybird`),this.#i&&s.push(`clickhouse`),s.length>0&&this.#a?.debug({message:`LogsSink initialized with query clients: ${s.join(`, `)}`,category:`LogsSink`})}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#a?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}let e=this.#r?.isReady()??!1,t=this.#i?.isReady()??!1;!e&&!t?this.#a?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}):this.#a?.info({message:`Logs sink query clients ready: tinybird=${e}, clickhouse=${t}`,category:`LogsSink`}),this.#a?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#c()}async#c(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#a?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#a?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#a?.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.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#a?.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,t){let n=this.#s(e,t);try{this.#a?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} logs (${r.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(r.data),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(requestsPlatformLogs(e)||this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{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.#i;if(!r?.isReady())return this.#a?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#a?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#a?.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.#a?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} action logs (${r.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(r.data,G),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n,r){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n},r)).actionLogs[0]}async getSteps(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} step logs (${r.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(r.data,K),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.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.#a?.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,i){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r},i)).stepLogs[0]}async getUnifiedLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} unified logs (${r.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(r.data,q),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n,r){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n},r)).unifiedLogs[0]}async getProviderLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} provider logs (${r.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(r.data,J),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} platform logs (${r.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(r.data,Y),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r,i){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r},i)).providerLogs[0]}async getAggregate(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n,engine:r}});let{dimensions:a,startTime:o,endTime:c,...l}=n,u=n.intervalType===A.None,d={organizationId:e,projectSecureId:t,...l,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...c&&{endTime:c.toISOString()},...u&&{pageSize:void 0,pageNumber:void 0}},f=await i?.query({endpoint:`project_logs_aggregation.json`,params:d});if(!f)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${f.length} aggregated data points`,category:`LogsSink`});let p=f.map(e=>(0,s.convertKeysToCamelCase)(e,!0)),m=[`success`,`isWorker`,`isBackground`,`skipped`],h=p.map(e=>{let t={...e};for(let e of m)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:u?foldTimeBuckets(h):h}}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n,engine:r}});let{dimensions:a,startTime:o,endTime:s,maxValues:c,...l}=n,u={organizationId:e,projectSecureId:t,...l,dimensions:a.join(`,`),...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...c&&{maxValuesPerDim:c}},d=await i?.query({endpoint:`project_logs_dimensions.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#a?.info({message:`Successfully retrieved ${d.length} dimension facets`,category:`LogsSink`});let f=[`success`,`isWorker`,`isBackground`,`skipped`],p={};for(let e of d)f.includes(e.dimension)?p[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):p[e.dimension]=e.values;return p}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n,engine:r}});let{startTime:a,endTime:o,sourceType:s}=n,c={organizationId:e,projectSecureId:t,...s&&{sourceType:Array.isArray(s)?s.join(`,`):s},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await i?.query({endpoint:`project_source_usage.json`,params:c});return l?(this.#a?.info({message:`Successfully retrieved ${l.length} source usage records`,category:`LogsSink`}),l.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#l(e){return(this.#n??j)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#l(e);if(!n)throw this.#a?.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.#a?.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.#a?.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.#a?.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.#u(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#u(e,t,n,r){if(!t)throw this.#a?.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.#a?.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.#a?.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.#a?.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},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,connectorVersion:`2`,...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,h.randomUUID)(),eventType:e.eventType,service:e.service,organizationId:e.organizationId,...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.accountSecureId!==void 0&&{accountSecureId:e.accountSecureId},...e.userId!==void 0&&{userId:e.userId},...e.action!==void 0&&{action:e.action},...e.subAction!==void 0&&{subAction:e.subAction},...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},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeSerialize(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 g.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.#a?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird 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 g.ZodError?this.#a?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#a?.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 G;case`step`:return K;case`unified`:return q;case`provider`:return J;case`platform`:return Y}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`},defender:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...X.logs,...e?.logs},advanced:{...X.advanced,...e?.advanced},defender:{...X.defender,...e?.defender},datasets:{...X.datasets,...e?.datasets}}}const buildHttpClient=e=>{try{return new _.HttpClient({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},Z=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Z}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Z}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),Q=__name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=Q(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=Q(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new u.S3Client(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){this.name=`OlapClient`,this.#c=e,this.#l=a??i,this.#u=t,this.#d=o,this.#h=s,this.#f=l,this.#p=u,this.#m=d,this.#t=n(f),this.#n=r(c,f),this.#r=f}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){let p=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});return await p.initialize(),p}async initialize(){this.#e=await this.#c(this.#l,this.#r);let e=this.#d?{producer:await this.#u(this.#d,this.#r)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#i=new LogsSink(t,this.#t,this.#f,this.#r,this.#p,e,this.#h),this.#a=new AdvancedSink(this.#n,this.#m?.advanced,this.#r),this.#o=new DefenderSink(this.#n,this.#m?.defender,this.#r),this.#s=new DatasetsSink(this.#m?.datasets,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#s?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,datasets:a}=resolveOlapOptions(t);this.#r?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,datasets:a}}});for(let t of e)(0,s.isMissing)(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let o=a?.enabled&&this.#s?this.#s.sendActions(e,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[c,l]=await Promise.all([r?.enabled&&this.#a?this.#a.sendActions(e,r).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#o?this.#o.sendActions(e,i).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),u=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:c[t]?.expiresAt,defenderExpiresAt:l[t]?.expiresAt}})),d=n?.enabled&&this.#i?this.#i.sendActions(u,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([o,d])}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.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}}),(0,s.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#a?await this.#a.sendUnified(e,t,i).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#i&&await this.#i.sendUnified(e,t,a,r).catch(e=>{this.#r?.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.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#i?(r?this.#i.sendPlatform(e,a):this.#i.sendPlatform(e,t??{},a)).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#a?this.#a.sendPlatform(e,i,o).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n,r){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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.#r?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#i?.getLastLogs(n,i)||(this.#r?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n,r){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n,r){let i=await this.#i?.getAction(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return i}async getLog(e,t,n,r){this.#r?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n,engine:r}});let i=await this.getLogs(e,t,{logId:n,pageSize:1},r);if(!i||i.logs.length===0){this.#r?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let a=i.logs[0];if(a.logType===`action`||a.logType===`unified`)return a}async getStepLogs(e,t,n,r){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,r,i){let a=await this.#i?.getStep(e,t,n,r,i);if((0,s.isMissing)(a)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n,r){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n,r){let i=await this.#i?.getUnifiedLog(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n,r){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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,n){let r={...t,organizationId:e};return this.#r?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:r,engine:n}}),await this.#i?.getPlatformLogs(r,n)||(this.#r?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,n,r,i){let a=await this.#i?.getProviderLog(e,t,n,r,i);if((0,s.isMissing)(a)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if((0,s.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#a?.getStep(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#a?.getUnified(e,t,n);if((0,s.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#a?.getProvider(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#a?.getPlatform(e,t);if((0,s.isMissing)(n)){this.#r?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if((0,s.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n,r){return this.#r?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getAggregate(e,t,n,r)??{data:[]}}async getLogsStatsDimensions(e,t,n,r){return this.#r?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getDimensions(e,t,n,r)??{}}async getSourceUsage(e,t,n,r){return this.#r?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSourceUsage(e,t,n,r)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f,getOlapClient:p=buildOlapClientInstance}){return this.olapClientPromise||=p({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};exports.AuthType=le,exports.ClickHouseClient=ClickHouseClient,exports.DEFAULT_TOPIC_CLUSTER_MAP=j,exports.Dimension=ie,exports.IntervalType=A,exports.LogType=D,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=O,exports.OrderDirection=k,exports.SourceType=F,exports.StreamType=ce,exports.TransportType=se,exports.createConfigFromEnv=createConfigFromEnv,exports.createOlapQueryClient=createOlapQueryClient,exports.hasErrorEntries=hasErrorEntries;
674
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_source_usage.json`,buildQuery:buildSourceUsageQuery});var SchemaValidationError$1=class extends Error{static{__name(this,`SchemaValidationError`)}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,o.createClient)({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#a(e.endpoint,e.params),n=this.#i(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async queryRaw(e){try{let t=await this.#a(e.endpoint,e.params);return t.data=this.#i(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError$1)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying clickhouse endpoint ${e.endpoint}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError$1(t,e)}}async#a(e,t){let n=this.#r(),r=getQueryDefinition(e);if(!r)throw Error(`Unknown endpoint: ${e}. No query definition registered.`);let{sql:i,params:a}=r.buildQuery(t??{});this.#n?.debug({message:`Querying clickhouse endpoint: ${e}`,category:`ClickHouseClient`,context:{endpoint:e,params:t}});let o=Date.now(),s=await(await n.query({query:i,query_params:a,format:`JSONEachRow`})).json(),c=(Date.now()-o)/1e3,l;if(r.buildCountQuery){let{sql:e,params:i}=r.buildCountQuery(t??{});l=(await(await n.query({query:e,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${s.length} rows`,category:`ClickHouseClient`,context:{endpoint:e,rows:s.length,elapsed:c}}),{meta:[],data:s,rows:s.length,rows_before_limit_at_least:l,statistics:{elapsed:c,rows_read:s.length,bytes_read:0}}}},SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error Querying tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new c.default.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(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:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};function createOlapQueryClient(e,t,n){switch(e.type){case`clickhouse`:if(!e.clickhouse)throw Error(`ClickHouse config required when type is "clickhouse"`);return new ClickHouseClient(e.clickhouse,n);default:return new TinybirdClient(t,e.tinybird,n)}}function createConfigFromEnv(){let e=process.env.TINYBIRD_BASE_URL,t=process.env.TINYBIRD_TOKEN,n=e&&t?{baseUrl:e,token:t,allowHttp:process.env.TINYBIRD_ALLOW_HTTP===`true`}:void 0,r=process.env.CLICKHOUSE_URL,i=r?{url:r,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0;return{type:n?`tinybird`:i?`clickhouse`:`tinybird`,tinybird:n,clickhouse:i}}const N={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},ae={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},oe={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},se={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},ce=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],le=[N.Scheduler,N.DataSync,N.DataSyncV2,N.Internal],P=[`data_sync`],F=[N.DataSync,N.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&ce.includes(e)||t&&le.includes(t))}function isDataSync(e,t){return!!(e&&P.includes(e)||t&&F.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>(0,s.isMissing)(e)?!1:Array.isArray(e)||(0,s.isString)(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,I=64*1024,L=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],R=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>(0,s.isObject)(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return(0,s.isObject)(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:n,total:r}=e.reduce((e,n)=>{if(e.total>t)return e;let r=e.total+(0,s.calculateSize)(n);return r>t?{kept:e.kept,total:r}:{kept:e.kept+1,total:r}},{kept:0,total:0});return r>t?e.slice(0,n):e},fitObject=(e,t)=>{let n=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+(0,s.calculateSize)(t)})).sort((e,t)=>e.size-t.size),{kept:r,remaining:i}=n.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),a=n.filter(e=>!r.includes(e.key)),o=a.length===0?0:Math.floor(i/a.length);return Object.fromEntries(n.map(e=>[e.key,r.includes(e.key)?e.value:fitValue(e.value,o)]))},fitValue=(e,t)=>{let n=(0,s.calculateSize)(e);return n<=t?e:((0,s.isString)(e)||Array.isArray(e)||(0,s.isObject)(e)&&!(0,s.isDate)(e))&&t<=0?marker(n):(0,s.isString)(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):(0,s.isObject)(e)&&!(0,s.isDate)(e)?fitObject(e,t):e},payloadFields=e=>L.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!(0,s.isMissing)(e)).map(e=>({...e,size:(0,s.calculateSize)(e.value)})),byRetentionPriority=e=>[...e.filter(e=>R.includes(e.path)),...e.filter(e=>!R.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*I;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(I,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>L.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),z=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],B=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],V=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e=this.createActionS3(r,i,t),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r=this.createStepS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new u.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new u.GetObjectCommand({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new u.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new u.GetObjectCommand({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new u.PutObjectCommand({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new u.HeadObjectCommand({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new u.GetObjectCommand({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{Key:i,ContentType:`application/json`,Expires:new Date(a*1e3),Body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let n=(0,l.redactFields)(e.data,l.CensorType.PARTIAL,!0),r={...e.metadata,expirationTime:t,sizeBytes:(0,s.calculateSize)(n)};return this.stringifyPlatform({data:n,metadata:r},r)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),u=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),d=this.processContent(o,c,`upload`),f=this.processContent(s,u,`download`),p=e.isBackground??isBackgroundLog(e.mode,e.sourceType),m=e.url,h={};if(e.url)try{m=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(m);h=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let g={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:m,path:e.pathParams,queryParams:h},body:d},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:f},...p?{isBackgroundLog:!0}:{}},metadata:{...p?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),u=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),d=this.processContent(o,c,`upload`),f=this.processContent(s,u,`download`),p=e.isBackground??isBackgroundLog(e.mode,e.sourceType),m=`/`,h=e.url,g={};if(e.url)try{h=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(h);m=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let _={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:h,path:m,queryParams:g},body:d},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:f}},metadata:{...p?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),u=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),d=this.processContent(o,c,`upload`),f=this.processContent(s,u,`download`),p,m=``,h=`/`,g={};if(e.url)try{p=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(p);m=t.hostname,h=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let _={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:p,hostname:m,path:h,queryParams:g},body:d},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:f}},metadata:{expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeAndLimit(e,t,n,r){let i=(0,s.calculateSize)(e);if(r===`complete`)return this.stringifyLog(e,{sizeBytes:i});let a=n&&r===`truncate`?t*this.#r:t;if(i<=a)return this.stringifyLog(e,{sizeBytes:i});if(r===`drop`)return this.#i?.warning({message:`Advanced log of ${i} bytes exceeds ${a}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:i,maxSizeBytes:a,isErrorResult:n}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:i,maxSizeBytes:a,truncated:!0});let{data:o,truncatedPaths:c}=truncateToLimit(e,a);return this.#i?.warning({message:`Advanced log of ${i} bytes exceeds ${a}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:i,maxSizeBytes:a,isErrorResult:n,truncatedPaths:c}}),this.stringifyLog(o,{sizeBytes:i,maxSizeBytes:a,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=z.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return B.includes(i)||V.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,s.isMissing)(e)){if(!(0,s.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new d.OTLPTraceExporter({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[m.ATTR_SERVICE_NAME]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new p.BasicTracerProvider({resource:(0,f.resourceFromAttributes)(n),spanProcessors:[new p.BatchSpanProcessor(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,includeBackground:t.includeBackground}}),(0,s.isMissing)(r.body)&&(0,s.isMissing)(i.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,i);if((0,s.isMissing)(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if((0,s.exceedsSize)(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=(0,s.isMissing)(e.body)?void 0:(0,s.extractSchema)(e.body),r=(0,s.isMissing)(t.body)?void 0:(0,s.extractSchema)(t.body);if(!((0,s.isMissing)(n)&&(0,s.isMissing)(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if((0,s.isMissing)(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new u.GetObjectCommand({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new u.PutObjectCommand({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},H=g.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 g.z.ZodError([{code:g.z.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},g.z.coerce.date()),U=g.z.object({logType:g.z.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:g.z.coerce.string(),projectSecureId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:g.z.literal(`action`),actionRunId:g.z.coerce.string(),actionId:g.z.coerce.string(),connectorKey:g.z.coerce.string(),connectorVersion:g.z.coerce.string(),connectorOwner:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),actionType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:g.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:g.z.literal(`step`),actionRunId:g.z.coerce.string(),stepIndex:g.z.coerce.number(),stepId:g.z.coerce.string(),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),skipped:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),message:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:g.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:g.z.literal(`unified`),requestId:g.z.coerce.string(),connectorKey:g.z.coerce.string(),connectorVersion:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),mode:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:g.z.literal(`provider`),requestId:g.z.coerce.string(),id:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:g.z.coerce.string(),mode:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:g.z.coerce.string(),originOwnerId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:g.z.coerce.string(),path:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:g.z.coerce.string(),connectorVersion:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:g.z.coerce.string(),accountSecureId:g.z.coerce.string(),status:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),provider:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:g.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),J=U.extend({logType:g.z.literal(`platform`),eventId:g.z.coerce.string(),eventType:g.z.coerce.string(),service:g.z.coerce.string(),organizationId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:g.z.undefined(),userId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),authId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:g.z.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:g.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:g.z.record(g.z.unknown()).optional().nullable().transform(e=>e??void 0)}),ue=g.z.discriminatedUnion(`logType`,[W,G,K,q]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Y=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a;#o(e){if(e===`clickhouse`&&this.#i?.isReady())return this.#i;if(this.#r?.isReady())return this.#r;if(this.#i?.isReady())return this.#i}#s(){if(this.#i?.isReady())return this.#i;this.#a?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`})}constructor(e,t,n,r,i,a,o){this.#e=e,this.#t=a,this.#n=o,this.#a=r,n&&(this.#r=new TinybirdClient(t,n,r)),i&&(this.#i=new ClickHouseClient(i,r));let s=[];this.#r&&s.push(`tinybird`),this.#i&&s.push(`clickhouse`),s.length>0&&this.#a?.debug({message:`LogsSink initialized with query clients: ${s.join(`, `)}`,category:`LogsSink`})}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#a?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}let e=this.#r?.isReady()??!1,t=this.#i?.isReady()??!1;!e&&!t?this.#a?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}):this.#a?.info({message:`Logs sink query clients ready: tinybird=${e}, clickhouse=${t}`,category:`LogsSink`}),this.#a?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#c()}async#c(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#a?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#a?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#a?.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.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#a?.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.#a?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#a?.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,t){let n=this.#o(t);try{this.#a?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} logs (${r.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(r.data),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{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.#i;if(!r?.isReady())return this.#a?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#a?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#a?.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.#a?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} action logs (${r.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(r.data,W),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n,r){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n},r)).actionLogs[0]}async getSteps(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} step logs (${r.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(r.data,G),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.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.#a?.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,i){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r},i)).stepLogs[0]}async getUnifiedLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} unified logs (${r.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(r.data,K),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n,r){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n},r)).unifiedLogs[0]}async getProviderLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} provider logs (${r.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(r.data,q),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e){let t=this.#s();try{this.#a?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#a?.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}):{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}catch(n){return t?.isReady()?this.#a?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#a?.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,i){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r},i)).providerLogs[0]}async getAggregate(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n,engine:r}});let{dimensions:a,startTime:o,endTime:c,...l}=n,u=n.intervalType===T.None,d={organizationId:e,projectSecureId:t,...l,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...c&&{endTime:c.toISOString()},...u&&{pageSize:void 0,pageNumber:void 0}},f=await i?.query({endpoint:`project_logs_aggregation.json`,params:d});if(!f)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${f.length} aggregated data points`,category:`LogsSink`});let p=f.map(e=>(0,s.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:u?foldTimeBuckets(p):p}}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats aggregate, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{data:[]}}}async getDimensions(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n,engine:r}});let{dimensions:a,startTime:o,endTime:s,maxValues:c,...l}=n,u={organizationId:e,projectSecureId:t,...l,dimensions:a.join(`,`),...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...c&&{maxValuesPerDim:c}},d=await i?.query({endpoint:`project_logs_dimensions.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{};this.#a?.info({message:`Successfully retrieved ${d.length} dimension facets`,category:`LogsSink`});let f={};for(let e of d)Y.includes(e.dimension)?f[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):f[e.dimension]=e.values;return f}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n,engine:r}});let{startTime:a,endTime:o,sourceType:s}=n,c={organizationId:e,projectSecureId:t,...s&&{sourceType:Array.isArray(s)?s.join(`,`):s},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await i?.query({endpoint:`project_source_usage.json`,params:c});return l?(this.#a?.info({message:`Successfully retrieved ${l.length} source usage records`,category:`LogsSink`}),l.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#l(e){return(this.#n??D)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#l(e);if(!n)throw this.#a?.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.#a?.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.#a?.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.#a?.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.#u(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#u(e,t,n,r){if(!t)throw this.#a?.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.#a?.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.#a?.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.#a?.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},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,connectorVersion:`2`,...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,h.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 g.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.#a?.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,ue)}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 g.ZodError?this.#a?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#a?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return W;case`step`:return G;case`unified`:return K;case`provider`:return q;case`platform`:return J}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`},defender:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...X.logs,...e?.logs},advanced:{...X.advanced,...e?.advanced},defender:{...X.defender,...e?.defender},datasets:{...X.datasets,...e?.datasets}}}const buildHttpClient=e=>{try{return new _.HttpClient({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},Z=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${Z}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${Z}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),Q=__name(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=Q(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=Q(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,reconstruct=async e=>{let a=Date.now();if(!(a-i<3e4)){i=a;try{let i=r;r=await t(),Promise.resolve().then(()=>i.close()).catch(()=>void 0),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}}},send=async e=>{try{return await r.send(e)}catch(e){throw await reconstruct(e),e}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},buildInternalKafkaClient=async(e,t)=>{if(!e)return;let{bootstrapBrokers:n,region:r,clientId:i,...a}=e;return buildKafkaClient({bootstrapBrokers:n,clientId:i??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:r,logger:t})},...a},t)},buildS3Client=(e,t)=>{try{return new u.S3Client(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){this.name=`OlapClient`,this.#c=e,this.#l=a??i,this.#u=t,this.#d=o,this.#h=s,this.#f=l,this.#p=u,this.#m=d,this.#t=n(f),this.#n=r(c,f),this.#r=f}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}){let p=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});return await p.initialize(),p}async initialize(){this.#e=await this.#c(this.#l,this.#r);let e=this.#d?{producer:await this.#u(this.#d,this.#r)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#i=new LogsSink(t,this.#t,this.#f,this.#r,this.#p,e,this.#h),this.#a=new AdvancedSink(this.#n,this.#m?.advanced,this.#r),this.#o=new DefenderSink(this.#n,this.#m?.defender,this.#r),this.#s=new DatasetsSink(this.#m?.datasets,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#s?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,datasets:a}=resolveOlapOptions(t);this.#r?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,datasets:a}}});for(let t of e)(0,s.isMissing)(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let o=a?.enabled&&this.#s?this.#s.sendActions(e,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[c,l]=await Promise.all([r?.enabled&&this.#a?this.#a.sendActions(e,r).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#o?this.#o.sendActions(e,i).catch(t=>(this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),u=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:c[t]?.expiresAt,defenderExpiresAt:l[t]?.expiresAt}})),d=n?.enabled&&this.#i?this.#i.sendActions(u,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([o,d])}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.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}}),(0,s.isMissing)(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#a?await this.#a.sendUnified(e,t,i).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#i&&await this.#i.sendUnified(e,t,a,r).catch(e=>{this.#r?.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.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#i?(r?this.#i.sendPlatform(e,a):this.#i.sendPlatform(e,t??{},a)).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#a?this.#a.sendPlatform(e,i,o).catch(e=>(this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n,r){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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.#r?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#i?.getLastLogs(n,i)||(this.#r?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n,r){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n,r){let i=await this.#i?.getAction(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return i}async getLog(e,t,n,r){this.#r?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n,engine:r}});let i=await this.getLogs(e,t,{logId:n,pageSize:1},r);if(!i||i.logs.length===0){this.#r?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let a=i.logs[0];if(a.logType===`action`||a.logType===`unified`)return a}async getStepLogs(e,t,n,r){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,r,i){let a=await this.#i?.getStep(e,t,n,r,i);if((0,s.isMissing)(a)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n,r){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n,r){let i=await this.#i?.getUnifiedLog(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n,r){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.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.#r?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getPlatformLogs(n)||(this.#r?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,n,r,i){let a=await this.#i?.getProviderLog(e,t,n,r,i);if((0,s.isMissing)(a)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if((0,s.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#a?.getStep(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#a?.getUnified(e,t,n);if((0,s.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#a?.getProvider(e,t,n,r);if((0,s.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#a?.getPlatform(e,t);if((0,s.isMissing)(n)){this.#r?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if((0,s.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n,r){return this.#r?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getAggregate(e,t,n,r)??{data:[]}}async getLogsStatsDimensions(e,t,n,r){return this.#r?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getDimensions(e,t,n,r)??{}}async getSourceUsage(e,t,n,r){return this.#r?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getSourceUsage(e,t,n,r)??[]}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,getHttpClient:n=buildHttpClient,getS3Client:r=buildS3Client,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f,getOlapClient:p=buildOlapClientInstance}){return this.olapClientPromise||=p({getKafkaClient:e,getInternalKafkaClient:t,getHttpClient:n,getS3Client:r,kafkaClientConfig:i,externalKafkaClientConfig:a,internalKafkaClientConfig:o,topicClusterMap:s,s3ClientConfig:c,tinybirdConfig:l,clickhouseConfig:u,sinkConfig:d,logger:f}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};exports.AuthType=se,exports.ClickHouseClient=ClickHouseClient,exports.DEFAULT_TOPIC_CLUSTER_MAP=D,exports.Dimension=E,exports.IntervalType=T,exports.LogType=C,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=ie,exports.OrderDirection=w,exports.SourceType=N,exports.StreamType=oe,exports.TransportType=ae,exports.createConfigFromEnv=createConfigFromEnv,exports.createOlapQueryClient=createOlapQueryClient,exports.hasErrorEntries=hasErrorEntries;