@stackone/olap 1.72.1 → 1.73.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 +27 -125
- package/dist/index.d.cts +91 -15
- package/dist/index.d.mts +91 -15
- package/dist/index.mjs +27 -125
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,117 +1,16 @@
|
|
|
1
|
-
import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhouse/client";import{calculateSize as n,convertKeysToCamelCase as r,exceedsSize as i,extractSchema as a,isDate as o,isMissing as s,isObject as c,isString as l,snakeToCamel as u}from"@stackone/utils";import d from"node:http";import{CensorType as f,redactFields as p,redactObject as m,redactUrl as h,scrubObjectAsync as g}from"@stackone/redaction";import{GetObjectCommand as _,HeadObjectCommand as ee,PutObjectCommand as v,S3Client as
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
organizationId,
|
|
8
|
-
projectSecureId,
|
|
9
|
-
accountSecureId,
|
|
10
|
-
actionRunId,
|
|
11
|
-
actionId,
|
|
12
|
-
connectorKey,
|
|
13
|
-
connectorVersion,
|
|
14
|
-
connectorOwner,
|
|
15
|
-
connectorProfileId,
|
|
16
|
-
actionType,
|
|
17
|
-
mode,
|
|
18
|
-
category,
|
|
19
|
-
originOwnerId,
|
|
20
|
-
originOwnerName,
|
|
21
|
-
httpMethod,
|
|
22
|
-
url,
|
|
23
|
-
sourceType,
|
|
24
|
-
sourceId,
|
|
25
|
-
sourceValue,
|
|
26
|
-
authType,
|
|
27
|
-
authId,
|
|
28
|
-
userAgent,
|
|
29
|
-
ipAddress,
|
|
30
|
-
sessionId,
|
|
31
|
-
agentId,
|
|
32
|
-
transportType,
|
|
33
|
-
streamType,
|
|
34
|
-
isBackground,
|
|
35
|
-
success,
|
|
36
|
-
statusCode,
|
|
37
|
-
riskLevel,
|
|
38
|
-
tier2Score,
|
|
39
|
-
advancedExpiresAt,
|
|
40
|
-
defenderExpiresAt,
|
|
41
|
-
message,
|
|
42
|
-
'action' as logType
|
|
43
|
-
FROM actions
|
|
44
|
-
WHERE 1=1
|
|
45
|
-
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
46
|
-
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
47
|
-
AND ({actionRunId:Array(String)} = [] OR actionRunId IN {actionRunId:Array(String)})
|
|
48
|
-
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
49
|
-
AND ({actionId:Array(String)} = [] OR actionId IN {actionId:Array(String)})
|
|
50
|
-
AND ({connectorKey:Array(String)} = [] OR connectorKey IN {connectorKey:Array(String)})
|
|
51
|
-
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
52
|
-
AND ({connectorOwner:Array(String)} = [] OR connectorOwner IN {connectorOwner:Array(String)})
|
|
53
|
-
AND ({connectorProfileId:Array(String)} = [] OR connectorProfileId IN {connectorProfileId:Array(String)})
|
|
54
|
-
AND ({actionType:Array(String)} = [] OR actionType IN {actionType:Array(String)})
|
|
55
|
-
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
56
|
-
AND ({category:Array(String)} = [] OR category IN {category:Array(String)})
|
|
57
|
-
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
58
|
-
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
59
|
-
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
60
|
-
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
61
|
-
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
62
|
-
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
63
|
-
AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
|
|
64
|
-
AND ({authId:Array(String)} = [] OR authId IN {authId:Array(String)})
|
|
65
|
-
AND ({userAgent:Array(String)} = [] OR userAgent IN {userAgent:Array(String)})
|
|
66
|
-
AND ({ipAddress:Array(String)} = [] OR ipAddress IN {ipAddress:Array(String)})
|
|
67
|
-
AND ({sessionId:Array(String)} = [] OR sessionId IN {sessionId:Array(String)})
|
|
68
|
-
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
69
|
-
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
70
|
-
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
71
|
-
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
72
|
-
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
73
|
-
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
74
|
-
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
75
|
-
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
76
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,se,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
1
|
+
import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhouse/client";import{calculateSize as n,convertKeysToCamelCase as r,exceedsSize as i,extractSchema as a,isDate as o,isMissing as s,isObject as c,isString as l,snakeToCamel as u}from"@stackone/utils";import d from"node:http";import{CensorType as f,redactFields as p,redactObject as m,redactUrl as h,scrubObjectAsync as g}from"@stackone/redaction";import{GetObjectCommand as _,HeadObjectCommand as ee,PutObjectCommand as v,S3Client as te}from"@aws-sdk/client-s3";import{OTLPTraceExporter as ne}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as re}from"@opentelemetry/resources";import{BasicTracerProvider as ie,BatchSpanProcessor as ae}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as oe}from"@opentelemetry/semantic-conventions";import{randomUUID as y}from"crypto";import{ZodError as b,z as x}from"zod";import{HttpClient as se}from"@stackone/transport";const S=new Map;function registerQuery(e){S.set(e.id,e)}function getQueryDefinition(e){return S.get(e)}function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toStatusCodes(e){let t=toArray(e);if(t.length===0)return[];let n=t.map(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length===0?NaN:Number(t)}).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return n.length>0?n:[-1]}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}const C={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},w=`action_logs_filtered`,T=`organizationId.projectSecureId.actionRunId.accountSecureId.actionId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.actionType.mode.category.originOwnerId.originOwnerName.httpMethod.sourceType.sourceId.sourceValue.authType.authId.userAgent.ipAddress.sessionId.agentId.transportType.streamType.policyResult.riskLevel`.split(`.`),E=[...T.map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),D=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
|
|
2
|
+
AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(T.map(t=>[t,toArray(e[t])])),statusCode:toStatusCodes(e.statusCode),isBackground:toNullableFlag(e.isBackground),success:toNullableFlag(e.success),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}),buildActionLogsQuery=e=>{let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
3
|
+
SELECT *
|
|
4
|
+
FROM ${w}(${E})
|
|
5
|
+
${D}
|
|
6
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,C,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
77
7
|
LIMIT {limit:UInt32}
|
|
78
8
|
OFFSET {offset:UInt32}
|
|
79
|
-
`,params:{
|
|
9
|
+
`,params:{...buildViewParams(e),limit:t,offset:n}}},buildActionLogsCountQuery=e=>({sql:`
|
|
80
10
|
SELECT count() as total
|
|
81
|
-
FROM
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
85
|
-
AND ({actionRunId:Array(String)} = [] OR actionRunId IN {actionRunId:Array(String)})
|
|
86
|
-
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
87
|
-
AND ({actionId:Array(String)} = [] OR actionId IN {actionId:Array(String)})
|
|
88
|
-
AND ({connectorKey:Array(String)} = [] OR connectorKey IN {connectorKey:Array(String)})
|
|
89
|
-
AND ({connectorVersion:Array(String)} = [] OR connectorVersion IN {connectorVersion:Array(String)})
|
|
90
|
-
AND ({connectorOwner:Array(String)} = [] OR connectorOwner IN {connectorOwner:Array(String)})
|
|
91
|
-
AND ({connectorProfileId:Array(String)} = [] OR connectorProfileId IN {connectorProfileId:Array(String)})
|
|
92
|
-
AND ({actionType:Array(String)} = [] OR actionType IN {actionType:Array(String)})
|
|
93
|
-
AND ({mode:Array(String)} = [] OR mode IN {mode:Array(String)})
|
|
94
|
-
AND ({category:Array(String)} = [] OR category IN {category:Array(String)})
|
|
95
|
-
AND ({originOwnerId:Array(String)} = [] OR originOwnerId IN {originOwnerId:Array(String)})
|
|
96
|
-
AND ({originOwnerName:Array(String)} = [] OR originOwnerName IN {originOwnerName:Array(String)})
|
|
97
|
-
AND ({httpMethod:Array(String)} = [] OR httpMethod IN {httpMethod:Array(String)})
|
|
98
|
-
AND ({sourceType:Array(String)} = [] OR sourceType IN {sourceType:Array(String)})
|
|
99
|
-
AND ({sourceId:Array(String)} = [] OR sourceId IN {sourceId:Array(String)})
|
|
100
|
-
AND ({sourceValue:Array(String)} = [] OR sourceValue IN {sourceValue:Array(String)})
|
|
101
|
-
AND ({authType:Array(String)} = [] OR authType IN {authType:Array(String)})
|
|
102
|
-
AND ({authId:Array(String)} = [] OR authId IN {authId:Array(String)})
|
|
103
|
-
AND ({userAgent:Array(String)} = [] OR userAgent IN {userAgent:Array(String)})
|
|
104
|
-
AND ({ipAddress:Array(String)} = [] OR ipAddress IN {ipAddress:Array(String)})
|
|
105
|
-
AND ({sessionId:Array(String)} = [] OR sessionId IN {sessionId:Array(String)})
|
|
106
|
-
AND ({agentId:Array(String)} = [] OR agentId IN {agentId:Array(String)})
|
|
107
|
-
AND ({transportType:Array(String)} = [] OR transportType IN {transportType:Array(String)})
|
|
108
|
-
AND ({streamType:Array(String)} = [] OR streamType IN {streamType:Array(String)})
|
|
109
|
-
AND ({statusCode:Array(Int16)} = [] OR statusCode IN {statusCode:Array(Int16)})
|
|
110
|
-
AND ({isBackground:Nullable(UInt8)} IS NULL OR isBackground = {isBackground:Nullable(UInt8)})
|
|
111
|
-
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
112
|
-
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
113
|
-
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
114
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),actionRunId:toArray(e.actionRunId),accountSecureId:toArray(e.accountSecureId),actionId:toArray(e.actionId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),actionType:toArray(e.actionType),mode:toArray(e.mode),category:toArray(e.category),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),httpMethod:toArray(e.httpMethod),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_action_logs.json`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery});const w={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
11
|
+
FROM ${w}(${E})
|
|
12
|
+
${D}
|
|
13
|
+
`,params:buildViewParams(e)});registerQuery({id:`project_action_logs.json`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery});const ce={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
115
14
|
SELECT
|
|
116
15
|
eventTime,
|
|
117
16
|
startTime,
|
|
@@ -142,7 +41,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
142
41
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
143
42
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
144
43
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
145
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
44
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,ce,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
146
45
|
LIMIT {limit:UInt32}
|
|
147
46
|
OFFSET {offset:UInt32}
|
|
148
47
|
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildStepLogsCountQuery(e){return{sql:`
|
|
@@ -158,7 +57,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
158
57
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
159
58
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
160
59
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
161
|
-
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_step_logs.json`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery});const
|
|
60
|
+
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}registerQuery({id:`project_step_logs.json`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery});const le={startTime:`startTime`,endTime:`endTime`,eventTime:`eventDatetime`,durationMs:`duration`};function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
162
61
|
SELECT
|
|
163
62
|
eventDatetime as eventTime,
|
|
164
63
|
startTime,
|
|
@@ -236,7 +135,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
236
135
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
237
136
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
238
137
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
239
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
138
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,le,`eventDatetime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
240
139
|
LIMIT {limit:UInt32}
|
|
241
140
|
OFFSET {offset:UInt32}
|
|
242
141
|
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toArray(e.statusCode).map(e=>typeof e==`string`?Number.parseInt(e,10):e),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildUnifiedLogsCountQuery(e){return{sql:`
|
|
@@ -276,7 +175,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
276
175
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
277
176
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
278
177
|
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
|
|
178
|
+
`,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 ue={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},de=[`requestId`,`resource`,`service`,`subResource`,`childResource`,`action`,`path`,`accountId`,`status`],fe=[`actionRunId`,`actionId`,`actionType`,`category`,`riskLevel`,`policyResult`],hasAnyFilter=(e,t)=>{let n=e;return t.some(e=>n[e]!==void 0)},untypedFilter=(e,t)=>e[t],toInt16Filter=e=>{let t=toArray(e),n=t.map(e=>typeof e==`string`&&e.trim()===``?NaN:Number(e)).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return{values:n,unsatisfiable:t.length>0&&n.length===0}},hasUnsatisfiableFilter=e=>toInt16Filter(e.statusCode).unsatisfiable||toInt16Filter(untypedFilter(e,`status`)).unsatisfiable;function shouldIncludeUnified(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`unified`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,fe)}function shouldIncludeActions(e){let t=toArray(e.logType);return t.length>0&&!t.includes(`action`)||hasUnsatisfiableFilter(e)?!1:!hasAnyFilter(e,de)}function buildUnifiedFilters(){return`
|
|
280
179
|
AND ({organizationId:Array(String)} = [] OR organizationId IN {organizationId:Array(String)})
|
|
281
180
|
AND ({projectSecureId:Array(String)} = [] OR projectSecureId IN {projectSecureId:Array(String)})
|
|
282
181
|
AND ({accountSecureId:Array(String)} = [] OR accountSecureId IN {accountSecureId:Array(String)})
|
|
@@ -332,6 +231,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
332
231
|
AND ${buildArrayFilter(`actionType`,`actionType`)}
|
|
333
232
|
AND ${buildArrayFilter(`category`,`category`)}
|
|
334
233
|
AND ${buildArrayFilter(`riskLevel`,`riskLevel`)}
|
|
234
|
+
AND ${buildArrayFilter(`policyResult`,`policyResult`)}
|
|
335
235
|
`.trim()}function buildUnifiedSelect(){return`
|
|
336
236
|
SELECT
|
|
337
237
|
eventDatetime as eventTime,
|
|
@@ -385,6 +285,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
385
285
|
statusCode,
|
|
386
286
|
CAST(NULL AS Nullable(String)) as message,
|
|
387
287
|
CAST(NULL AS Nullable(String)) as riskLevel,
|
|
288
|
+
CAST(NULL AS Nullable(String)) as policyResult,
|
|
388
289
|
CAST(NULL AS Nullable(Float32)) as tier2Score,
|
|
389
290
|
'unified' as logType
|
|
390
291
|
FROM unified_requests
|
|
@@ -445,6 +346,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
445
346
|
statusCode,
|
|
446
347
|
message,
|
|
447
348
|
riskLevel,
|
|
349
|
+
policyResult,
|
|
448
350
|
tier2Score,
|
|
449
351
|
'action' as logType
|
|
450
352
|
FROM actions
|
|
@@ -452,7 +354,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
452
354
|
${buildActionsFilters()}
|
|
453
355
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
454
356
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
455
|
-
`}function buildCombinedSourceSql(e){let t=[shouldIncludeUnified(e)?buildUnifiedSelect():void 0,shouldIncludeActions(e)?buildActionsSelect():void 0].filter(e=>e!==void 0);return t.length===0?`${buildUnifiedSelect()} AND 1 = 0`:t.join(` UNION ALL `)}function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toInt16Filter(e.statusCode).values,isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),status:toInt16Filter(untypedFilter(e,`status`)).values}}function buildCombinedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,
|
|
357
|
+
`}function buildCombinedSourceSql(e){let t=[shouldIncludeUnified(e)?buildUnifiedSelect():void 0,shouldIncludeActions(e)?buildActionsSelect():void 0].filter(e=>e!==void 0);return t.length===0?`${buildUnifiedSelect()} AND 1 = 0`:t.join(` UNION ALL `)}function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toInt16Filter(e.statusCode).values,isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),policyResult:toArray(untypedFilter(e,`policyResult`)),status:toInt16Filter(untypedFilter(e,`status`)).values}}function buildCombinedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,ue,`eventTime`),i=sanitizeOrderDirection(e.orderDirection);return{sql:`
|
|
456
358
|
WITH combined AS (
|
|
457
359
|
${buildCombinedSourceSql(e)}
|
|
458
360
|
)
|
|
@@ -474,7 +376,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
474
376
|
${buildActionsFilters()}
|
|
475
377
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
476
378
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
477
|
-
`),{sql:t.length>0?`SELECT sum(cnt) as total FROM (${t.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const
|
|
379
|
+
`),{sql:t.length>0?`SELECT sum(cnt) as total FROM (${t.join(` UNION ALL `)})`:`SELECT 0 as total`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs.json`,buildQuery:buildCombinedLogsQuery,buildCountQuery:buildCombinedLogsCountQuery});const O={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},k=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`,`authType`,`authId`,`policyResult`,`riskLevel`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(u),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(O,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildCombinedSourceSql(e);return{sql:r.map(e=>{let t=O[e];return`
|
|
478
380
|
SELECT
|
|
479
381
|
'${e}' as dimension,
|
|
480
382
|
arrayReverseSort(
|
|
@@ -489,14 +391,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
489
391
|
${i}
|
|
490
392
|
) AS combined
|
|
491
393
|
WHERE ${t} IS NOT NULL
|
|
492
|
-
${
|
|
394
|
+
${k.has(e)?`AND ${t} != ''`:``}
|
|
493
395
|
GROUP BY ${t}
|
|
494
396
|
ORDER BY count DESC
|
|
495
397
|
LIMIT {maxValues:UInt32}
|
|
496
398
|
) AS facets
|
|
497
399
|
`}).join(`
|
|
498
400
|
UNION ALL
|
|
499
|
-
`),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||!
|
|
401
|
+
`),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||!k.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=`
|
|
500
402
|
WITH combined AS (
|
|
501
403
|
${buildCombinedSourceSql(e)}
|
|
502
404
|
)
|
|
@@ -504,7 +406,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
504
406
|
WHERE ${t} IN {entityIds:Array(String)}
|
|
505
407
|
ORDER BY eventTime DESC
|
|
506
408
|
LIMIT 1 BY ${t}
|
|
507
|
-
`,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
|
|
409
|
+
`,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 A={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),pe={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},me={Asc:`asc`,Desc:`desc`},j={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},he={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},M={actions:[`external`],steps:[`external`],unified_requests:[`external`],provider_requests:[`external`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===A.Platform,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`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},P={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},F={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(P,e)?P[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(F,e)?F[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=toCsvArray(e.dimensions).map(u),n=e.intervalType??`hour`,r=Math.floor(Number(e.intervalPeriod??1)),i=Number.isFinite(r)&&r>0?r:1,a=t.filter(e=>Object.prototype.hasOwnProperty.call(N,e)).map(e=>N[e]),o=n===j.None?void 0:buildTimeBucket(n,i),s=[...o?[`${o} as startTime`]:[],`count() as count`,...a].join(`, `),c=[...o?[`startTime`]:[],...a],l=c.length>0?`GROUP BY ${c.join(`, `)}`:``,d=o?`ORDER BY startTime ASC`:``;return{sql:`
|
|
508
410
|
WITH combined AS (
|
|
509
411
|
${buildCombinedSourceSql(e)}
|
|
510
412
|
)
|
|
@@ -513,7 +415,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
513
415
|
FROM combined
|
|
514
416
|
${l}
|
|
515
417
|
${d}
|
|
516
|
-
`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const
|
|
418
|
+
`,params:buildCommonLogParams(e)}}registerQuery({id:`project_logs_aggregation.json`,buildQuery:buildAggregationQuery});const I={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
517
419
|
SELECT
|
|
518
420
|
eventDatetime as eventTime,
|
|
519
421
|
startTime,
|
|
@@ -563,7 +465,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
563
465
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
564
466
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
565
467
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
566
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
468
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,I,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
567
469
|
LIMIT {limit:UInt32}
|
|
568
470
|
OFFSET {offset:UInt32}
|
|
569
471
|
`,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:`
|
|
@@ -578,7 +480,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
578
480
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
579
481
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime >= {startTime:Nullable(DateTime64(3))})
|
|
580
482
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventDatetime <= {endTime:Nullable(DateTime64(3))})
|
|
581
|
-
`,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
|
|
483
|
+
`,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 L={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
|
|
582
484
|
SELECT
|
|
583
485
|
eventTime,
|
|
584
486
|
startTime,
|
|
@@ -636,7 +538,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
636
538
|
AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
|
|
637
539
|
AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
|
|
638
540
|
AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
|
|
639
|
-
ORDER BY ${sanitizeOrderBy(e.orderBy,
|
|
541
|
+
ORDER BY ${sanitizeOrderBy(e.orderBy,L,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
|
|
640
542
|
LIMIT {limit:UInt32}
|
|
641
543
|
OFFSET {offset:UInt32}
|
|
642
544
|
`,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildPlatformLogsCountQuery(e){return{sql:`
|
|
@@ -685,4 +587,4 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{createClient as t}from"@clickhou
|
|
|
685
587
|
AND sourceId != ''
|
|
686
588
|
GROUP BY sourceId, sourceType
|
|
687
589
|
ORDER BY request_count DESC
|
|
688
|
-
`,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 d.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};function createOlapQueryClient(e,t,n){switch(e.type){case`clickhouse`:if(!e.clickhouse)throw Error(`ClickHouse config required when type is "clickhouse"`);return new ClickHouseClient(e.clickhouse,n);default:return new TinybirdClient(t,e.tinybird,n)}}function createConfigFromEnv(){let e=process.env.TINYBIRD_BASE_URL,t=process.env.TINYBIRD_TOKEN,n=e&&t?{baseUrl:e,token:t,allowHttp:process.env.TINYBIRD_ALLOW_HTTP===`true`}:void 0,r=process.env.CLICKHOUSE_URL,i=r?{url:r,username:process.env.CLICKHOUSE_USER,password:process.env.CLICKHOUSE_PASSWORD,database:process.env.CLICKHOUSE_DATABASE??`olap`,requestTimeout:(()=>{if(!process.env.CLICKHOUSE_TIMEOUT)return;let e=Number.parseInt(process.env.CLICKHOUSE_TIMEOUT,10);return Number.isFinite(e)?e:void 0})()}:void 0;return{type:n?`tinybird`:i?`clickhouse`:`tinybird`,tinybird:n,clickhouse:i}}const F={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},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`},he=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],ge=[F.Scheduler,F.DataSync,F.DataSyncV2,F.Internal],_e=[`data_sync`],ve=[F.DataSync,F.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&he.includes(e)||t&&ge.includes(t))}function isDataSync(e,t){return!!(e&&_e.includes(e)||t&&ve.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>s(e)?!1:Array.isArray(e)||l(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,z=64*1024,B=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],V=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>c(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return c(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+n(r);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,r):e},fitObject=(e,t)=>{let r=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+n(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let r=n(e);return r<=t?e:(l(e)||Array.isArray(e)||c(e)&&!o(e))&&t<=0?marker(r):l(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):c(e)&&!o(e)?fitObject(e,t):e},payloadFields=e=>B.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!s(e)).map(e=>({...e,size:n(e.value)})),byRetentionPriority=e=>[...e.filter(e=>V.includes(e.path)),...e.filter(e=>!V.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*z;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(z,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>B.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),ye=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],be=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],xe=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed, content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`,error:e})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&n(e)>this.#n)return e;try{return await g(e,this.#a)}catch(t){return this.#i?.warning({message:`PII content scrub failed, storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`,error:t}),e}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e={...r,body:await this.scrubPii(p(r.body,f.PARTIAL,!0),t)},a={...i,body:await this.scrubPii(p(i.body,f.PARTIAL,!0),t)},o=this.createActionS3(e,a,t),s=await this.send(o,t?.ttl);n.push(s)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r={...e,inputs:await this.scrubPii(p(e.inputs,f.PARTIAL,!0),n)},i={...t,outputs:await this.scrubPii(p(t.outputs,f.PARTIAL,!0),n),errors:await this.scrubPii(p(t.errors,f.PARTIAL,!0),n)},a=this.createStepS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(p(e.body,f.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(p(t.body,f.PARTIAL,!0),n)},a=this.createUnifiedS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(p(e.body,f.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(p(t.body,f.PARTIAL,!0),n)},a=this.createProviderS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new _({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new _({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new _({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new _({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new v({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new ee({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new _({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{Key:i,ContentType:`application/json`,Expires:new Date(a*1e3),Body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let r=p(e.data,f.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:n(r)};return this.stringifyPlatform({data:r,metadata:i},i)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=e.url,p={};if(e.url)try{d=h(e.url,f.PARTIAL);let t=new URL(d);p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let g={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:d,path:e.pathParams,queryParams:p},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l},...u?{isBackgroundLog:!0}:{}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=`/`,p=e.url,g={};if(e.url)try{p=h(e.url,f.PARTIAL);let t=new URL(p);d=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let _={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:p,path:d,queryParams:g},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u,d=``,p=`/`,g={};if(e.url)try{u=h(e.url,f.PARTIAL);let t=new URL(u);d=t.hostname,p=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let _={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:u,hostname:d,path:p,queryParams:g},body:c},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeAndLimit(e,t,r,i){let a=n(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?t*this.#r:t;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=ye.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return be.includes(i)||xe.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!s(e)){if(!l(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new te({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[ae]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new re({resource:ne(n),spanProcessors:[new ie(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),s(r.body)&&s(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,a);if(s(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(i(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=s(e.body)?void 0:a(e.body),r=s(t.body)?void 0:a(t.body);if(!(s(n)&&s(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(s(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new _({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new v({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},H=x.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 x.ZodError([{code:x.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},x.coerce.date()),U=x.object({logType:x.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:x.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:x.coerce.string(),projectSecureId:x.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:x.literal(`action`),actionRunId:x.coerce.string(),actionId:x.coerce.string(),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string(),connectorOwner:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:x.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),actionType:x.coerce.string().optional().nullable().transform(e=>e??void 0),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),category:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:x.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:x.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:x.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:x.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),G=U.extend({logType:x.literal(`step`),actionRunId:x.coerce.string(),stepIndex:x.coerce.number(),stepId:x.coerce.string(),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),skipped:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),message:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:x.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:x.literal(`unified`),requestId:x.coerce.string(),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:x.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string().optional().nullable().transform(e=>e??void 0),path:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),service:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:x.coerce.number().optional().nullable().transform(e=>e??void 0),provider:x.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:x.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:x.literal(`provider`),requestId:x.coerce.string(),id:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string(),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string(),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string(),path:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),service:x.coerce.string().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),status:x.coerce.number().optional().nullable().transform(e=>e??void 0),provider:x.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:x.coerce.number().optional().nullable().transform(e=>e??void 0)}),J=U.extend({logType:x.literal(`platform`),eventId:x.coerce.string(),eventType:x.coerce.string(),service:x.coerce.string(),organizationId:x.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:x.undefined(),userId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:x.record(x.unknown()).optional().nullable().transform(e=>e??void 0)}),Se=x.discriminatedUnion(`logType`,[W,G,K,q]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Y=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a;#o(e){if(e===`clickhouse`&&this.#i?.isReady())return this.#i;if(this.#r?.isReady())return this.#r;if(this.#i?.isReady())return this.#i}#s(){if(this.#i?.isReady())return this.#i;this.#a?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`})}constructor(e,t,n,r,i,a,o){this.#e=e,this.#t=a,this.#n=o,this.#a=r,n&&(this.#r=new TinybirdClient(t,n,r)),i&&(this.#i=new ClickHouseClient(i,r));let s=[];this.#r&&s.push(`tinybird`),this.#i&&s.push(`clickhouse`),s.length>0&&this.#a?.debug({message:`LogsSink initialized with query clients: ${s.join(`, `)}`,category:`LogsSink`})}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#a?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}let e=this.#r?.isReady()??!1,t=this.#i?.isReady()??!1;!e&&!t?this.#a?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}):this.#a?.info({message:`Logs sink query clients ready: tinybird=${e}, clickhouse=${t}`,category:`LogsSink`}),this.#a?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#c()}async#c(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#a?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#a?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#a?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#a?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#a?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} logs (${r.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(r.data),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#i;if(!r?.isReady())return this.#a?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#a?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#a?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#a?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} action logs (${r.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(r.data,W),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n,r){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n},r)).actionLogs[0]}async getSteps(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} step logs (${r.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(r.data,G),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r,i){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r},i)).stepLogs[0]}async getUnifiedLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} unified logs (${r.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(r.data,K),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n,r){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n},r)).unifiedLogs[0]}async getProviderLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} provider logs (${r.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(r.data,q),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e){let t=this.#s();try{this.#a?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#a?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,J),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}catch(n){return t?.isReady()?this.#a?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r,i){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r},i)).providerLogs[0]}async getAggregate(e,t,n,i){let a=this.#o(i);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n,engine:i}});let{dimensions:o,startTime:s,endTime:c,...l}=n,u=n.intervalType===O.None,d={organizationId:e,projectSecureId:t,...l,...o&&o.length>0&&{dimensions:o.join(`,`)},...s&&{startTime:s.toISOString()},...c&&{endTime:c.toISOString()},...u&&{pageSize:void 0,pageNumber:void 0}},f=await a?.query({endpoint:`project_logs_aggregation.json`,params:d});if(!f)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${f.length} aggregated data points`,category:`LogsSink`});let p=f.map(e=>r(e,!0)).map(e=>{let t={...e};for(let e of Y)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:u?foldTimeBuckets(p):p}}catch(e){return 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={};for(let e of d)Y.includes(e.dimension)?f[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):f[e.dimension]=e.values;return f}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n,engine:r}});let{startTime:a,endTime:o,sourceType:s}=n,c={organizationId:e,projectSecureId:t,...s&&{sourceType:Array.isArray(s)?s.join(`,`):s},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await i?.query({endpoint:`project_source_usage.json`,params:c});return l?(this.#a?.info({message:`Successfully retrieved ${l.length} source usage records`,category:`LogsSink`}),l.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#l(e){return(this.#n??k)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#l(e);if(!n)throw this.#a?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#a?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#a?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#a?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#u(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#u(e,t,n,r){if(!t)throw this.#a?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#a?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#a?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#a?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??oe(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof b){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#a?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,Se)}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 b?this.#a?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#a?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return W;case`step`:return G;case`unified`:return K;case`provider`:return q;case`platform`:return J}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!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 S({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 y(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)s(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}}}),s(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(s(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(s(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(s(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n,r){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#r?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getPlatformLogs(n)||(this.#r?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,n,r,i){let a=await this.#i?.getProviderLog(e,t,n,r,i);if(s(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(s(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(s(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(s(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(s(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(s(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(s(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,k as DEFAULT_TOPIC_CLUSTER_MAP,me as Dimension,O as IntervalType,D as LogType,$ as OlapClient,OlapClientManager,fe as OrderBy,pe as OrderDirection,F as SourceType,L as StreamType,I as TransportType,createConfigFromEnv,createOlapQueryClient,hasErrorEntries};
|
|
590
|
+
`,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 d.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 R={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`},ge={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},_e={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},ve={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},ye=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],be=[R.Scheduler,R.DataSync,R.DataSyncV2,R.Internal],xe=[`data_sync`],Se=[R.DataSync,R.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&ye.includes(e)||t&&be.includes(t))}function isDataSync(e,t){return!!(e&&xe.includes(e)||t&&Se.includes(t))}const safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>s(e)?!1:Array.isArray(e)||l(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,z=64*1024,B=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],V=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>c(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return c(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>t)return e;let i=e.total+n(r);return i>t?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>t?e.slice(0,r):e},fitObject=(e,t)=>{let r=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+n(t)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,t)=>{let r=n(e);return r<=t?e:(l(e)||Array.isArray(e)||c(e)&&!o(e))&&t<=0?marker(r):l(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):c(e)&&!o(e)?fitObject(e,t):e},payloadFields=e=>B.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!s(e)).map(e=>({...e,size:n(e.value)})),byRetentionPriority=e=>[...e.filter(e=>V.includes(e.path)),...e.filter(e=>!V.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*z;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(z,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>B.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),Ce=[`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`],we=[`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`],Te=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],platformKey=(e,t)=>`${e}/platform/${t}.json`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(!this.#e){this.#i?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed, content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`,error:e})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&n(e)>this.#n)return e;try{return await g(e,this.#a)}catch(t){return this.#i?.warning({message:`PII content scrub failed, storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`,error:t}),e}}requireBucket(){if(!this.#t)throw Error(`Advanced sink bucket is not configured`);return this.#t}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let e={...r,body:await this.scrubPii(p(r.body,f.PARTIAL,!0),t)},a={...i,body:await this.scrubPii(p(i.body,f.PARTIAL,!0),t)},o=this.createActionS3(e,a,t),s=await this.send(o,t?.ttl);n.push(s)}return n}async sendStep(e,t,n){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r={...e,inputs:await this.scrubPii(p(e.inputs,f.PARTIAL,!0),n)},i={...t,outputs:await this.scrubPii(p(t.outputs,f.PARTIAL,!0),n),errors:await this.scrubPii(p(t.errors,f.PARTIAL,!0),n)},a=this.createStepS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(p(e.body,f.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(p(t.body,f.PARTIAL,!0),n)},a=this.createUnifiedS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(p(e.body,f.PARTIAL,!0),n)},i={...t,body:await this.scrubPii(p(t.body,f.PARTIAL,!0),n)},a=this.createProviderS3(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new _({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new _({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=this.requireBucket();try{let i=new _({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#i?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=this.requireBucket();try{let a=new _({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#i?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e)throw Error(`No s3 client available, cannot send to advanced sink`);let n=this.requireBucket(),r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);this.#i?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:a.toISOString()}});try{return await this.#e.send(new v({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:a,Tagging:r})),{expiresAt:a}}catch(t){throw this.#i?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}async getObjectExpiry(e){if(!this.#e)return this.#i?.warning({message:`No s3 client available, cannot check object expiry`,category:`AdvancedSink`}),{exists:!1};let t=this.requireBucket();try{return{exists:!0,expiresAt:(await this.#e.send(new ee({Bucket:t,Key:e}))).Expires}}catch(t){let n=t;if(n.name===`NotFound`||n.$metadata?.httpStatusCode===404)return this.#i?.debug({message:`Object not found in S3 for key ${e}`,category:`AdvancedSink`}),{exists:!1};throw this.#i?.error({message:`Error when checking object expiry in S3 for key ${e}`,error:t,code:`AdvancedLogHeadError`,category:`AdvancedSink`}),t}}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformS3(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){if(!this.#e){this.#i?.warning({message:`No s3 client available, cannot get platform log from advanced sink`,category:`AdvancedSink`});return}let n=this.requireBucket();try{let r=new _({Bucket:n,Key:platformKey(e,t)}),i=await this.#e.send(r);if(!i.Body){this.#i?.warning({message:`Received empty body when trying to get platform log from S3 for eventId ${t}`,category:`AdvancedSink`});return}let a=await i.Body.transformToString();return this.#i?.debug({message:`Successfully retrieved platform advanced log from S3 for eventId ${t}`,category:`AdvancedSink`}),JSON.parse(a)}catch(e){let n=e;if(n.name===`NoSuchKey`||n.$metadata?.httpStatusCode===404){this.#i?.debug({message:`Platform advanced log not found in S3 for eventId ${t}`,category:`AdvancedSink`});return}throw this.#i?.error({message:`Error when getting platform advanced log from S3 for eventId ${t}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createPlatformS3(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{Key:i,ContentType:`application/json`,Expires:new Date(a*1e3),Body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,t){let r=p(e.data,f.PARTIAL,!0),i={...e.metadata,expirationTime:t,sizeBytes:n(r)};return this.stringifyPlatform({data:r,metadata:i},i)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n)),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=e.url,p={};if(e.url)try{d=h(e.url,f.PARTIAL);let t=new URL(d);p=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let g={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:d,path:e.pathParams,queryParams:p},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l},...u?{isBackgroundLog:!0}:{}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(g,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=`/`,p=e.url,g={};if(e.url)try{p=h(e.url,f.PARTIAL);let t=new URL(p);d=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let _={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:p,path:d,queryParams:g},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(s),body:l}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=m({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},f.PARTIAL),o=a.req?.headers,s=a.res?.headers,c=this.processContent(o,e.body,`upload`),l=this.processContent(s,t.body,`download`),u,d=``,p=`/`,g={};if(e.url)try{u=h(e.url,f.PARTIAL);let t=new URL(u);d=t.hostname,p=t.pathname,g=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let _={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(o),url:{url:u,hostname:d,path:p,queryParams:g},body:c},response:{statusCode:t.statusCode,headers:this.filterHeaders(s),body:l}},metadata:{expirationTime:n}};return this.serializeAndLimit(_,r,isErrorResult(t),i)}serializeAndLimit(e,t,r,i){let a=n(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?t*this.#r:t;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=Ce.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 we.includes(i)||Te.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!s(e)){if(!l(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};function defaultProviderFactory(e){let t=new ne({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`}}),n={[oe]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new ie({resource:re(n),spanProcessors:[new ae(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(this.#r)try{await this.#r.forceFlush()}catch(e){this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`})}}},DatasetsSink=class{#e;#t;#n;#r;#i;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),s(r.body)&&s(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,a);if(s(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(i(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=s(e.body)?void 0:a(e.body),r=s(t.body)?void 0:a(t.body);if(!(s(n)&&s(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}},DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Defender sink bucket is not configured`);return this.#t}async initialize(){if(!this.#e){this.#r?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`}),n.push(null);continue}if(s(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}}),n.push(null);continue}let e=this.createDefenderS3(r,i),a=await this.send(e);n.push(a)}return n}async getAction(e,t,n){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=this.requireBucket();try{let i=new _({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#r?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#r?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#r?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to defender sink`);let t=this.requireBucket(),n=Math.floor(Date.now()/1e3)+this.#n*24*60*60,r=new Date(n*1e3),i=`ttl=${this.#n}d`;this.#r?.debug({message:`Storing defender log in S3 bucket ${t} with ${this.#n}-day TTL`,category:`DefenderSink`,context:{bucket:t,key:e.Key,ttlTag:i,expiresAt:r.toISOString()}});try{return await this.#e.send(new v({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:r,Tagging:i})),{expiresAt:r}}catch(t){throw this.#r?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createDefenderS3(e,t){let n=e.organizationId,r=e.projectSecureId;return{Key:this.generateS3Key(n,r,e.actionRunId),Body:JSON.stringify(t.defenderContext),ContentType:`application/json`}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},H=x.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 x.ZodError([{code:x.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},x.coerce.date()),U=x.object({logType:x.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:x.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:x.coerce.string(),projectSecureId:x.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:x.literal(`action`),actionRunId:x.coerce.string(),actionId:x.coerce.string(),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string(),connectorOwner:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:x.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),actionType:x.coerce.string().optional().nullable().transform(e=>e??void 0),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),category:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:x.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:x.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:x.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:x.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:x.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:x.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),G=U.extend({logType:x.literal(`step`),actionRunId:x.coerce.string(),stepIndex:x.coerce.number(),stepId:x.coerce.string(),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),skipped:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),message:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:x.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:x.literal(`unified`),requestId:x.coerce.string(),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:x.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string().optional().nullable().transform(e=>e??void 0),path:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),service:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:x.coerce.number().optional().nullable().transform(e=>e??void 0),provider:x.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:x.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:x.literal(`provider`),requestId:x.coerce.string(),id:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string(),mode:x.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:x.coerce.string(),originOwnerId:x.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:x.coerce.string().optional().nullable().transform(e=>e??void 0),url:x.coerce.string(),path:x.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:x.coerce.string(),connectorVersion:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:x.coerce.string().optional().nullable().transform(e=>e??void 0),service:x.coerce.string().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:x.coerce.string(),accountSecureId:x.coerce.string(),status:x.coerce.number().optional().nullable().transform(e=>e??void 0),provider:x.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:x.coerce.number().optional().nullable().transform(e=>e??void 0)}),J=U.extend({logType:x.literal(`platform`),eventId:x.coerce.string(),eventType:x.coerce.string(),service:x.coerce.string(),organizationId:x.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:x.undefined(),userId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:x.coerce.string().optional().nullable().transform(e=>e??void 0),action:x.coerce.string().optional().nullable().transform(e=>e??void 0),resource:x.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:x.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:x.coerce.string().optional().nullable().transform(e=>e??void 0),authType:x.coerce.string().optional().nullable().transform(e=>e??void 0),authId:x.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:x.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:x.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:x.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:x.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:x.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:x.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:x.coerce.number().optional().nullable().transform(e=>e??void 0),success:x.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:x.record(x.unknown()).optional().nullable().transform(e=>e??void 0)}),Ee=x.discriminatedUnion(`logType`,[W,G,K,q]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},Y=[`success`,`isWorker`,`isBackground`,`skipped`];var LogsSink=class{#e;#t;#n;#r;#i;#a;#o(e){if(e===`clickhouse`&&this.#i?.isReady())return this.#i;if(this.#r?.isReady())return this.#r;if(this.#i?.isReady())return this.#i}#s(){if(this.#i?.isReady())return this.#i;this.#a?.warning({message:`Platform logs were requested but the ClickHouse client is not available`,category:`LogsSink`})}constructor(e,t,n,r,i,a,o){this.#e=e,this.#t=a,this.#n=o,this.#a=r,n&&(this.#r=new TinybirdClient(t,n,r)),i&&(this.#i=new ClickHouseClient(i,r));let s=[];this.#r&&s.push(`tinybird`),this.#i&&s.push(`clickhouse`),s.length>0&&this.#a?.debug({message:`LogsSink initialized with query clients: ${s.join(`, `)}`,category:`LogsSink`})}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#a?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}let e=this.#r?.isReady()??!1,t=this.#i?.isReady()??!1;!e&&!t?this.#a?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}):this.#a?.info({message:`Logs sink query clients ready: tinybird=${e}, clickhouse=${t}`,category:`LogsSink`}),this.#a?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#c()}async#c(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{try{await t?.connectToBrokers(),this.#a?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#a?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t,metadata:n})=>this.buildActionLog(e,t,n));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n,r){if(!r?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#a?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#a?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#a?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#a?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} logs (${r.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(r.data),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getLastLogs(e,t){let n=e?.ids??[];if(n.length===0)return emptyQueryResult();let r=this.#i;if(!r?.isReady())return this.#a?.warning({message:`ClickHouse client not available, returning empty results`,category:`LogsSink`}),emptyQueryResult();try{this.#a?.info({message:`Querying last logs for ${n.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await r.queryWithPagination({endpoint:`project_last_logs.json`,params:{...t,entities:e}});return this.#a?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){return this.#a?.warning({message:`Failed to query for last logs, returning empty results`,category:`LogsSink`,error:e}),emptyQueryResult()}}async getActions(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} action logs (${r.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(r.data,W),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n,r){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n},r)).actionLogs[0]}async getSteps(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} step logs (${r.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(r.data,G),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r,i){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r},i)).stepLogs[0]}async getUnifiedLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} unified logs (${r.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(r.data,K),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.warning({message:`Failed to query for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n,r){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n},r)).unifiedLogs[0]}async getProviderLogs(e,t){let n=this.#o(t);try{this.#a?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e,engine:t}});let r=await n?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return r?(this.#a?.info({message:`Successfully retrieved ${r.data.length} provider logs (${r.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(r.data,q),total:r.total,pageNumber:r.pageNumber,pageSize:r.pageSize}):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return n?.isReady()?this.#a?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:t}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogs(e){let t=this.#s();try{this.#a?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t?.queryWithPagination({endpoint:`organization_platform_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return n?(this.#a?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,J),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}):{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}catch(n){return t?.isReady()?this.#a?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:n}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:n}),{platformLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r,i){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r},i)).providerLogs[0]}async getAggregate(e,t,n,i){let a=this.#o(i);try{this.#a?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n,engine:i}});let{dimensions:o,startTime:s,endTime:c,...l}=n,u=n.intervalType===j.None,d={organizationId:e,projectSecureId:t,...l,...o&&o.length>0&&{dimensions:o.join(`,`)},...s&&{startTime:s.toISOString()},...c&&{endTime:c.toISOString()},...u&&{pageSize:void 0,pageNumber:void 0}},f=await a?.query({endpoint:`project_logs_aggregation.json`,params:d});if(!f)return this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),{data:[]};this.#a?.info({message:`Successfully retrieved ${f.length} aggregated data points`,category:`LogsSink`});let p=f.map(e=>r(e,!0)).map(e=>{let t={...e};for(let e of Y)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:u?foldTimeBuckets(p):p}}catch(e){return 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={};for(let e of d)Y.includes(e.dimension)?f[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):f[e.dimension]=e.values;return f}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats dimensions, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),{}}}async getSourceUsage(e,t,n,r){let i=this.#o(r);try{this.#a?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n,engine:r}});let{startTime:a,endTime:o,sourceType:s}=n,c={organizationId:e,projectSecureId:t,...s&&{sourceType:Array.isArray(s)?s.join(`,`):s},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await i?.query({endpoint:`project_source_usage.json`,params:c});return l?(this.#a?.info({message:`Successfully retrieved ${l.length} source usage records`,category:`LogsSink`}),l.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))):(this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`}),[])}catch(e){return i?.isReady()?this.#a?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}):this.#a?.warning({message:`Query client not available, returning empty results`,category:`LogsSink`,error:e}),[]}}#l(e){return(this.#n??M)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#l(e);if(!n)throw this.#a?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#a?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#a?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#a?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#u(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#u(e,t,n,r){if(!t)throw this.#a?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#a?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#a?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#a?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,...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??y(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof b){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#a?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,Ee)}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 b?this.#a?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#a?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return W;case`step`:return G;case`unified`:return K;case`provider`:return q;case`platform`:return J}}};const X={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...X.logs,...e?.logs},advanced:{...X.advanced,...e?.advanced},defender:{...X.defender,...e?.defender},policy:{...X.policy,...e?.policy},datasets:{...X.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=e,this.#t=t?.bucket,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#t)throw Error(`Policy sink bucket is not configured`);return this.#t}async initialize(){this.#e||this.#r?.warning({message:`No s3 client provided, policy sink will not function`,category:`PolicySink`})}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(!t?.enabled){n.push(null);continue}if(!this.#t){n.push(null);continue}if(s(i.policyContext)){n.push(null);continue}let e=await this.send(this.createPolicyS3(r,i));n.push(e)}return n}async getAction(e,t,n,r){if(!this.#e){this.#r?.warning({message:`No s3 client available, cannot get action log from policy sink`,category:`PolicySink`});return}if(this.#t)try{let i=await this.#e.send(new _({Bucket:this.requireBucket(),Key:this.generateS3Key(e,t,n,r)}));if(!i.Body){this.#r?.warning({message:`Received empty body when trying to get policy log from S3 for actionRunId ${r}`,category:`PolicySink`});return}return JSON.parse(await i.Body.transformToString())}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#r?.debug({message:`Policy log not found in S3 for actionRunId ${r}`,category:`PolicySink`});return}throw this.#r?.error({message:`Error when getting policy log from S3 for actionRunId ${r}`,error:e,code:`PolicyLogReadError`,category:`PolicySink`}),e}}async send(e){if(!this.#e)throw Error(`No s3 client available, cannot send to policy sink`);let t=new Date(Date.now()+this.#n*24*60*60*1e3);try{return await this.#e.send(new v({Bucket:this.requireBucket(),Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:t,Tagging:`ttl=${this.#n}d`})),{expiresAt:t}}catch(t){throw this.#r?.error({message:`Failed to write policy log to S3 at ${e.Key}`,error:t,code:`PolicyLogWriteError`,category:`PolicySink`}),t}}generateS3Key(e,t,n,r){return`${e}/${t}/${n}/${r}/policy.json`}createPolicyS3(e,t){return{Key:this.generateS3Key(e.organizationId,e.projectSecureId,e.accountSecureId,e.actionRunId),Body:JSON.stringify(t.policyContext),ContentType:`application/json`}}};const buildHttpClient=e=>{try{return new se({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 te(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;#g;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.#l=e,this.#u=a??i,this.#d=t,this.#f=o,this.#g=s,this.#p=l,this.#m=u,this.#h=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.#l(this.#u,this.#r);let e=this.#f?{producer:await this.#d(this.#f,this.#r)}:void 0,t=this.#e||this.#u?{producer:this.#e}:void 0;this.#i=new LogsSink(t,this.#t,this.#p,this.#r,this.#m,e,this.#g),this.#a=new AdvancedSink(this.#n,this.#h?.advanced,this.#r),this.#o=new DefenderSink(this.#n,this.#h?.defender,this.#r),this.#s=new PolicySink(this.#n,this.#h?.policy,this.#r),this.#c=new DatasetsSink(this.#h?.datasets,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#c?.initialize(),await this.#o?.initialize(),await this.#s?.initialize()}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,policy:a,datasets:o}=resolveOlapOptions(t);this.#r?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,policy:a,datasets:o}}});for(let t of e)s(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=a?.enabled&&this.#s?this.#s.sendActions(e,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to policy logs s3: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=o?.enabled&&this.#c?this.#c.sendActions(e,o).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=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))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=n?.enabled&&this.#i?this.#i.sendActions(f,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#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}}}),s(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(s(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(s(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(s(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n,r){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n,engine:r}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t},r)||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#r?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getPlatformLogs(n)||(this.#r?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getProviderLog(e,t,n,r,i){let a=await this.#i?.getProviderLog(e,t,n,r,i);if(s(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(s(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(s(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(s(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(s(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(s(n)){this.#r?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getPolicyLog(e,t,n,r){let i=await this.#s?.getAction(e,t,n,r);if(s(i)){this.#r?.debug({message:`Failed to retrieve policy log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if(s(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{ve as AuthType,ClickHouseClient,M as DEFAULT_TOPIC_CLUSTER_MAP,he as Dimension,j as IntervalType,A as LogType,$ as OlapClient,OlapClientManager,pe as OrderBy,me as OrderDirection,PolicySink,R as SourceType,_e as StreamType,ge as TransportType,createConfigFromEnv,createOlapQueryClient,getPolicySink,hasErrorEntries};
|