@stackone/olap 1.62.0 → 1.64.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
@@ -276,7 +276,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
276
276
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
277
277
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
278
278
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
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 ee={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},S=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],te=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`];function shouldIncludeUnified(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`unified`))return!1;let n=e;for(let e of te)if(n[e]!==void 0)return!1;return!0}function shouldIncludeActions(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`action`))return!1;let n=e;for(let e of S)if(n[e]!==void 0)return!1;return!0}function buildUnifiedFilters(){return`AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
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 ee={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},S=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],C=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`];function shouldIncludeUnified(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`unified`))return!1;let n=e;for(let e of C)if(n[e]!==void 0)return!1;return!0}function shouldIncludeActions(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`action`))return!1;let n=e;for(let e of S)if(n[e]!==void 0)return!1;return!0}function buildUnifiedFilters(){return`AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
280
280
  AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
281
281
  AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
282
282
  AND ({connectorKey:Array(String)} = [] OR provider IN {connectorKey:Array(String)})
@@ -450,7 +450,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
450
450
  ${buildActionsFilters()}
451
451
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
452
452
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
453
- `),{sql:r.length>0?`SELECT sum(cnt) as total FROM (${r.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const C={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`},w=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(C,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=C[e];return`
453
+ `),{sql:r.length>0?`SELECT sum(cnt) as total FROM (${r.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const w={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`},T=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(w,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=w[e];return`
454
454
  SELECT
455
455
  '${e}' as dimension,
456
456
  arrayReverseSort(
@@ -465,14 +465,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
465
465
  ${i}
466
466
  ) AS combined
467
467
  WHERE ${t} IS NOT NULL
468
- ${w.has(e)?`AND ${t} != ''`:``}
468
+ ${T.has(e)?`AND ${t} != ''`:``}
469
469
  GROUP BY ${t}
470
470
  ORDER BY count DESC
471
471
  LIMIT {maxValues:UInt32}
472
472
  ) AS facets
473
473
  `}).join(`
474
474
  UNION ALL
475
- `),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||!w.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
475
+ `),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||!T.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
476
476
  WITH combined AS (
477
477
  ${buildCombinedSourceSql(e)}
478
478
  )
@@ -480,7 +480,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
480
480
  WHERE ${t} IN {entityIds:Array(String)}
481
481
  ORDER BY eventTime DESC
482
482
  LIMIT 1 BY ${t}
483
- `,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 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={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},D={minute:60,hour:3600,day:86400,week:604800,month:2592e3};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(T,e)).map(e=>T[e]),o=a.length>0?`, ${a.join(`, `)}`:``,c=a.length>0?`, ${a.join(`, `)}`:``,l=Object.prototype.hasOwnProperty.call(E,n)?E[n]:`toStartOfHour`,u=i*(Object.prototype.hasOwnProperty.call(D,n)?D[n]:3600),d=i>1?`toDateTime(intDiv(toUnixTimestamp(${l}(eventTime)), ${u}) * ${u})`:`${l}(eventTime)`;return{sql:`
483
+ `,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 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={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},O={minute:60,hour:3600,day:86400,week:604800,month:2592e3};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(E,e)).map(e=>E[e]),o=a.length>0?`, ${a.join(`, `)}`:``,c=a.length>0?`, ${a.join(`, `)}`:``,l=Object.prototype.hasOwnProperty.call(D,n)?D[n]:`toStartOfHour`,u=i*(Object.prototype.hasOwnProperty.call(O,n)?O[n]:3600),d=i>1?`toDateTime(intDiv(toUnixTimestamp(${l}(eventTime)), ${u}) * ${u})`:`${l}(eventTime)`;return{sql:`
484
484
  WITH combined AS (
485
485
  ${buildCombinedSourceSql(e)}
486
486
  )
@@ -492,7 +492,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
492
492
  WHERE ({actionType:Array(String)} = [] OR actionType IN {actionType:Array(String)})
493
493
  GROUP BY startTime ${c}
494
494
  ORDER BY startTime ASC
495
- `,params:{...buildCommonLogParams(e),actionType:toArray(e.actionType)}}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const O={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
495
+ `,params:{...buildCommonLogParams(e),actionType:toArray(e.actionType)}}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const te={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
496
496
  SELECT
497
497
  eventDatetime as eventTime,
498
498
  startTime,
@@ -532,7 +532,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
532
532
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
533
533
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
534
534
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
535
- ORDER BY ${sanitizeOrderBy(e.orderBy,O,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
535
+ ORDER BY ${sanitizeOrderBy(e.orderBy,te,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
536
536
  LIMIT {limit:UInt32}
537
537
  OFFSET {offset:UInt32}
538
538
  `,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:`
@@ -547,7 +547,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
547
547
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
548
548
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
549
549
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
550
- `,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 k={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
550
+ `,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 ne={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
551
551
  SELECT
552
552
  eventTime,
553
553
  startTime,
@@ -579,7 +579,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
579
579
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
580
580
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
581
581
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
582
- ORDER BY ${sanitizeOrderBy(e.orderBy,k,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
582
+ ORDER BY ${sanitizeOrderBy(e.orderBy,ne,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
583
583
  LIMIT {limit:UInt32}
584
584
  OFFSET {offset:UInt32}
585
585
  `,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),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:`
@@ -615,4 +615,4 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
615
615
  AND sourceId != ''
616
616
  GROUP BY sourceId, sourceType
617
617
  ORDER BY request_count DESC
618
- `,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 A={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),ne={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},re={Asc:`asc`,Desc:`desc`},ie={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`},ae={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,IsBackground:`isBackground`},j={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},M={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`},N={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},P={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},F={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},I=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],L=[M.Scheduler,M.DataSync,M.DataSyncV2,M.Internal],R=[`data_sync`],z=[M.DataSync,M.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&I.includes(e)||t&&L.includes(t))}function isDataSync(e,t){return!!(e&&R.includes(e)||t&&z.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,B=[`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`],V=[`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`],H=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`];var AdvancedSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=n}async initialize(){if(!this.#e){this.#r?.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}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:`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.#r?.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.#r?.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.#r?.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.#r?.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?.ttl),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#r?.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.#r?.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.#r?.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?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#r?.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)}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),c=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),u=this.processContent(a,s,`upload`),d=this.processContent(o,c,`download`),f=e.isBackground??isBackgroundLog(e.mode,e.sourceType),p=e.url,m={};if(e.url)try{p=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(p);m=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let h={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:p,path:e.pathParams,queryParams:m},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:d},...f?{isBackgroundLog:!0}:{}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(h,r)}serializeStepResult(e,t,n,r){let i={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(i,r)}serializeUnifiedResult(e,t,n,r){let i=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),c=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),u=this.processContent(a,s,`upload`),d=this.processContent(o,c,`download`),f=e.isBackground??isBackgroundLog(e.mode,e.sourceType),p=`/`,m=e.url,h={};if(e.url)try{m=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(m);p=t.pathname,h=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let g={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:m,path:p,queryParams:h},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:d}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r)}serializeProviderResult(e,t,n,r){let i=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),c=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),u=this.processContent(a,s,`upload`),d=this.processContent(o,c,`download`),f,p=``,m=`/`,h={};if(e.url)try{f=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(f);p=t.hostname,m=t.pathname,h=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let g={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:f,hostname:p,path:m,queryParams:h},body:u},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:d}},metadata:{expirationTime:n}};return this.serializeAndLimit(g,r)}serializeAndLimit(e,t){if((0,s.exceedsSize)(e,t)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=B.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 V.includes(i)||H.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),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:g.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),oe=g.z.discriminatedUnion(`logType`,[G,K,q,J]);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}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.#s()}async#s(){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){if(!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 r=this.buildPlatformLog(e,t);await this.send(`platform`,[r])}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,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={organizationId:e,projectSecureId:t,...l,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...c&&{endTime:c.toISOString()}},d=await i?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,s.convertKeysToCamelCase)(e,!0)),p=[`success`,`isWorker`,`isBackground`,`skipped`];return{data:f.map(e=>{let t={...e};for(let e of p)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t})}}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}),[]}}#c(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.#c(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.#l(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#l(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},...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,oe)}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},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{logs:r}=resolveOlapOptions(n);r?.enabled&&this.#i&&await this.#i.sendPlatform(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}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 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=F,exports.ClickHouseClient=ClickHouseClient,exports.DEFAULT_TOPIC_CLUSTER_MAP=j,exports.Dimension=ae,exports.IntervalType=ie,exports.LogType=A,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=ne,exports.OrderDirection=re,exports.SourceType=M,exports.StreamType=P,exports.TransportType=N,exports.createConfigFromEnv=createConfigFromEnv,exports.createOlapQueryClient=createOlapQueryClient,exports.hasErrorEntries=hasErrorEntries;
618
+ `,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 k={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),A={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},re={Asc:`asc`,Desc:`desc`},ie={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`},ae={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,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===k.Platform,M={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`},N={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},P={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},F={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},I=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],L=[M.Scheduler,M.DataSync,M.DataSyncV2,M.Internal],R=[`data_sync`],z=[M.DataSync,M.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&I.includes(e)||t&&L.includes(t))}function isDataSync(e,t){return!!(e&&R.includes(e)||t&&z.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,B=[`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`],V=[`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`],H=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=n}async initialize(){if(!this.#e){this.#r?.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}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:`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.#r?.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.#r?.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.#r?.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.#r?.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?.ttl),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#r?.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.#r?.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.#r?.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?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;this.#r?.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.#r?.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.#r?.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.#r?.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.#r?.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.#r?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#r?.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??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#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,a={Key:r,ContentType:`application/json`,Expires:new Date(i*1e3)},o={...t.metadata,expirationTime:i},c={data:(0,l.redactFields)(t.data,l.CensorType.PARTIAL,!0),metadata:o},u=JSON.stringify(c);if(!(0,s.exceedsSize)(u,this.#n))return{...a,Body:u};this.#r?.warning({message:`Platform advanced payload exceeds maximum size, dropping data for eventId ${e.eventId}`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadTooLarge`});let d={data:{note:`Payload exceeded the maximum advanced log size and was dropped`},metadata:o};return{...a,Body:JSON.stringify(d)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),c=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),u=this.processContent(a,s,`upload`),d=this.processContent(o,c,`download`),f=e.isBackground??isBackgroundLog(e.mode,e.sourceType),p=e.url,m={};if(e.url)try{p=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(p);m=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let h={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:p,path:e.pathParams,queryParams:m},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:d},...f?{isBackgroundLog:!0}:{}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(h,r)}serializeStepResult(e,t,n,r){let i={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(i,r)}serializeUnifiedResult(e,t,n,r){let i=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),c=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),u=this.processContent(a,s,`upload`),d=this.processContent(o,c,`download`),f=e.isBackground??isBackgroundLog(e.mode,e.sourceType),p=`/`,m=e.url,h={};if(e.url)try{m=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(m);p=t.pathname,h=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let g={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:m,path:p,queryParams:h},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:d}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r)}serializeProviderResult(e,t,n,r){let i=(0,l.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=(0,l.redactFields)(e.body,l.CensorType.PARTIAL,!0),c=(0,l.redactFields)(t.body,l.CensorType.PARTIAL,!0),u=this.processContent(a,s,`upload`),d=this.processContent(o,c,`download`),f,p=``,m=`/`,h={};if(e.url)try{f=(0,l.redactUrl)(e.url,l.CensorType.PARTIAL);let t=new URL(f);p=t.hostname,m=t.pathname,h=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let g={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:f,hostname:p,path:m,queryParams:h},body:u},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:d}},metadata:{expirationTime:n}};return this.serializeAndLimit(g,r)}serializeAndLimit(e,t){if((0,s.exceedsSize)(e,t)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=B.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 V.includes(i)||H.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),success:g.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:g.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),oe=g.z.discriminatedUnion(`logType`,[G,K,q,J]);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}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.#s()}async#s(){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,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={organizationId:e,projectSecureId:t,...l,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...c&&{endTime:c.toISOString()}},d=await i?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>(0,s.convertKeysToCamelCase)(e,!0)),p=[`success`,`isWorker`,`isBackground`,`skipped`];return{data:f.map(e=>{let t={...e};for(let e of p)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t})}}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}),[]}}#c(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.#c(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.#l(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#l(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},...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,oe)}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},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=F,exports.ClickHouseClient=ClickHouseClient,exports.DEFAULT_TOPIC_CLUSTER_MAP=j,exports.Dimension=ae,exports.IntervalType=ie,exports.LogType=k,exports.OlapClient=$,exports.OlapClientManager=OlapClientManager,exports.OrderBy=A,exports.OrderDirection=re,exports.SourceType=M,exports.StreamType=P,exports.TransportType=N,exports.createConfigFromEnv=createConfigFromEnv,exports.createOlapQueryClient=createOlapQueryClient,exports.hasErrorEntries=hasErrorEntries;
package/dist/index.d.cts CHANGED
@@ -31,6 +31,20 @@ type DatasetsOptions = {
31
31
  includeBackground?: boolean;
32
32
  };
33
33
  //#endregion
34
+ //#region src/defender/types.d.ts
35
+ type DefenderSinkConfig = {
36
+ bucket?: string;
37
+ ttlDays?: number;
38
+ };
39
+ type DefenderLog = {
40
+ result?: {
41
+ riskLevel: string;
42
+ tier2Score?: number;
43
+ [key: string]: unknown;
44
+ };
45
+ [key: string]: unknown;
46
+ };
47
+ //#endregion
34
48
  //#region src/advanced/types.d.ts
35
49
  type AdvancedSinkConfig = {
36
50
  bucket?: string;
@@ -70,25 +84,19 @@ type ProviderAdvancedLog = {
70
84
  expirationTime?: number;
71
85
  };
72
86
  };
87
+ type PlatformAdvancedLog = {
88
+ data: {
89
+ [key: string]: unknown;
90
+ };
91
+ metadata?: {
92
+ expirationTime?: number;
93
+ };
94
+ };
73
95
  interface S3ClientConfig {
74
96
  region?: string;
75
97
  }
76
98
  type S3ClientBuilder = (config?: S3ClientConfig, logger?: ILogger) => S3Client | undefined;
77
99
  //#endregion
78
- //#region src/defender/types.d.ts
79
- type DefenderSinkConfig = {
80
- bucket?: string;
81
- ttlDays?: number;
82
- };
83
- type DefenderLog = {
84
- result?: {
85
- riskLevel: string;
86
- tier2Score?: number;
87
- [key: string]: unknown;
88
- };
89
- [key: string]: unknown;
90
- };
91
- //#endregion
92
100
  //#region src/types.d.ts
93
101
  declare const SourceType: {
94
102
  readonly RequestTester: "REQUEST_TESTER";
@@ -158,6 +166,8 @@ interface IOlapClient {
158
166
  recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
159
167
  recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
160
168
  recordPlatform(platformInput: PlatformInput, platformResult: PlatformResult, options?: OlapOptions): Promise<void>;
169
+ recordPlatform(platformLog: PlatformLog, options?: OlapOptions): Promise<void>;
170
+ recordPlatform(platformLog: PlatformLog, advancedLog: PlatformAdvancedLog, options?: OlapOptions): Promise<void>;
161
171
  getLogs(organizationId: string, projectSecureId: string, query: Query, engine?: OlapEngine): Promise<QueryResult>;
162
172
  getLastLogs(organizationId: string, projectSecureId: string, entities: LogEntities, query?: Query): Promise<QueryResult>;
163
173
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery, engine?: OlapEngine): Promise<ActionsQueryResult>;
@@ -174,6 +184,7 @@ interface IOlapClient {
174
184
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
175
185
  getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
176
186
  getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
187
+ getPlatformAdvancedLog(organizationId: string, eventId: string): Promise<PlatformAdvancedLog | undefined>;
177
188
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
178
189
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery, engine?: OlapEngine): Promise<AggregateResult>;
179
190
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery, engine?: OlapEngine): Promise<DimensionsResult>;
@@ -971,6 +982,8 @@ declare class OlapClient implements IOlapClient {
971
982
  recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
972
983
  recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
973
984
  recordPlatform(platformInput: PlatformInput, platformResult: PlatformResult, options?: OlapOptions): Promise<void>;
985
+ recordPlatform(platformLog: PlatformLog, options?: OlapOptions): Promise<void>;
986
+ recordPlatform(platformLog: PlatformLog, advancedLog: PlatformAdvancedLog, options?: OlapOptions): Promise<void>;
974
987
  getLogs(organizationId: string, projectSecureId: string, query: Query, engine?: OlapEngine): Promise<QueryResult>;
975
988
  getLastLogs(organizationId: string, projectSecureId: string, entities: LogEntities, query?: Query): Promise<QueryResult>;
976
989
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery, engine?: OlapEngine): Promise<ActionsQueryResult>;
@@ -987,6 +1000,7 @@ declare class OlapClient implements IOlapClient {
987
1000
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
988
1001
  getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
989
1002
  getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
1003
+ getPlatformAdvancedLog(organizationId: string, eventId: string): Promise<PlatformAdvancedLog | undefined>;
990
1004
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
991
1005
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery, engine?: OlapEngine): Promise<AggregateResult>;
992
1006
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery, engine?: OlapEngine): Promise<DimensionsResult>;
@@ -1062,4 +1076,4 @@ declare class OlapClientManager {
1062
1076
  //#region src/utils/stepErrors.d.ts
1063
1077
  declare const hasErrorEntries: (errors: unknown) => boolean;
1064
1078
  //#endregion
1065
- export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IQueryClient, type IQueryClient as ITinybirdClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapEngine, type OlapOptions, type OlapQueryClientConfig, type OlapQueryClientType, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryOptions as TinybirdQueryOptions, type QueryResponse, type QueryResponse as TinybirdResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TinybirdConfig, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, hasErrorEntries };
1079
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IQueryClient, type IQueryClient as ITinybirdClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapEngine, type OlapOptions, type OlapQueryClientConfig, type OlapQueryClientType, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformAdvancedLog, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryOptions as TinybirdQueryOptions, type QueryResponse, type QueryResponse as TinybirdResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TinybirdConfig, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, hasErrorEntries };
package/dist/index.d.mts CHANGED
@@ -30,6 +30,20 @@ type DatasetsOptions = {
30
30
  includeBackground?: boolean;
31
31
  };
32
32
  //#endregion
33
+ //#region src/defender/types.d.ts
34
+ type DefenderSinkConfig = {
35
+ bucket?: string;
36
+ ttlDays?: number;
37
+ };
38
+ type DefenderLog = {
39
+ result?: {
40
+ riskLevel: string;
41
+ tier2Score?: number;
42
+ [key: string]: unknown;
43
+ };
44
+ [key: string]: unknown;
45
+ };
46
+ //#endregion
33
47
  //#region src/advanced/types.d.ts
34
48
  type AdvancedSinkConfig = {
35
49
  bucket?: string;
@@ -69,25 +83,19 @@ type ProviderAdvancedLog = {
69
83
  expirationTime?: number;
70
84
  };
71
85
  };
86
+ type PlatformAdvancedLog = {
87
+ data: {
88
+ [key: string]: unknown;
89
+ };
90
+ metadata?: {
91
+ expirationTime?: number;
92
+ };
93
+ };
72
94
  interface S3ClientConfig {
73
95
  region?: string;
74
96
  }
75
97
  type S3ClientBuilder = (config?: S3ClientConfig, logger?: ILogger) => S3Client | undefined;
76
98
  //#endregion
77
- //#region src/defender/types.d.ts
78
- type DefenderSinkConfig = {
79
- bucket?: string;
80
- ttlDays?: number;
81
- };
82
- type DefenderLog = {
83
- result?: {
84
- riskLevel: string;
85
- tier2Score?: number;
86
- [key: string]: unknown;
87
- };
88
- [key: string]: unknown;
89
- };
90
- //#endregion
91
99
  //#region src/types.d.ts
92
100
  declare const SourceType: {
93
101
  readonly RequestTester: "REQUEST_TESTER";
@@ -157,6 +165,8 @@ interface IOlapClient {
157
165
  recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
158
166
  recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
159
167
  recordPlatform(platformInput: PlatformInput, platformResult: PlatformResult, options?: OlapOptions): Promise<void>;
168
+ recordPlatform(platformLog: PlatformLog, options?: OlapOptions): Promise<void>;
169
+ recordPlatform(platformLog: PlatformLog, advancedLog: PlatformAdvancedLog, options?: OlapOptions): Promise<void>;
160
170
  getLogs(organizationId: string, projectSecureId: string, query: Query, engine?: OlapEngine): Promise<QueryResult>;
161
171
  getLastLogs(organizationId: string, projectSecureId: string, entities: LogEntities, query?: Query): Promise<QueryResult>;
162
172
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery, engine?: OlapEngine): Promise<ActionsQueryResult>;
@@ -173,6 +183,7 @@ interface IOlapClient {
173
183
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
174
184
  getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
175
185
  getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
186
+ getPlatformAdvancedLog(organizationId: string, eventId: string): Promise<PlatformAdvancedLog | undefined>;
176
187
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
177
188
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery, engine?: OlapEngine): Promise<AggregateResult>;
178
189
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery, engine?: OlapEngine): Promise<DimensionsResult>;
@@ -970,6 +981,8 @@ declare class OlapClient implements IOlapClient {
970
981
  recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
971
982
  recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
972
983
  recordPlatform(platformInput: PlatformInput, platformResult: PlatformResult, options?: OlapOptions): Promise<void>;
984
+ recordPlatform(platformLog: PlatformLog, options?: OlapOptions): Promise<void>;
985
+ recordPlatform(platformLog: PlatformLog, advancedLog: PlatformAdvancedLog, options?: OlapOptions): Promise<void>;
973
986
  getLogs(organizationId: string, projectSecureId: string, query: Query, engine?: OlapEngine): Promise<QueryResult>;
974
987
  getLastLogs(organizationId: string, projectSecureId: string, entities: LogEntities, query?: Query): Promise<QueryResult>;
975
988
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery, engine?: OlapEngine): Promise<ActionsQueryResult>;
@@ -986,6 +999,7 @@ declare class OlapClient implements IOlapClient {
986
999
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
987
1000
  getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
988
1001
  getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
1002
+ getPlatformAdvancedLog(organizationId: string, eventId: string): Promise<PlatformAdvancedLog | undefined>;
989
1003
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
990
1004
  getLogsStatsAggregate(organizationId: string, projectSecureId: string, query: AggregateQuery, engine?: OlapEngine): Promise<AggregateResult>;
991
1005
  getLogsStatsDimensions(organizationId: string, projectSecureId: string, query: DimensionsQuery, engine?: OlapEngine): Promise<DimensionsResult>;
@@ -1061,4 +1075,4 @@ declare class OlapClientManager {
1061
1075
  //#region src/utils/stepErrors.d.ts
1062
1076
  declare const hasErrorEntries: (errors: unknown) => boolean;
1063
1077
  //#endregion
1064
- export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IQueryClient, type IQueryClient as ITinybirdClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapEngine, type OlapOptions, type OlapQueryClientConfig, type OlapQueryClientType, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryOptions as TinybirdQueryOptions, type QueryResponse, type QueryResponse as TinybirdResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TinybirdConfig, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, hasErrorEntries };
1078
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type AdvancedSinkConfig, type AggregateQuery, type AggregateResult, AuthType, type AuthType as AuthTypeValue, ClickHouseClient, type ClickHouseConfig, DEFAULT_TOPIC_CLUSTER_MAP, type DatasetsOptions, type DatasetsSinkConfig, type DefenderContext, type DefenderLog, type DefenderOptions, type DefenderSinkConfig, Dimension, type Dimension as DimensionValues, type DimensionsQuery, type DimensionsResult, type ILog, type IOlapClient, type IQueryClient, type IQueryClient as ITinybirdClient, type InternalKafkaClientBuilder, type InternalKafkaClientConfig, IntervalType, type IntervalType as IntervalTypeValues, type KafkaClientBuilder, type KafkaClientConfig, type KafkaClusterName, type LogEntities, LogType, type LogType as LogTypeValues, type LogfireConfig, type LogsOptions, OlapClient, OlapClientManager, type OlapEngine, type OlapOptions, type OlapQueryClientConfig, type OlapQueryClientType, type OlapSinkConfig, OrderBy, type OrderBy as OrderByValues, OrderDirection, type OrderDirection as OrderDirectionValues, type PlatformAdvancedLog, type PlatformInput, type PlatformLog, type PlatformQuery, type PlatformQueryResult, type PlatformResult, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryOptions, type QueryOptions as TinybirdQueryOptions, type QueryResponse, type QueryResponse as TinybirdResponse, type QueryResult, type SASLMechanism, type Source, type SourceQuery, type SourceResult, SourceType, type SourceType as SourceTypeValue, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, StreamType, type StreamType as StreamTypeValue, type TinybirdConfig, type TopicClusterMap, TransportType, type TransportType as TransportTypeValue, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult, createConfigFromEnv, createOlapQueryClient, hasErrorEntries };
package/dist/index.mjs CHANGED
@@ -276,7 +276,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
276
276
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
277
277
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
278
278
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
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 w={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},T=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],E=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`];function shouldIncludeUnified(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`unified`))return!1;let n=e;for(let e of E)if(n[e]!==void 0)return!1;return!0}function shouldIncludeActions(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`action`))return!1;let n=e;for(let e of T)if(n[e]!==void 0)return!1;return!0}function buildUnifiedFilters(){return`AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
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 w={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},T=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],oe=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`];function shouldIncludeUnified(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`unified`))return!1;let n=e;for(let e of oe)if(n[e]!==void 0)return!1;return!0}function shouldIncludeActions(e){let t=toArray(e.logType);if(t.length>0&&!t.includes(`action`))return!1;let n=e;for(let e of T)if(n[e]!==void 0)return!1;return!0}function buildUnifiedFilters(){return`AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
280
280
  AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
281
281
  AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
282
282
  AND ({connectorKey:Array(String)} = [] OR provider IN {connectorKey:Array(String)})
@@ -450,7 +450,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
450
450
  ${buildActionsFilters()}
451
451
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
452
452
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
453
- `),{sql:r.length>0?`SELECT sum(cnt) as total FROM (${r.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const D={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,isBackground:`isBackground`},O=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(s),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(D,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=D[e];return`
453
+ `),{sql:r.length>0?`SELECT sum(cnt) as total FROM (${r.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const 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=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(s),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(E,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=E[e];return`
454
454
  SELECT
455
455
  '${e}' as dimension,
456
456
  arrayReverseSort(
@@ -465,14 +465,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
465
465
  ${i}
466
466
  ) AS combined
467
467
  WHERE ${t} IS NOT NULL
468
- ${O.has(e)?`AND ${t} != ''`:``}
468
+ ${D.has(e)?`AND ${t} != ''`:``}
469
469
  GROUP BY ${t}
470
470
  ORDER BY count DESC
471
471
  LIMIT {maxValues:UInt32}
472
472
  ) AS facets
473
473
  `}).join(`
474
474
  UNION ALL
475
- `),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||!O.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
475
+ `),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||!D.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
476
476
  WITH combined AS (
477
477
  ${buildCombinedSourceSql(e)}
478
478
  )
@@ -480,7 +480,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
480
480
  WHERE ${t} IN {entityIds:Array(String)}
481
481
  ORDER BY eventTime DESC
482
482
  LIMIT 1 BY ${t}
483
- `,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 k={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`},A={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},j={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(s),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(k,e)).map(e=>k[e]),o=a.length>0?`, ${a.join(`, `)}`:``,c=a.length>0?`, ${a.join(`, `)}`:``,l=Object.prototype.hasOwnProperty.call(A,n)?A[n]:`toStartOfHour`,u=i*(Object.prototype.hasOwnProperty.call(j,n)?j[n]:3600),d=i>1?`toDateTime(intDiv(toUnixTimestamp(${l}(eventTime)), ${u}) * ${u})`:`${l}(eventTime)`;return{sql:`
483
+ `,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 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 buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(s),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=a.length>0?`, ${a.join(`, `)}`:``,c=a.length>0?`, ${a.join(`, `)}`:``,l=Object.prototype.hasOwnProperty.call(k,n)?k[n]:`toStartOfHour`,u=i*(Object.prototype.hasOwnProperty.call(A,n)?A[n]:3600),d=i>1?`toDateTime(intDiv(toUnixTimestamp(${l}(eventTime)), ${u}) * ${u})`:`${l}(eventTime)`;return{sql:`
484
484
  WITH combined AS (
485
485
  ${buildCombinedSourceSql(e)}
486
486
  )
@@ -492,7 +492,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
492
492
  WHERE ({actionType:Array(String)} = [] OR actionType IN {actionType:Array(String)})
493
493
  GROUP BY startTime ${c}
494
494
  ORDER BY startTime ASC
495
- `,params:{...buildCommonLogParams(e),actionType:toArray(e.actionType)}}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const oe={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
495
+ `,params:{...buildCommonLogParams(e),actionType:toArray(e.actionType)}}}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:`
496
496
  SELECT
497
497
  eventDatetime as eventTime,
498
498
  startTime,
@@ -532,7 +532,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
532
532
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
533
533
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
534
534
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
535
- ORDER BY ${sanitizeOrderBy(e.orderBy,oe,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
535
+ ORDER BY ${sanitizeOrderBy(e.orderBy,j,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
536
536
  LIMIT {limit:UInt32}
537
537
  OFFSET {offset:UInt32}
538
538
  `,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:`
@@ -615,4 +615,4 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
615
615
  AND sourceId != ''
616
616
  GROUP BY sourceId, sourceType
617
617
  ORDER BY request_count DESC
618
- `,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{e(this,`SchemaValidationError`)}constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=t({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError$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.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 ce={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),le={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},ue={Asc:`asc`,Desc:`desc`},M={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`},N={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`},P={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},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`},I={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},L={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},R={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},z=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],B=[F.Scheduler,F.DataSync,F.DataSyncV2,F.Internal],V=[`data_sync`],H=[F.DataSync,F.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&z.includes(e)||t&&B.includes(t))}function isDataSync(e,t){return!!(e&&V.includes(e)||t&&H.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},hasErrorEntries=e=>a(e)?!1:Array.isArray(e)||o(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,de=[`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`],fe=[`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`],pe=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`];var AdvancedSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=n}async initialize(){if(!this.#e){this.#r?.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}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:`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.#r?.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.#r?.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.#r?.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.#r?.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?.ttl),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#r?.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.#r?.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.#r?.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?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new p({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),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:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#r?.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.#r?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new p({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.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.#r?.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.#r?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new p({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#r?.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.#r?.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.#r?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new p({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.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.#r?.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.#r?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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 h({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#r?.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.#r?.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 m({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#r?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#r?.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)}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=d({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=u(e.body,l.PARTIAL,!0),c=u(t.body,l.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,c,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=e.url,_={};if(e.url)try{g=f(e.url,l.PARTIAL);let t=new URL(g);_=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let v={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:g,path:e.pathParams,queryParams:_},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:m},...h?{isBackgroundLog:!0}:{}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(v,r)}serializeStepResult(e,t,n,r){let i={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(i,r)}serializeUnifiedResult(e,t,n,r){let i=d({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=u(e.body,l.PARTIAL,!0),c=u(t.body,l.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,c,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=`/`,_=e.url,v={};if(e.url)try{_=f(e.url,l.PARTIAL);let t=new URL(_);g=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let y={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:_,path:g,queryParams:v},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:m}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(y,r)}serializeProviderResult(e,t,n,r){let i=d({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=u(e.body,l.PARTIAL,!0),c=u(t.body,l.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,c,`download`),h,g=``,_=`/`,v={};if(e.url)try{h=f(e.url,l.PARTIAL);let t=new URL(h);g=t.hostname,_=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let y={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:h,hostname:g,path:_,queryParams:v},body:p},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:m}},metadata:{expirationTime:n}};return this.serializeAndLimit(y,r)}serializeAndLimit(e,t){if(r(e,t)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=de.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 fe.includes(i)||pe.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!a(e)){if(!o(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 _({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[b]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new y({resource:v(n),spanProcessors:[new ee(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:i,result:o}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:o.success,statusCode:o.statusCode,includeBackground:t.includeBackground}}),a(i.body)&&a(o.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,o);if(a(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(r(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}this.send(i,e),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=a(e.body)?void 0:i(e.body),r=a(t.body)?void 0:i(t.body);if(!(a(n)&&a(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(a(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),o=await this.send(e);n.push(o)}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 p({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 h({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=S.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 S.ZodError([{code:S.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},S.coerce.date()),W=S.object({logType:S.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:U,startTime:U,endTime:U.optional().nullable().transform(e=>e??void 0),durationMs:S.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:S.coerce.string(),projectSecureId:S.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:S.coerce.string().optional().nullable().transform(e=>e??void 0)}),G=W.extend({logType:S.literal(`action`),actionRunId:S.coerce.string(),actionId:S.coerce.string(),connectorKey:S.coerce.string(),connectorVersion:S.coerce.string(),connectorOwner:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:S.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),actionType:S.coerce.string().optional().nullable().transform(e=>e??void 0),mode:S.coerce.string().optional().nullable().transform(e=>e??void 0),category:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:S.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:S.coerce.string().optional().nullable().transform(e=>e??void 0),url:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:S.coerce.string().optional().nullable().transform(e=>e??void 0),authType:S.coerce.string().optional().nullable().transform(e=>e??void 0),authId:S.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:S.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:S.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:S.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:S.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:S.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:S.coerce.string().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:S.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:S.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:S.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:S.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:S.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:S.literal(`step`),actionRunId:S.coerce.string(),stepIndex:S.coerce.number(),stepId:S.coerce.string(),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),skipped:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),message:S.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:S.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:S.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:S.coerce.number().optional().nullable().transform(e=>e??void 0)}),q=W.extend({logType:S.literal(`unified`),requestId:S.coerce.string(),connectorKey:S.coerce.string(),connectorVersion:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:S.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),mode:S.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:S.coerce.string().optional().nullable().transform(e=>e??void 0),url:S.coerce.string().optional().nullable().transform(e=>e??void 0),path:S.coerce.string().optional().nullable().transform(e=>e??void 0),resource:S.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),service:S.coerce.string().optional().nullable().transform(e=>e??void 0),action:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:S.coerce.string().optional().nullable().transform(e=>e??void 0),authType:S.coerce.string().optional().nullable().transform(e=>e??void 0),authId:S.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:S.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:S.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:S.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:S.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:S.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:S.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:S.coerce.number().optional().nullable().transform(e=>e??void 0),provider:S.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:S.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),J=W.extend({logType:S.literal(`provider`),requestId:S.coerce.string(),id:S.coerce.string().optional().nullable().transform(e=>e??void 0),action:S.coerce.string(),mode:S.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:S.coerce.string(),originOwnerId:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:S.coerce.string().optional().nullable().transform(e=>e??void 0),url:S.coerce.string(),path:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:S.coerce.string(),connectorVersion:S.coerce.string().optional().nullable().transform(e=>e??void 0),resource:S.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),service:S.coerce.string().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),status:S.coerce.number().optional().nullable().transform(e=>e??void 0),provider:S.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:S.coerce.number().optional().nullable().transform(e=>e??void 0)}),Y=W.extend({logType:S.literal(`platform`),eventId:S.coerce.string(),eventType:S.coerce.string(),service:S.coerce.string(),userId:S.coerce.string().optional().nullable().transform(e=>e??void 0),action:S.coerce.string().optional().nullable().transform(e=>e??void 0),subAction:S.coerce.string().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:S.coerce.string().optional().nullable().transform(e=>e??void 0)}),me=S.discriminatedUnion(`logType`,[G,K,q,J]);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}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.#s()}async#s(){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){if(!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 r=this.buildPlatformLog(e,t);await this.send(`platform`,[r])}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,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,r,i){let a=this.#o(i);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r,engine:i}});let{dimensions:o,startTime:s,endTime:c,...l}=r,u={organizationId:e,projectSecureId:t,...l,...o&&o.length>0&&{dimensions:o.join(`,`)},...s&&{startTime:s.toISOString()},...c&&{endTime:c.toISOString()}},d=await a?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>n(e,!0)),p=[`success`,`isWorker`,`isBackground`,`skipped`];return{data:f.map(e=>{let t={...e};for(let e of p)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t})}}catch(e){return a?.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}),[]}}#c(e){return(this.#n??P)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#c(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.#l(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#l(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??te(),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},...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 x){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,me)}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 x?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},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 ne({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=e(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=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 g(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:o}=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:o}}});for(let t of e)a(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let s=o?.enabled&&this.#s?this.#s.sendActions(e,o).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([s,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}}}),a(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={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,o,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{logs:r}=resolveOlapOptions(n);r?.enabled&&this.#i&&await this.#i.sendPlatform(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}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(a(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 o=await this.#i?.getStep(e,t,n,r,i);if(a(o)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return o}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(a(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 o=await this.#i?.getProviderLog(e,t,n,r,i);if(a(o)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return o}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(a(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(a(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(a(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(a(i)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if(a(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}};export{R as AuthType,ClickHouseClient,P as DEFAULT_TOPIC_CLUSTER_MAP,N as Dimension,M as IntervalType,ce as LogType,$ as OlapClient,OlapClientManager,le as OrderBy,ue as OrderDirection,F as SourceType,L as StreamType,I as TransportType,createConfigFromEnv,createOlapQueryClient,hasErrorEntries};
618
+ `,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{e(this,`SchemaValidationError`)}constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,n){this.#t=e,this.#n=n,e?.url&&(this.#e=t({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){try{let t=await this.#a(e.endpoint,e.params);return this.#i(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError$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.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 M={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),ce={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},le={Asc:`asc`,Desc:`desc`},ue={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`},N={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`},P={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===M.Platform,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`},I={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},L={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},R={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},z=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],B=[F.Scheduler,F.DataSync,F.DataSyncV2,F.Internal],V=[`data_sync`],H=[F.DataSync,F.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&z.includes(e)||t&&B.includes(t))}function isDataSync(e,t){return!!(e&&V.includes(e)||t&&H.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},hasErrorEntries=e=>a(e)?!1:Array.isArray(e)||o(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,de=[`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`],fe=[`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`],pe=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=n}async initialize(){if(!this.#e){this.#r?.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}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:`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.#r?.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.#r?.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.#r?.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.#r?.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?.ttl),a=await this.send(e,t?.ttl);n.push(a)}return n}async sendStep(e,t,n){if(this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#r?.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.#r?.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.#r?.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?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#r?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#r?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#r?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#r?.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.#r?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new p({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),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:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#r?.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.#r?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new p({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.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.#r?.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.#r?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new p({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#r?.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.#r?.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.#r?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new p({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#r?.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.#r?.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.#r?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#r?.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.#r?.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 h({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#r?.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.#r?.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 m({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#r?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#r?.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.#r?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;this.#r?.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.#r?.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.#r?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new p({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#r?.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.#r?.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.#r?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#r?.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??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n){let i=platformKey(e.organizationId,e.eventId),a=Math.floor(Date.now()/1e3)+(n??30)*24*60*60,o={Key:i,ContentType:`application/json`,Expires:new Date(a*1e3)},s={...t.metadata,expirationTime:a},c={data:u(t.data,l.PARTIAL,!0),metadata:s},d=JSON.stringify(c);if(!r(d,this.#n))return{...o,Body:d};this.#r?.warning({message:`Platform advanced payload exceeds maximum size, dropping data for eventId ${e.eventId}`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadTooLarge`});let f={data:{note:`Payload exceeded the maximum advanced log size and was dropped`},metadata:s};return{...o,Body:JSON.stringify(f)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#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??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=d({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=u(e.body,l.PARTIAL,!0),c=u(t.body,l.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,c,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=e.url,_={};if(e.url)try{g=f(e.url,l.PARTIAL);let t=new URL(g);_=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let v={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:g,path:e.pathParams,queryParams:_},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:m},...h?{isBackgroundLog:!0}:{}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(v,r)}serializeStepResult(e,t,n,r){let i={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(i,r)}serializeUnifiedResult(e,t,n,r){let i=d({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=u(e.body,l.PARTIAL,!0),c=u(t.body,l.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,c,`download`),h=e.isBackground??isBackgroundLog(e.mode,e.sourceType),g=`/`,_=e.url,v={};if(e.url)try{_=f(e.url,l.PARTIAL);let t=new URL(_);g=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let y={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:_,path:g,queryParams:v},body:p},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:m}},metadata:{...h?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(y,r)}serializeProviderResult(e,t,n,r){let i=d({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},l.PARTIAL),a=i.req?.headers,o=i.res?.headers,s=u(e.body,l.PARTIAL,!0),c=u(t.body,l.PARTIAL,!0),p=this.processContent(a,s,`upload`),m=this.processContent(o,c,`download`),h,g=``,_=`/`,v={};if(e.url)try{h=f(e.url,l.PARTIAL);let t=new URL(h);g=t.hostname,_=t.pathname,v=Object.fromEntries(t.searchParams)}catch{this.#r?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let y={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:h,hostname:g,path:_,queryParams:v},body:p},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:m}},metadata:{expirationTime:n}};return this.serializeAndLimit(y,r)}serializeAndLimit(e,t){if(r(e,t)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=de.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 fe.includes(i)||pe.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!a(e)){if(!o(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 _({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[b]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new y({resource:v(n),spanProcessors:[new ee(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:i,result:o}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:o.success,statusCode:o.statusCode,includeBackground:t.includeBackground}}),a(i.body)&&a(o.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,o);if(a(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(r(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}this.send(i,e),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=a(e.body)?void 0:i(e.body),r=a(t.body)?void 0:i(t.body);if(!(a(n)&&a(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(a(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),o=await this.send(e);n.push(o)}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 p({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 h({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=S.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 S.ZodError([{code:S.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},S.coerce.date()),W=S.object({logType:S.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:U,startTime:U,endTime:U.optional().nullable().transform(e=>e??void 0),durationMs:S.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:S.coerce.string(),projectSecureId:S.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:S.coerce.string().optional().nullable().transform(e=>e??void 0)}),G=W.extend({logType:S.literal(`action`),actionRunId:S.coerce.string(),actionId:S.coerce.string(),connectorKey:S.coerce.string(),connectorVersion:S.coerce.string(),connectorOwner:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:S.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),actionType:S.coerce.string().optional().nullable().transform(e=>e??void 0),mode:S.coerce.string().optional().nullable().transform(e=>e??void 0),category:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:S.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:S.coerce.string().optional().nullable().transform(e=>e??void 0),url:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:S.coerce.string().optional().nullable().transform(e=>e??void 0),authType:S.coerce.string().optional().nullable().transform(e=>e??void 0),authId:S.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:S.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:S.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:S.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:S.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:S.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:S.coerce.string().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:S.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:S.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:S.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:S.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:S.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:S.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:S.literal(`step`),actionRunId:S.coerce.string(),stepIndex:S.coerce.number(),stepId:S.coerce.string(),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),skipped:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),message:S.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:S.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:S.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:S.coerce.number().optional().nullable().transform(e=>e??void 0)}),q=W.extend({logType:S.literal(`unified`),requestId:S.coerce.string(),connectorKey:S.coerce.string(),connectorVersion:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:S.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),mode:S.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:S.coerce.string().optional().nullable().transform(e=>e??void 0),url:S.coerce.string().optional().nullable().transform(e=>e??void 0),path:S.coerce.string().optional().nullable().transform(e=>e??void 0),resource:S.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),service:S.coerce.string().optional().nullable().transform(e=>e??void 0),action:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:S.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:S.coerce.string().optional().nullable().transform(e=>e??void 0),authType:S.coerce.string().optional().nullable().transform(e=>e??void 0),authId:S.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:S.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:S.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:S.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:S.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:S.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:S.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:S.coerce.number().optional().nullable().transform(e=>e??void 0),provider:S.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:S.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:U.optional().nullable().transform(e=>e??void 0)}),J=W.extend({logType:S.literal(`provider`),requestId:S.coerce.string(),id:S.coerce.string().optional().nullable().transform(e=>e??void 0),action:S.coerce.string(),mode:S.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:S.coerce.string(),originOwnerId:S.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:S.coerce.string().optional().nullable().transform(e=>e??void 0),url:S.coerce.string(),path:S.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:S.coerce.string(),connectorVersion:S.coerce.string().optional().nullable().transform(e=>e??void 0),resource:S.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:S.coerce.string().optional().nullable().transform(e=>e??void 0),service:S.coerce.string().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:S.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:S.coerce.string(),accountSecureId:S.coerce.string(),status:S.coerce.number().optional().nullable().transform(e=>e??void 0),provider:S.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:U.optional().nullable().transform(e=>e??void 0),duration:S.coerce.number().optional().nullable().transform(e=>e??void 0)}),Y=W.extend({logType:S.literal(`platform`),eventId:S.coerce.string(),eventType:S.coerce.string(),service:S.coerce.string(),userId:S.coerce.string().optional().nullable().transform(e=>e??void 0),action:S.coerce.string().optional().nullable().transform(e=>e??void 0),subAction:S.coerce.string().optional().nullable().transform(e=>e??void 0),success:S.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:S.coerce.string().optional().nullable().transform(e=>e??void 0)}),me=S.discriminatedUnion(`logType`,[G,K,q,J]);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}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.#s()}async#s(){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,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,r,i){let a=this.#o(i);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r,engine:i}});let{dimensions:o,startTime:s,endTime:c,...l}=r,u={organizationId:e,projectSecureId:t,...l,...o&&o.length>0&&{dimensions:o.join(`,`)},...s&&{startTime:s.toISOString()},...c&&{endTime:c.toISOString()}},d=await a?.query({endpoint:`project_logs_aggregation.json`,params:u});if(!d)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>n(e,!0)),p=[`success`,`isWorker`,`isBackground`,`skipped`];return{data:f.map(e=>{let t={...e};for(let e of p)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t})}}catch(e){return a?.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}),[]}}#c(e){return(this.#n??P)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#c(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.#l(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#l(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??te(),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},...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 x){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,me)}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 x?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},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 ne({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=e(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=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 g(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:o}=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:o}}});for(let t of e)a(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let s=o?.enabled&&this.#s?this.#s.sendActions(e,o).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([s,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}}}),a(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let o={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,o,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(a(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 o=await this.#i?.getStep(e,t,n,r,i);if(a(o)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return o}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(a(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 o=await this.#i?.getProviderLog(e,t,n,r,i);if(a(o)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return o}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(a(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(a(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(a(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(a(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(a(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(a(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}};export{R as AuthType,ClickHouseClient,P as DEFAULT_TOPIC_CLUSTER_MAP,N as Dimension,ue as IntervalType,M as LogType,$ as OlapClient,OlapClientManager,ce as OrderBy,le as OrderDirection,F as SourceType,L as StreamType,I as TransportType,createConfigFromEnv,createOlapQueryClient,hasErrorEntries};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/olap",
3
- "version": "1.62.0",
3
+ "version": "1.64.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",