@rawdash/connector-datadog 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -2
- package/dist/index.d.ts +52 -21
- package/dist/index.js +106 -30
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ A Datadog API key and Application key are required, scoped to the org and site y
|
|
|
35
35
|
|
|
36
36
|
## Resources
|
|
37
37
|
|
|
38
|
-
- **`datadog_monitor`** _(entity)_ - Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.
|
|
38
|
+
- **`datadog_monitor`** _(entity)_ - Datadog monitors with name, type, current status (OK / Alert / Warn / No Data / Ignored / Skipped / Unknown), priority, and tags.
|
|
39
39
|
- Endpoint: `GET /api/v1/monitor/search`
|
|
40
40
|
- **`datadog_monitor_event`** _(event)_ - Monitor state-transition events, emitted whenever a monitor's status changes from its previously-stored value.
|
|
41
41
|
- Derived by diffing each monitor's current status against the last-synced status, so it depends on the monitors phase running and on prior monitor state being stored.
|
|
@@ -43,7 +43,8 @@ A Datadog API key and Application key are required, scoped to the org and site y
|
|
|
43
43
|
- Endpoint: `GET /api/v2/incidents`
|
|
44
44
|
- **`datadog_slo`** _(entity)_ - Service Level Objectives with type, thresholds, primary target, and latest SLI value.
|
|
45
45
|
- Endpoint: `GET /api/v1/slo`
|
|
46
|
-
- **`datadog_slo_sli`** _(metric)_ - SLI value samples per SLO, one per
|
|
46
|
+
- **`datadog_slo_sli`** _(metric)_ - SLI value samples per SLO, one per sync, read from the SLO history endpoint over a window derived from the SLO threshold timeframes.
|
|
47
|
+
- Endpoint: `GET /api/v1/slo/{slo_id}/history`
|
|
47
48
|
- Unit: percent
|
|
48
49
|
- Dimensions: `sloId`, `sloType`
|
|
49
50
|
- **`datadog_metric`** _(metric)_ - User-declared metric timeseries samples, stored as `datadog_metric.<query name>`, from the Datadog Metrics Query API.
|
|
@@ -102,6 +103,8 @@ Datadog returns X-RateLimit-Remaining / X-RateLimit-Reset headers (reset in seco
|
|
|
102
103
|
- Synthetic monitor results are out of scope.
|
|
103
104
|
- Monitor entities are not cleared on a full sync - the monitor_events diff depends on the prior status being stored.
|
|
104
105
|
- Pagination URLs are pinned to the configured `api.<site>` host.
|
|
106
|
+
- SLI values are read per SLO from the SLO history endpoint, so the SLO phase issues one extra request per SLO each sync.
|
|
107
|
+
- The SLO list is capped at 1000 entries per sync; orgs with more SLOs will not see the remainder.
|
|
105
108
|
|
|
106
109
|
## Links
|
|
107
110
|
|
package/dist/index.d.ts
CHANGED
|
@@ -58,9 +58,9 @@ declare const datadogResources: {
|
|
|
58
58
|
readonly filterable: [{
|
|
59
59
|
readonly field: "status";
|
|
60
60
|
readonly ops: ["eq"];
|
|
61
|
-
readonly values: ["OK", "Alert", "Warn", "No Data", "Ignored"];
|
|
61
|
+
readonly values: ["OK", "Alert", "Warn", "No Data", "Ignored", "Skipped", "Unknown"];
|
|
62
62
|
}];
|
|
63
|
-
readonly description: "Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.";
|
|
63
|
+
readonly description: "Datadog monitors with name, type, current status (OK / Alert / Warn / No Data / Ignored / Skipped / Unknown), priority, and tags.";
|
|
64
64
|
readonly endpoint: "GET /api/v1/monitor/search";
|
|
65
65
|
readonly responses: {
|
|
66
66
|
readonly monitors: z.ZodObject<{
|
|
@@ -74,6 +74,8 @@ declare const datadogResources: {
|
|
|
74
74
|
Warn: "Warn";
|
|
75
75
|
"No Data": "No Data";
|
|
76
76
|
Ignored: "Ignored";
|
|
77
|
+
Skipped: "Skipped";
|
|
78
|
+
Unknown: "Unknown";
|
|
77
79
|
}>;
|
|
78
80
|
priority: z.ZodNullable<z.ZodNumber>;
|
|
79
81
|
tags: z.ZodArray<z.ZodString>;
|
|
@@ -142,10 +144,6 @@ declare const datadogResources: {
|
|
|
142
144
|
target: z.ZodNumber;
|
|
143
145
|
warning: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
144
146
|
}, z.core.$strip>>;
|
|
145
|
-
overall_status: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
|
|
146
|
-
sli_value: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
147
|
-
indexed_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
148
|
-
}, z.core.$strip>>>>;
|
|
149
147
|
created_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
150
148
|
modified_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
151
149
|
}, z.core.$strip>>;
|
|
@@ -154,8 +152,9 @@ declare const datadogResources: {
|
|
|
154
152
|
};
|
|
155
153
|
readonly datadog_slo_sli: {
|
|
156
154
|
readonly shape: "metric";
|
|
157
|
-
readonly description: "SLI value samples per SLO, one per
|
|
155
|
+
readonly description: "SLI value samples per SLO, one per sync, read from the SLO history endpoint over a window derived from the SLO threshold timeframes.";
|
|
158
156
|
readonly unit: "percent";
|
|
157
|
+
readonly endpoint: "GET /api/v1/slo/{slo_id}/history";
|
|
159
158
|
readonly dimensions: [{
|
|
160
159
|
readonly name: "sloId";
|
|
161
160
|
readonly description: "Datadog SLO id.";
|
|
@@ -163,6 +162,17 @@ declare const datadogResources: {
|
|
|
163
162
|
readonly name: "sloType";
|
|
164
163
|
readonly description: "SLO type (metric, monitor, etc.).";
|
|
165
164
|
}];
|
|
165
|
+
readonly responses: {
|
|
166
|
+
readonly slo_history: z.ZodObject<{
|
|
167
|
+
data: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
168
|
+
to_ts: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
169
|
+
from_ts: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
170
|
+
overall: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
171
|
+
sli_value: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
172
|
+
}, z.core.$strip>>>;
|
|
173
|
+
}, z.core.$strip>>>;
|
|
174
|
+
}, z.core.$strip>;
|
|
175
|
+
};
|
|
166
176
|
};
|
|
167
177
|
readonly datadog_metric: {
|
|
168
178
|
readonly shape: "metric";
|
|
@@ -189,7 +199,7 @@ declare const datadogResources: {
|
|
|
189
199
|
query_index: z.ZodOptional<z.ZodNumber>;
|
|
190
200
|
}, z.core.$strip>>>;
|
|
191
201
|
times: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
|
|
192
|
-
values: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodNumber
|
|
202
|
+
values: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodNullable<z.ZodNumber>>>>;
|
|
193
203
|
}, z.core.$strip>;
|
|
194
204
|
}, z.core.$strip>;
|
|
195
205
|
}, z.core.$strip>;
|
|
@@ -205,9 +215,9 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
205
215
|
readonly filterable: [{
|
|
206
216
|
readonly field: "status";
|
|
207
217
|
readonly ops: ["eq"];
|
|
208
|
-
readonly values: ["OK", "Alert", "Warn", "No Data", "Ignored"];
|
|
218
|
+
readonly values: ["OK", "Alert", "Warn", "No Data", "Ignored", "Skipped", "Unknown"];
|
|
209
219
|
}];
|
|
210
|
-
readonly description: "Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.";
|
|
220
|
+
readonly description: "Datadog monitors with name, type, current status (OK / Alert / Warn / No Data / Ignored / Skipped / Unknown), priority, and tags.";
|
|
211
221
|
readonly endpoint: "GET /api/v1/monitor/search";
|
|
212
222
|
readonly responses: {
|
|
213
223
|
readonly monitors: z.ZodObject<{
|
|
@@ -221,6 +231,8 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
221
231
|
Warn: "Warn";
|
|
222
232
|
"No Data": "No Data";
|
|
223
233
|
Ignored: "Ignored";
|
|
234
|
+
Skipped: "Skipped";
|
|
235
|
+
Unknown: "Unknown";
|
|
224
236
|
}>;
|
|
225
237
|
priority: z.ZodNullable<z.ZodNumber>;
|
|
226
238
|
tags: z.ZodArray<z.ZodString>;
|
|
@@ -289,10 +301,6 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
289
301
|
target: z.ZodNumber;
|
|
290
302
|
warning: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
291
303
|
}, z.core.$strip>>;
|
|
292
|
-
overall_status: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
|
|
293
|
-
sli_value: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
294
|
-
indexed_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
295
|
-
}, z.core.$strip>>>>;
|
|
296
304
|
created_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
297
305
|
modified_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
298
306
|
}, z.core.$strip>>;
|
|
@@ -301,8 +309,9 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
301
309
|
};
|
|
302
310
|
readonly datadog_slo_sli: {
|
|
303
311
|
readonly shape: "metric";
|
|
304
|
-
readonly description: "SLI value samples per SLO, one per
|
|
312
|
+
readonly description: "SLI value samples per SLO, one per sync, read from the SLO history endpoint over a window derived from the SLO threshold timeframes.";
|
|
305
313
|
readonly unit: "percent";
|
|
314
|
+
readonly endpoint: "GET /api/v1/slo/{slo_id}/history";
|
|
306
315
|
readonly dimensions: [{
|
|
307
316
|
readonly name: "sloId";
|
|
308
317
|
readonly description: "Datadog SLO id.";
|
|
@@ -310,6 +319,17 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
310
319
|
readonly name: "sloType";
|
|
311
320
|
readonly description: "SLO type (metric, monitor, etc.).";
|
|
312
321
|
}];
|
|
322
|
+
readonly responses: {
|
|
323
|
+
readonly slo_history: z.ZodObject<{
|
|
324
|
+
data: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
325
|
+
to_ts: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
326
|
+
from_ts: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
327
|
+
overall: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
328
|
+
sli_value: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
329
|
+
}, z.core.$strip>>>;
|
|
330
|
+
}, z.core.$strip>>>;
|
|
331
|
+
}, z.core.$strip>;
|
|
332
|
+
};
|
|
313
333
|
};
|
|
314
334
|
readonly datadog_metric: {
|
|
315
335
|
readonly shape: "metric";
|
|
@@ -336,7 +356,7 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
336
356
|
query_index: z.ZodOptional<z.ZodNumber>;
|
|
337
357
|
}, z.core.$strip>>>;
|
|
338
358
|
times: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
|
|
339
|
-
values: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodNumber
|
|
359
|
+
values: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodNullable<z.ZodNumber>>>>;
|
|
340
360
|
}, z.core.$strip>;
|
|
341
361
|
}, z.core.$strip>;
|
|
342
362
|
}, z.core.$strip>;
|
|
@@ -355,6 +375,8 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
355
375
|
Warn: "Warn";
|
|
356
376
|
"No Data": "No Data";
|
|
357
377
|
Ignored: "Ignored";
|
|
378
|
+
Skipped: "Skipped";
|
|
379
|
+
Unknown: "Unknown";
|
|
358
380
|
}>;
|
|
359
381
|
priority: z.ZodNullable<z.ZodNumber>;
|
|
360
382
|
tags: z.ZodArray<z.ZodString>;
|
|
@@ -403,14 +425,20 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
403
425
|
target: z.ZodNumber;
|
|
404
426
|
warning: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
405
427
|
}, z.core.$strip>>;
|
|
406
|
-
overall_status: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
|
|
407
|
-
sli_value: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
408
|
-
indexed_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
409
|
-
}, z.core.$strip>>>>;
|
|
410
428
|
created_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
411
429
|
modified_at: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
412
430
|
}, z.core.$strip>>;
|
|
413
431
|
}, z.core.$strip>;
|
|
432
|
+
} & {
|
|
433
|
+
readonly slo_history: z.ZodObject<{
|
|
434
|
+
data: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
435
|
+
to_ts: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
436
|
+
from_ts: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
437
|
+
overall: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
438
|
+
sli_value: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
439
|
+
}, z.core.$strip>>>;
|
|
440
|
+
}, z.core.$strip>>>;
|
|
441
|
+
}, z.core.$strip>;
|
|
414
442
|
} & {
|
|
415
443
|
readonly metric_queries: z.ZodObject<{
|
|
416
444
|
data: z.ZodObject<{
|
|
@@ -421,7 +449,7 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
421
449
|
query_index: z.ZodOptional<z.ZodNumber>;
|
|
422
450
|
}, z.core.$strip>>>;
|
|
423
451
|
times: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
|
|
424
|
-
values: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodNumber
|
|
452
|
+
values: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodNullable<z.ZodNumber>>>>;
|
|
425
453
|
}, z.core.$strip>;
|
|
426
454
|
}, z.core.$strip>;
|
|
427
455
|
}, z.core.$strip>;
|
|
@@ -453,10 +481,13 @@ declare class DatadogConnector extends BaseConnector<DatadogSettings, DatadogCre
|
|
|
453
481
|
private buildInitialIncidentsUrl;
|
|
454
482
|
private buildNextIncidentsUrl;
|
|
455
483
|
private buildSlosUrl;
|
|
484
|
+
private buildSloHistoryUrl;
|
|
485
|
+
private sloHistoryWindowSeconds;
|
|
456
486
|
private buildMetricsUrl;
|
|
457
487
|
private fetchMonitorsPage;
|
|
458
488
|
private fetchIncidentsPage;
|
|
459
489
|
private fetchSlos;
|
|
490
|
+
private fetchSloSli;
|
|
460
491
|
private fetchMetrics;
|
|
461
492
|
private writeMonitorsBatch;
|
|
462
493
|
private writeIncidents;
|
package/dist/index.js
CHANGED
|
@@ -168,7 +168,9 @@ var doc = defineConnectorDoc({
|
|
|
168
168
|
"Logs and RUM session data are out of scope (high volume, low dashboard signal).",
|
|
169
169
|
"Synthetic monitor results are out of scope.",
|
|
170
170
|
"Monitor entities are not cleared on a full sync - the monitor_events diff depends on the prior status being stored.",
|
|
171
|
-
"Pagination URLs are pinned to the configured `api.<site>` host."
|
|
171
|
+
"Pagination URLs are pinned to the configured `api.<site>` host.",
|
|
172
|
+
"SLI values are read per SLO from the SLO history endpoint, so the SLO phase issues one extra request per SLO each sync.",
|
|
173
|
+
"The SLO list is capped at 1000 entries per sync; orgs with more SLOs will not see the remainder."
|
|
172
174
|
]
|
|
173
175
|
});
|
|
174
176
|
var datadogCredentials = {
|
|
@@ -193,7 +195,15 @@ var monitorSchema = z.object({
|
|
|
193
195
|
id: z.number().int().nonnegative(),
|
|
194
196
|
name: z.string(),
|
|
195
197
|
type: z.string(),
|
|
196
|
-
status: z.enum([
|
|
198
|
+
status: z.enum([
|
|
199
|
+
"OK",
|
|
200
|
+
"Alert",
|
|
201
|
+
"Warn",
|
|
202
|
+
"No Data",
|
|
203
|
+
"Ignored",
|
|
204
|
+
"Skipped",
|
|
205
|
+
"Unknown"
|
|
206
|
+
]),
|
|
197
207
|
priority: z.number().int().nullable(),
|
|
198
208
|
tags: z.array(z.string()),
|
|
199
209
|
overall_state_modified: z.iso.datetime().nullable().optional(),
|
|
@@ -243,18 +253,21 @@ var sloSchema = z.object({
|
|
|
243
253
|
warning: z.number().nullable().optional()
|
|
244
254
|
})
|
|
245
255
|
),
|
|
246
|
-
overall_status: z.array(
|
|
247
|
-
z.object({
|
|
248
|
-
sli_value: z.number().nullable().optional(),
|
|
249
|
-
indexed_at: z.number().nullable().optional()
|
|
250
|
-
})
|
|
251
|
-
).nullable().optional(),
|
|
252
256
|
created_at: z.number().nullable().optional(),
|
|
253
257
|
modified_at: z.number().nullable().optional()
|
|
254
258
|
});
|
|
255
259
|
var slosResponseSchema = z.object({
|
|
256
260
|
data: z.array(sloSchema)
|
|
257
261
|
});
|
|
262
|
+
var sloHistoryResponseSchema = z.object({
|
|
263
|
+
data: z.object({
|
|
264
|
+
to_ts: z.number().nullable().optional(),
|
|
265
|
+
from_ts: z.number().nullable().optional(),
|
|
266
|
+
overall: z.object({
|
|
267
|
+
sli_value: z.number().nullable().optional()
|
|
268
|
+
}).nullable().optional()
|
|
269
|
+
}).nullable().optional()
|
|
270
|
+
});
|
|
258
271
|
var timeseriesResponseSchema = z.object({
|
|
259
272
|
data: z.object({
|
|
260
273
|
type: z.literal("timeseries_response"),
|
|
@@ -266,7 +279,7 @@ var timeseriesResponseSchema = z.object({
|
|
|
266
279
|
})
|
|
267
280
|
).optional(),
|
|
268
281
|
times: z.array(z.number()).optional(),
|
|
269
|
-
values: z.array(z.array(z.number())).optional()
|
|
282
|
+
values: z.array(z.array(z.number().nullable())).optional()
|
|
270
283
|
})
|
|
271
284
|
})
|
|
272
285
|
});
|
|
@@ -274,6 +287,12 @@ var DEFAULT_SITE = "datadoghq.com";
|
|
|
274
287
|
var MONITORS_PAGE_SIZE = 100;
|
|
275
288
|
var INCIDENTS_PAGE_SIZE = 50;
|
|
276
289
|
var DEFAULT_METRICS_LOOKBACK_HOURS = 24;
|
|
290
|
+
var DEFAULT_SLO_HISTORY_WINDOW_S = 7 * 24 * 60 * 60;
|
|
291
|
+
var TIMEFRAME_UNIT_SECONDS = {
|
|
292
|
+
h: 60 * 60,
|
|
293
|
+
d: 24 * 60 * 60,
|
|
294
|
+
w: 7 * 24 * 60 * 60
|
|
295
|
+
};
|
|
277
296
|
var INTERVAL_MS = {
|
|
278
297
|
"5m": 5 * 60 * 1e3,
|
|
279
298
|
"15m": 15 * 60 * 1e3,
|
|
@@ -288,10 +307,18 @@ var datadogResources = defineResources({
|
|
|
288
307
|
{
|
|
289
308
|
field: "status",
|
|
290
309
|
ops: ["eq"],
|
|
291
|
-
values: [
|
|
310
|
+
values: [
|
|
311
|
+
"OK",
|
|
312
|
+
"Alert",
|
|
313
|
+
"Warn",
|
|
314
|
+
"No Data",
|
|
315
|
+
"Ignored",
|
|
316
|
+
"Skipped",
|
|
317
|
+
"Unknown"
|
|
318
|
+
]
|
|
292
319
|
}
|
|
293
320
|
],
|
|
294
|
-
description: "Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.",
|
|
321
|
+
description: "Datadog monitors with name, type, current status (OK / Alert / Warn / No Data / Ignored / Skipped / Unknown), priority, and tags.",
|
|
295
322
|
endpoint: "GET /api/v1/monitor/search",
|
|
296
323
|
responses: { monitors: monitorSearchResponseSchema }
|
|
297
324
|
},
|
|
@@ -317,12 +344,14 @@ var datadogResources = defineResources({
|
|
|
317
344
|
},
|
|
318
345
|
datadog_slo_sli: {
|
|
319
346
|
shape: "metric",
|
|
320
|
-
description: "SLI value samples per SLO, one per
|
|
347
|
+
description: "SLI value samples per SLO, one per sync, read from the SLO history endpoint over a window derived from the SLO threshold timeframes.",
|
|
321
348
|
unit: "percent",
|
|
349
|
+
endpoint: "GET /api/v1/slo/{slo_id}/history",
|
|
322
350
|
dimensions: [
|
|
323
351
|
{ name: "sloId", description: "Datadog SLO id." },
|
|
324
352
|
{ name: "sloType", description: "SLO type (metric, monitor, etc.)." }
|
|
325
|
-
]
|
|
353
|
+
],
|
|
354
|
+
responses: { slo_history: sloHistoryResponseSchema }
|
|
326
355
|
},
|
|
327
356
|
datadog_metric: {
|
|
328
357
|
shape: "metric",
|
|
@@ -341,6 +370,18 @@ var datadogResources = defineResources({
|
|
|
341
370
|
}
|
|
342
371
|
});
|
|
343
372
|
var id = "datadog";
|
|
373
|
+
function parseTimeframeSeconds(timeframe) {
|
|
374
|
+
const match = /^(\d+)([hdw])$/.exec(timeframe.trim().toLowerCase());
|
|
375
|
+
if (!match) {
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
const amount = Number(match[1]);
|
|
379
|
+
const unitSeconds = TIMEFRAME_UNIT_SECONDS[match[2]];
|
|
380
|
+
if (!Number.isFinite(amount) || amount <= 0 || unitSeconds === void 0) {
|
|
381
|
+
return null;
|
|
382
|
+
}
|
|
383
|
+
return amount * unitSeconds;
|
|
384
|
+
}
|
|
344
385
|
function pushableEq(filter, field) {
|
|
345
386
|
if (!filter) {
|
|
346
387
|
return null;
|
|
@@ -495,6 +536,24 @@ var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
|
495
536
|
u.searchParams.set("offset", "0");
|
|
496
537
|
return u.toString();
|
|
497
538
|
}
|
|
539
|
+
buildSloHistoryUrl(sloId, fromTs, toTs) {
|
|
540
|
+
const u = new URL(
|
|
541
|
+
`${this.apiBase}/api/v1/slo/${encodeURIComponent(sloId)}/history`
|
|
542
|
+
);
|
|
543
|
+
u.searchParams.set("from_ts", String(fromTs));
|
|
544
|
+
u.searchParams.set("to_ts", String(toTs));
|
|
545
|
+
return u.toString();
|
|
546
|
+
}
|
|
547
|
+
sloHistoryWindowSeconds(slo) {
|
|
548
|
+
let maxSeconds = 0;
|
|
549
|
+
for (const threshold of slo.thresholds) {
|
|
550
|
+
const seconds = parseTimeframeSeconds(threshold.timeframe);
|
|
551
|
+
if (seconds !== null && seconds > maxSeconds) {
|
|
552
|
+
maxSeconds = seconds;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return maxSeconds > 0 ? maxSeconds : DEFAULT_SLO_HISTORY_WINDOW_S;
|
|
556
|
+
}
|
|
498
557
|
buildMetricsUrl() {
|
|
499
558
|
return `${this.apiBase}/api/v2/query/timeseries`;
|
|
500
559
|
}
|
|
@@ -547,7 +606,33 @@ var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
|
547
606
|
"slos",
|
|
548
607
|
signal
|
|
549
608
|
);
|
|
550
|
-
|
|
609
|
+
const nowSeconds = Math.floor(Date.now() / 1e3);
|
|
610
|
+
const items = [];
|
|
611
|
+
for (const slo of res.body.data) {
|
|
612
|
+
signal?.throwIfAborted();
|
|
613
|
+
const sli = await this.fetchSloSli(slo, nowSeconds, signal);
|
|
614
|
+
items.push({ slo, sli });
|
|
615
|
+
}
|
|
616
|
+
return { items, next: null };
|
|
617
|
+
}
|
|
618
|
+
async fetchSloSli(slo, nowSeconds, signal) {
|
|
619
|
+
const fromTs = nowSeconds - this.sloHistoryWindowSeconds(slo);
|
|
620
|
+
const res = await this.fetch(
|
|
621
|
+
this.buildSloHistoryUrl(slo.id, fromTs, nowSeconds),
|
|
622
|
+
"slos",
|
|
623
|
+
signal
|
|
624
|
+
);
|
|
625
|
+
const value = res.body.data?.overall?.sli_value;
|
|
626
|
+
if (value === null || value === void 0 || !Number.isFinite(value)) {
|
|
627
|
+
return null;
|
|
628
|
+
}
|
|
629
|
+
const rawTs = res.body.data?.to_ts;
|
|
630
|
+
const tsSeconds = rawTs !== null && rawTs !== void 0 && Number.isFinite(rawTs) ? rawTs : nowSeconds;
|
|
631
|
+
const ts = parseEpoch(tsSeconds, "s");
|
|
632
|
+
if (ts === null) {
|
|
633
|
+
return null;
|
|
634
|
+
}
|
|
635
|
+
return { value, ts };
|
|
551
636
|
}
|
|
552
637
|
async fetchMetrics(options, signal) {
|
|
553
638
|
const queries = this.settings.metricQueries ?? [];
|
|
@@ -685,10 +770,10 @@ var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
|
685
770
|
});
|
|
686
771
|
}
|
|
687
772
|
}
|
|
688
|
-
async writeSlos(storage,
|
|
773
|
+
async writeSlos(storage, items) {
|
|
689
774
|
const sliSamples = [];
|
|
690
775
|
const entities = [];
|
|
691
|
-
for (const s of
|
|
776
|
+
for (const { slo: s, sli } of items) {
|
|
692
777
|
const createdMs = s.created_at !== null && s.created_at !== void 0 ? parseEpoch(s.created_at, "s") : null;
|
|
693
778
|
const modifiedMs = s.modified_at !== null && s.modified_at !== void 0 ? parseEpoch(s.modified_at, "s") : null;
|
|
694
779
|
const targets = s.thresholds.map((t) => ({
|
|
@@ -696,10 +781,6 @@ var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
|
696
781
|
target: t.target
|
|
697
782
|
}));
|
|
698
783
|
const primaryTarget = s.thresholds[0]?.target ?? null;
|
|
699
|
-
const latestStatus = (s.overall_status ?? []).find(
|
|
700
|
-
(st) => st.sli_value !== null && st.sli_value !== void 0
|
|
701
|
-
);
|
|
702
|
-
const latestSli = latestStatus?.sli_value ?? null;
|
|
703
784
|
entities.push({
|
|
704
785
|
type: "datadog_slo",
|
|
705
786
|
id: s.id,
|
|
@@ -709,22 +790,17 @@ var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
|
709
790
|
sloType: s.type,
|
|
710
791
|
thresholds: targets,
|
|
711
792
|
target: primaryTarget,
|
|
712
|
-
latestSliValue:
|
|
793
|
+
latestSliValue: sli?.value ?? null,
|
|
713
794
|
createdAt: createdMs,
|
|
714
795
|
modifiedAt: modifiedMs
|
|
715
796
|
},
|
|
716
797
|
updated_at: modifiedMs ?? createdMs ?? Date.now()
|
|
717
798
|
});
|
|
718
|
-
|
|
719
|
-
const ts = status.indexed_at !== null && status.indexed_at !== void 0 ? parseEpoch(status.indexed_at, "s") : null;
|
|
720
|
-
const value = status.sli_value;
|
|
721
|
-
if (ts === null || value === null || value === void 0 || !Number.isFinite(value)) {
|
|
722
|
-
continue;
|
|
723
|
-
}
|
|
799
|
+
if (sli !== null) {
|
|
724
800
|
sliSamples.push({
|
|
725
801
|
name: "datadog_slo_sli",
|
|
726
|
-
ts,
|
|
727
|
-
value,
|
|
802
|
+
ts: sli.ts,
|
|
803
|
+
value: sli.value,
|
|
728
804
|
attributes: { sloId: s.id, sloType: s.type }
|
|
729
805
|
});
|
|
730
806
|
}
|
|
@@ -756,7 +832,7 @@ var DatadogConnector = class _DatadogConnector extends BaseConnector {
|
|
|
756
832
|
for (let t = 0; t < times.length; t++) {
|
|
757
833
|
const rawTs = times[t];
|
|
758
834
|
const rawValue = seriesValues[t];
|
|
759
|
-
if (rawTs === void 0 || rawValue === void 0) {
|
|
835
|
+
if (rawTs === void 0 || rawValue === void 0 || rawValue === null) {
|
|
760
836
|
continue;
|
|
761
837
|
}
|
|
762
838
|
const ts = parseEpoch(rawTs, "ms");
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/datadog.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n sanitizeAllowedUrl,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type Entity,\n type FetchSpec,\n type FilterClause,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nconst metricQuerySchema = z.object({\n name: z\n .string()\n .min(1)\n .regex(/^[a-zA-Z0-9_]+$/, {\n message: 'Metric name must be alphanumeric / underscore',\n }),\n query: z.string().min(1),\n interval: z\n .enum(['5m', '15m', '1h', '1d'])\n .optional()\n .describe('Aggregation interval - defaults to 1h.'),\n});\n\nconst datadogSiteSchema = z\n .string()\n .trim()\n .min(1)\n .toLowerCase()\n .regex(/^(?:[a-z0-9-]+\\.)*(?:datadoghq\\.com|datadoghq\\.eu|ddog-gov\\.com)$/, {\n message:\n 'Site must be a Datadog hostname (e.g. datadoghq.com, datadoghq.eu, us3.datadoghq.com)',\n });\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'API Key',\n description:\n 'Datadog API key. Create at Datadog → Organization Settings → API Keys.',\n placeholder: 'dd_api_key',\n secret: true,\n }),\n appKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'Application Key',\n description:\n 'Datadog Application key. Create at Datadog → Organization Settings → Application Keys. Used in tandem with the API key to authenticate REST calls.',\n placeholder: 'dd_app_key',\n secret: true,\n }),\n site: datadogSiteSchema.optional().meta({\n label: 'Site',\n description:\n 'Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`). Defaults to `datadoghq.com`.',\n placeholder: 'datadoghq.com',\n }),\n metricQueries: z.array(metricQuerySchema).nonempty().optional().meta({\n label: 'Metric queries (optional)',\n description:\n 'User-declared metric timeseries queries. Each entry produces `datadog_metric` samples named `<name>` from the Datadog Metrics Query API.',\n }),\n resources: z\n .array(\n z.enum([\n 'monitors',\n 'monitor_events',\n 'incidents',\n 'slos',\n 'metric_queries',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n \"Which Datadog resources to sync. Omit to sync all of them. 'monitor_events' depends on 'monitors' being fetched - enabling it without 'monitors' still runs the monitors query but skips writing monitor entities.\",\n }),\n metricsLookbackHours: z.number().int().positive().max(168).optional().meta({\n label: 'Metrics lookback (hours)',\n description:\n 'Window of metric samples to pull on each sync, in hours. Defaults to 24.',\n placeholder: '24',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Datadog',\n category: 'infrastructure',\n brandColor: '#632CA6',\n tagline:\n 'Sync monitor health, monitor state-change events, incidents, SLOs, and user-declared metric queries from a Datadog org.',\n vendor: {\n name: 'Datadog',\n domain: 'datadoghq.com',\n apiDocs: 'https://docs.datadoghq.com/api/latest/',\n website: 'https://www.datadoghq.com',\n },\n auth: {\n summary:\n 'A Datadog API key and Application key are required, scoped to the org and site you want to read from. Both are stored as secrets.',\n setup: [\n 'Open Datadog → Organization Settings → API Keys and create (or copy) an API key.',\n 'Open Datadog → Organization Settings → Application Keys and create an Application key with read access to monitors, incidents, SLOs, and metrics.',\n 'Store both as secrets and reference them from the connector config as `apiKey: secret(\"DD_API_KEY\")` and `appKey: secret(\"DD_APP_KEY\")`.',\n 'Set `site` to your Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`); it defaults to `datadoghq.com`.',\n ],\n },\n rateLimit:\n 'Datadog returns X-RateLimit-Remaining / X-RateLimit-Reset headers (reset in seconds) on the v2 endpoints, wired through the standard rate-limit policy so the host scheduler backs off on near-empty windows.',\n limitations: [\n 'Logs and RUM session data are out of scope (high volume, low dashboard signal).',\n 'Synthetic monitor results are out of scope.',\n 'Monitor entities are not cleared on a full sync - the monitor_events diff depends on the prior status being stored.',\n 'Pagination URLs are pinned to the configured `api.<site>` host.',\n ],\n});\n\nexport type DatadogResource =\n | 'monitors'\n | 'monitor_events'\n | 'incidents'\n | 'slos'\n | 'metric_queries';\n\nexport interface DatadogMetricQuery {\n name: string;\n query: string;\n interval?: '5m' | '15m' | '1h' | '1d';\n}\n\nexport interface DatadogSettings {\n site?: string;\n metricQueries?: readonly DatadogMetricQuery[];\n resources?: readonly DatadogResource[];\n metricsLookbackHours?: number;\n}\n\nconst datadogCredentials = {\n apiKey: {\n description: 'Datadog API key',\n auth: 'required' as const,\n },\n appKey: {\n description: 'Datadog Application key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype DatadogCredentials = typeof datadogCredentials;\n\nconst datadogRateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\nconst PHASE_ORDER = ['monitors', 'incidents', 'slos', 'metrics'] as const;\n\ntype DatadogPhase = (typeof PHASE_ORDER)[number];\n\ntype DatadogSyncCursor = ChunkedSyncCursor<DatadogPhase, string>;\n\nconst isDatadogSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\ntype DatadogMonitorStatus = 'OK' | 'Alert' | 'Warn' | 'No Data' | 'Ignored';\n\ninterface DatadogMonitor {\n id: number;\n name: string;\n type: string;\n status: DatadogMonitorStatus;\n priority: number | null;\n tags: string[];\n overall_state_modified?: string | null;\n created: string;\n modified: string;\n}\n\ninterface DatadogMonitorSearchResponse {\n monitors: DatadogMonitor[];\n metadata: {\n page: number;\n page_count: number;\n per_page: number;\n total_count: number;\n };\n}\n\ninterface DatadogIncident {\n id: string;\n type: 'incidents';\n attributes: {\n title: string;\n severity?: string | null;\n state?: string | null;\n customer_impact_scope?: string | null;\n created: string;\n modified?: string | null;\n resolved?: string | null;\n };\n}\n\ninterface DatadogIncidentsResponse {\n data: DatadogIncident[];\n meta?: {\n pagination?: {\n next_offset?: number | null;\n offset?: number;\n size?: number;\n };\n };\n}\n\ninterface DatadogSloThreshold {\n timeframe: string;\n target: number;\n warning?: number | null;\n}\n\ninterface DatadogSloStatus {\n sli_value?: number | null;\n indexed_at?: number | null;\n}\n\ninterface DatadogSlo {\n id: string;\n name: string;\n type: string;\n thresholds: DatadogSloThreshold[];\n overall_status?: DatadogSloStatus[] | null;\n created_at?: number | null;\n modified_at?: number | null;\n}\n\ninterface DatadogSlosResponse {\n data: DatadogSlo[];\n}\n\ninterface DatadogTimeseriesResponse {\n data: {\n type: 'timeseries_response';\n attributes: {\n series?: Array<{\n group_tags?: string[];\n query_index?: number;\n unit?: Array<{ name?: string } | null> | null;\n }>;\n times?: number[];\n values?: number[][];\n };\n };\n}\n\ninterface MonitorsBatchItem {\n monitor: DatadogMonitor;\n}\n\ninterface MetricsBatchItem {\n queryName: string;\n query: string;\n response: DatadogTimeseriesResponse;\n}\n\nconst idString = z.string().min(1);\n\nconst monitorSchema = z.object({\n id: z.number().int().nonnegative(),\n name: z.string(),\n type: z.string(),\n status: z.enum(['OK', 'Alert', 'Warn', 'No Data', 'Ignored']),\n priority: z.number().int().nullable(),\n tags: z.array(z.string()),\n overall_state_modified: z.iso.datetime().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime(),\n});\n\nconst monitorSearchResponseSchema = z.object({\n monitors: z.array(monitorSchema),\n metadata: z.object({\n page: z.number().int().nonnegative(),\n page_count: z.number().int().nonnegative(),\n per_page: z.number().int().positive(),\n total_count: z.number().int().nonnegative(),\n }),\n});\n\nconst incidentSchema = z.object({\n id: idString,\n type: z.literal('incidents'),\n attributes: z.object({\n title: z.string(),\n severity: z.string().nullable().optional(),\n state: z.string().nullable().optional(),\n customer_impact_scope: z.string().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime().nullable().optional(),\n resolved: z.iso.datetime().nullable().optional(),\n }),\n});\n\nconst incidentsResponseSchema = z.object({\n data: z.array(incidentSchema),\n meta: z\n .object({\n pagination: z\n .object({\n next_offset: z.number().int().nullable().optional(),\n offset: z.number().int().optional(),\n size: z.number().int().optional(),\n })\n .optional(),\n })\n .optional(),\n});\n\nconst sloSchema = z.object({\n id: idString,\n name: z.string(),\n type: z.string(),\n thresholds: z.array(\n z.object({\n timeframe: z.string(),\n target: z.number(),\n warning: z.number().nullable().optional(),\n }),\n ),\n overall_status: z\n .array(\n z.object({\n sli_value: z.number().nullable().optional(),\n indexed_at: z.number().nullable().optional(),\n }),\n )\n .nullable()\n .optional(),\n created_at: z.number().nullable().optional(),\n modified_at: z.number().nullable().optional(),\n});\n\nconst slosResponseSchema = z.object({\n data: z.array(sloSchema),\n});\n\nconst timeseriesResponseSchema = z.object({\n data: z.object({\n type: z.literal('timeseries_response'),\n attributes: z.object({\n series: z\n .array(\n z.object({\n group_tags: z.array(z.string()).optional(),\n query_index: z.number().int().optional(),\n }),\n )\n .optional(),\n times: z.array(z.number()).optional(),\n values: z.array(z.array(z.number())).optional(),\n }),\n }),\n});\n\nconst DEFAULT_SITE = 'datadoghq.com';\nconst MONITORS_PAGE_SIZE = 100;\nconst INCIDENTS_PAGE_SIZE = 50;\nconst DEFAULT_METRICS_LOOKBACK_HOURS = 24;\nconst INTERVAL_MS: Record<\n NonNullable<DatadogMetricQuery['interval']>,\n number\n> = {\n '5m': 5 * 60 * 1000,\n '15m': 15 * 60 * 1000,\n '1h': 60 * 60 * 1000,\n '1d': 24 * 60 * 60 * 1000,\n};\nconst DEFAULT_INTERVAL_MS = INTERVAL_MS['1h'];\n\nexport const datadogResources = defineResources({\n datadog_monitor: {\n shape: 'entity',\n filterable: [\n {\n field: 'status',\n ops: ['eq'],\n values: ['OK', 'Alert', 'Warn', 'No Data', 'Ignored'],\n },\n ],\n description:\n 'Datadog monitors with name, type, current status (OK / Alert / Warn / No Data), priority, and tags.',\n endpoint: 'GET /api/v1/monitor/search',\n responses: { monitors: monitorSearchResponseSchema },\n },\n datadog_monitor_event: {\n shape: 'event',\n filterable: [],\n description:\n \"Monitor state-transition events, emitted whenever a monitor's status changes from its previously-stored value.\",\n notes:\n \"Derived by diffing each monitor's current status against the last-synced status, so it depends on the monitors phase running and on prior monitor state being stored.\",\n },\n datadog_incident: {\n shape: 'entity',\n filterable: [],\n description:\n 'Datadog incidents with title, severity, state, and created / resolved timestamps.',\n endpoint: 'GET /api/v2/incidents',\n responses: { incidents: incidentsResponseSchema },\n },\n datadog_slo: {\n shape: 'entity',\n filterable: [],\n description:\n 'Service Level Objectives with type, thresholds, primary target, and latest SLI value.',\n endpoint: 'GET /api/v1/slo',\n responses: { slos: slosResponseSchema },\n },\n datadog_slo_sli: {\n shape: 'metric',\n description:\n 'SLI value samples per SLO, one per overall_status snapshot reported by Datadog.',\n unit: 'percent',\n dimensions: [\n { name: 'sloId', description: 'Datadog SLO id.' },\n { name: 'sloType', description: 'SLO type (metric, monitor, etc.).' },\n ],\n },\n datadog_metric: {\n shape: 'metric',\n dynamic: true,\n description:\n 'User-declared metric timeseries samples, stored as `datadog_metric.<query name>`, from the Datadog Metrics Query API.',\n endpoint: 'POST /api/v2/query/timeseries',\n dimensions: [\n { name: 'queryName', description: 'The user-declared query name.' },\n { name: 'query', description: 'The Datadog metrics query string.' },\n {\n name: 'tags',\n description:\n 'Comma-joined group tags for the series, or `*` when the series is ungrouped.',\n },\n ],\n responses: { metric_queries: timeseriesResponseSchema },\n },\n});\n\nexport const id = 'datadog';\n\nfunction pushableEq(\n filter: FilterClause[] | undefined,\n field: string,\n): string | null {\n if (!filter) {\n return null;\n }\n for (const clause of filter) {\n if (\n 'field' in clause &&\n clause.field === field &&\n clause.op === 'eq' &&\n typeof clause.value === 'string'\n ) {\n return clause.value;\n }\n }\n return null;\n}\n\nexport class DatadogConnector extends BaseConnector<\n DatadogSettings,\n DatadogCredentials\n> {\n static readonly id = id;\n\n static readonly resources = datadogResources;\n\n static readonly schemas = schemasFromResources(datadogResources);\n\n static create(input: unknown, ctx?: ConnectorContext): DatadogConnector {\n const parsed = configFields.parse(input);\n return new DatadogConnector(\n {\n site: parsed.site,\n metricQueries: parsed.metricQueries,\n resources: parsed.resources,\n metricsLookbackHours: parsed.metricsLookbackHours,\n },\n { apiKey: parsed.apiKey, appKey: parsed.appKey },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = datadogCredentials;\n\n private get apiHost(): string {\n return `api.${(this.settings.site ?? DEFAULT_SITE).toLowerCase()}`;\n }\n\n private get apiBase(): string {\n return `https://${this.apiHost}`;\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n 'DD-API-KEY': this.creds.apiKey,\n 'DD-APPLICATION-KEY': this.creds.appKey,\n 'User-Agent': connectorUserAgent('datadog'),\n };\n }\n\n private fetch<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n private postJson<T>(\n url: string,\n body: unknown,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.post<T>(url, {\n resource,\n headers: {\n ...this.buildHeaders(),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n private activePhases(): DatadogPhase[] {\n return selectActivePhases<DatadogResource, DatadogPhase>(\n (r) => {\n switch (r) {\n case 'monitors':\n case 'monitor_events':\n return 'monitors';\n case 'incidents':\n return 'incidents';\n case 'slos':\n return 'slos';\n case 'metric_queries':\n return 'metrics';\n }\n },\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n private allowedPagePath(phase: DatadogPhase): string {\n switch (phase) {\n case 'monitors':\n return '/api/v1/monitor/search';\n case 'incidents':\n return '/api/v2/incidents';\n case 'slos':\n return '/api/v1/slo';\n case 'metrics':\n return '/api/v2/query/timeseries';\n }\n }\n\n private sanitizePageUrl(\n phase: DatadogPhase,\n pageUrl: string | null,\n ): string | null {\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: this.apiHost,\n pathname: this.allowedPagePath(phase),\n });\n }\n\n private resolveCursor(cursor: unknown): DatadogSyncCursor | undefined {\n if (!isDatadogSyncCursor(cursor)) {\n return undefined;\n }\n return {\n phase: cursor.phase,\n page: this.sanitizePageUrl(cursor.phase, cursor.page),\n };\n }\n\n private singleSpec(\n options: SyncOptions,\n resource: string,\n ): FetchSpec | undefined {\n const specs = options.fetchSpecs?.[resource];\n return specs && specs.length === 1 ? specs[0] : undefined;\n }\n\n private buildInitialMonitorsUrl(options: SyncOptions): string {\n const u = new URL(`${this.apiBase}/api/v1/monitor/search`);\n u.searchParams.set('per_page', String(MONITORS_PAGE_SIZE));\n u.searchParams.set('page', '0');\n u.searchParams.set('sort', 'status,desc');\n const status = pushableEq(\n this.singleSpec(options, 'datadog_monitor')?.filter,\n 'status',\n );\n if (status !== null) {\n u.searchParams.set('query', `status:\"${status}\"`);\n }\n return u.toString();\n }\n\n private buildNextMonitorsUrl(currentUrl: string, nextPage: number): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page', String(nextPage));\n return u.toString();\n }\n\n private buildInitialIncidentsUrl(options: SyncOptions): string {\n const u = new URL(`${this.apiBase}/api/v2/incidents`);\n u.searchParams.set('page[size]', String(INCIDENTS_PAGE_SIZE));\n u.searchParams.set('page[offset]', '0');\n u.searchParams.set('include', '');\n if (options.since) {\n u.searchParams.set('filter[created.from]', options.since);\n }\n return u.toString();\n }\n\n private buildNextIncidentsUrl(\n currentUrl: string,\n nextOffset: number,\n ): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page[offset]', String(nextOffset));\n return u.toString();\n }\n\n private buildSlosUrl(): string {\n const u = new URL(`${this.apiBase}/api/v1/slo`);\n u.searchParams.set('limit', '1000');\n u.searchParams.set('offset', '0');\n return u.toString();\n }\n\n private buildMetricsUrl(): string {\n return `${this.apiBase}/api/v2/query/timeseries`;\n }\n\n private async fetchMonitorsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MonitorsBatchItem[]; next: string | null }> {\n const url = page ?? this.buildInitialMonitorsUrl(options);\n const res = await this.fetch<DatadogMonitorSearchResponse>(\n url,\n 'monitors',\n signal,\n );\n const meta = res.body.metadata;\n const currentPage = meta.page;\n const totalPages = meta.page_count;\n const hasNext = currentPage + 1 < totalPages;\n const next = hasNext\n ? this.sanitizePageUrl(\n 'monitors',\n this.buildNextMonitorsUrl(url, currentPage + 1),\n )\n : null;\n return {\n items: res.body.monitors.map((m) => ({ monitor: m })),\n next,\n };\n }\n\n private async fetchIncidentsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: DatadogIncident[]; next: string | null }> {\n const url = page ?? this.buildInitialIncidentsUrl(options);\n const res = await this.fetch<DatadogIncidentsResponse>(\n url,\n 'incidents',\n signal,\n );\n const nextOffset = res.body.meta?.pagination?.next_offset ?? null;\n const incidents = res.body.data;\n const cutoff = options.since\n ? (parseEpoch(options.since, 'iso') ?? null)\n : null;\n const filtered =\n cutoff !== null\n ? incidents.filter((inc) => {\n const ts = parseEpoch(inc.attributes.created, 'iso');\n return ts === null || ts >= cutoff;\n })\n : incidents;\n const lastIncident = incidents.at(-1);\n const lastTs = lastIncident\n ? parseEpoch(lastIncident.attributes.created, 'iso')\n : null;\n const cutoffReached = cutoff !== null && lastTs !== null && lastTs < cutoff;\n const next =\n !cutoffReached && nextOffset !== null\n ? this.sanitizePageUrl(\n 'incidents',\n this.buildNextIncidentsUrl(url, nextOffset),\n )\n : null;\n return { items: filtered, next };\n }\n\n private async fetchSlos(\n signal: AbortSignal | undefined,\n ): Promise<{ items: DatadogSlo[]; next: string | null }> {\n const res = await this.fetch<DatadogSlosResponse>(\n this.buildSlosUrl(),\n 'slos',\n signal,\n );\n return { items: res.body.data, next: null };\n }\n\n private async fetchMetrics(\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MetricsBatchItem[]; next: string | null }> {\n const queries = this.settings.metricQueries ?? [];\n if (queries.length === 0) {\n return { items: [], next: null };\n }\n const lookbackHours =\n this.settings.metricsLookbackHours ?? DEFAULT_METRICS_LOOKBACK_HOURS;\n const now = Date.now();\n const sinceMs = options.since ? parseEpoch(options.since, 'iso') : null;\n const fromMs =\n sinceMs !== null ? sinceMs : now - lookbackHours * 60 * 60 * 1000;\n const items: MetricsBatchItem[] = [];\n for (const q of queries) {\n signal?.throwIfAborted();\n const intervalMs = q.interval\n ? INTERVAL_MS[q.interval]\n : DEFAULT_INTERVAL_MS;\n const body = {\n data: {\n type: 'timeseries_request',\n attributes: {\n from: fromMs,\n to: now,\n interval: intervalMs,\n queries: [\n {\n name: 'a',\n data_source: 'metrics',\n query: q.query,\n },\n ],\n formulas: [{ formula: 'a' }],\n },\n },\n };\n const res = await this.postJson<DatadogTimeseriesResponse>(\n this.buildMetricsUrl(),\n body,\n 'metric_queries',\n signal,\n );\n items.push({\n queryName: q.name,\n query: q.query,\n response: res.body,\n });\n }\n return { items, next: null };\n }\n\n private async writeMonitorsBatch(\n storage: StorageHandle,\n items: MonitorsBatchItem[],\n ): Promise<void> {\n const writeEntities = this.isResourceEnabled('monitors');\n const writeEvents = this.isResourceEnabled('monitor_events');\n\n for (const item of items) {\n const m = item.monitor;\n const createdMs = parseEpoch(m.created, 'iso');\n const modifiedMs = parseEpoch(m.modified, 'iso');\n const stateModifiedMs =\n m.overall_state_modified !== undefined &&\n m.overall_state_modified !== null\n ? parseEpoch(m.overall_state_modified, 'iso')\n : null;\n if (createdMs === null || modifiedMs === null) {\n console.warn(\n `[connector-datadog] skipping monitor ${m.id} with unparseable created/modified timestamps`,\n );\n continue;\n }\n const updatedMs = Math.max(modifiedMs, stateModifiedMs ?? 0);\n\n const attributes: Record<string, JSONValue> = {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n status: m.status,\n priority: m.priority,\n tags: m.tags,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n stateModifiedAt: stateModifiedMs,\n };\n\n if (writeEvents) {\n const prior = await storage.getEntity('datadog_monitor', String(m.id));\n const priorStatus =\n prior !== null &&\n typeof prior.attributes === 'object' &&\n prior.attributes !== null\n ? (prior.attributes as { status?: string }).status\n : undefined;\n if (\n priorStatus !== m.status &&\n stateModifiedMs !== null &&\n Number.isFinite(stateModifiedMs)\n ) {\n await storage.event({\n name: 'datadog_monitor_event',\n start_ts: stateModifiedMs,\n end_ts: null,\n attributes: {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n fromStatus: priorStatus ?? null,\n toStatus: m.status,\n priority: m.priority,\n tags: m.tags,\n },\n });\n }\n }\n\n if (writeEntities) {\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n } else if (writeEvents) {\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n }\n }\n }\n\n private async writeIncidents(\n storage: StorageHandle,\n incidents: DatadogIncident[],\n ): Promise<void> {\n for (const inc of incidents) {\n const createdMs = parseEpoch(inc.attributes.created, 'iso');\n if (createdMs === null) {\n console.warn(\n `[connector-datadog] skipping incident ${inc.id} with unparseable created timestamp`,\n );\n continue;\n }\n const modifiedMs = inc.attributes.modified\n ? parseEpoch(inc.attributes.modified, 'iso')\n : null;\n const resolvedMs = inc.attributes.resolved\n ? parseEpoch(inc.attributes.resolved, 'iso')\n : null;\n await storage.entity({\n type: 'datadog_incident',\n id: inc.id,\n attributes: {\n incidentId: inc.id,\n title: inc.attributes.title,\n severity: inc.attributes.severity ?? null,\n state: inc.attributes.state ?? null,\n customerImpactScope: inc.attributes.customer_impact_scope ?? null,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n resolvedAt: resolvedMs,\n },\n updated_at: Math.max(createdMs, modifiedMs ?? 0, resolvedMs ?? 0),\n });\n }\n }\n\n private async writeSlos(\n storage: StorageHandle,\n slos: DatadogSlo[],\n ): Promise<void> {\n const sliSamples: Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }> = [];\n const entities: Entity[] = [];\n for (const s of slos) {\n const createdMs =\n s.created_at !== null && s.created_at !== undefined\n ? parseEpoch(s.created_at, 's')\n : null;\n const modifiedMs =\n s.modified_at !== null && s.modified_at !== undefined\n ? parseEpoch(s.modified_at, 's')\n : null;\n const targets = s.thresholds.map((t) => ({\n timeframe: t.timeframe,\n target: t.target,\n }));\n const primaryTarget = s.thresholds[0]?.target ?? null;\n const latestStatus = (s.overall_status ?? []).find(\n (st) => st.sli_value !== null && st.sli_value !== undefined,\n );\n const latestSli = latestStatus?.sli_value ?? null;\n entities.push({\n type: 'datadog_slo',\n id: s.id,\n attributes: {\n sloId: s.id,\n name: s.name,\n sloType: s.type,\n thresholds: targets as unknown as JSONValue,\n target: primaryTarget,\n latestSliValue: latestSli,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n },\n updated_at: modifiedMs ?? createdMs ?? Date.now(),\n });\n\n for (const status of s.overall_status ?? []) {\n const ts =\n status.indexed_at !== null && status.indexed_at !== undefined\n ? parseEpoch(status.indexed_at, 's')\n : null;\n const value = status.sli_value;\n if (\n ts === null ||\n value === null ||\n value === undefined ||\n !Number.isFinite(value)\n ) {\n continue;\n }\n sliSamples.push({\n name: 'datadog_slo_sli',\n ts,\n value,\n attributes: { sloId: s.id, sloType: s.type },\n });\n }\n }\n for (const entity of entities) {\n await storage.entity(entity);\n }\n if (sliSamples.length > 0) {\n await storage.metrics(sliSamples, { names: ['datadog_slo_sli'] });\n }\n }\n\n private async writeMetrics(\n storage: StorageHandle,\n items: MetricsBatchItem[],\n ): Promise<void> {\n if (items.length === 0) {\n return;\n }\n const samplesByName: Map<\n string,\n Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }>\n > = new Map();\n for (const item of items) {\n const attrs = item.response.data.attributes;\n const times = attrs.times ?? [];\n const series = attrs.series ?? [];\n const values = attrs.values ?? [];\n for (let s = 0; s < series.length; s++) {\n const seriesValues = values[s];\n if (!seriesValues) {\n continue;\n }\n const tagsArr = series[s]?.group_tags ?? [];\n const tagsStr = tagsArr.length > 0 ? tagsArr.join(',') : '*';\n for (let t = 0; t < times.length; t++) {\n const rawTs = times[t];\n const rawValue = seriesValues[t];\n if (rawTs === undefined || rawValue === undefined) {\n continue;\n }\n const ts = parseEpoch(rawTs, 'ms');\n if (ts === null || !Number.isFinite(rawValue)) {\n continue;\n }\n const name = `datadog_metric.${item.queryName}`;\n let bucket = samplesByName.get(name);\n if (!bucket) {\n bucket = [];\n samplesByName.set(name, bucket);\n }\n bucket.push({\n name,\n ts,\n value: rawValue,\n attributes: {\n queryName: item.queryName,\n query: item.query,\n tags: tagsStr,\n },\n });\n }\n }\n }\n for (const [name, samples] of samplesByName) {\n await storage.metrics(samples, { names: [name] });\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<DatadogPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'monitors':\n return this.fetchMonitorsPage(page, options, sig);\n case 'incidents':\n return this.fetchIncidentsPage(page, options, sig);\n case 'slos':\n return this.fetchSlos(sig);\n case 'metrics':\n return this.fetchMetrics(options, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n switch (phase) {\n case 'monitors':\n if (this.isResourceEnabled('monitor_events')) {\n await storage.events([], { names: ['datadog_monitor_event'] });\n }\n break;\n case 'incidents':\n await storage.entities([], { types: ['datadog_incident'] });\n break;\n case 'slos':\n await storage.entities([], { types: ['datadog_slo'] });\n await storage.metrics([], { names: ['datadog_slo_sli'] });\n break;\n case 'metrics':\n for (const q of this.settings.metricQueries ?? []) {\n await storage.metrics([], {\n names: [`datadog_metric.${q.name}`],\n });\n }\n break;\n }\n }\n switch (phase) {\n case 'monitors':\n return this.writeMonitorsBatch(\n storage,\n items as MonitorsBatchItem[],\n );\n case 'incidents':\n return this.writeIncidents(storage, items as DatadogIncident[]);\n case 'slos':\n return this.writeSlos(storage, items as DatadogSlo[]);\n case 'metrics':\n return this.writeMetrics(storage, items as MetricsBatchItem[]);\n }\n },\n });\n }\n}\n","import { DatadogConnector } from './datadog';\n\nexport {\n configFields,\n doc,\n DatadogConnector,\n id,\n datadogResources as resources,\n} from './datadog';\nexport type { DatadogResource, DatadogSettings } from './datadog';\nexport default DatadogConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AEUO,SAAS,wBACd,QACiB;AACjB,QAAM,EAAE,iBAAiB,aAAa,WAAW,gBAAgB,IAAI;AACrE,QAAM,aAAa,cAAc,MAAM,MAAO;AAC9C,SAAO;IACL,MAAM,GAAG;AACP,YAAM,eAAe,EAAE,IAAI,eAAe;AAC1C,UAAI,iBAAiB,QAAQ,aAAa,KAAK,MAAM,IAAI;AACvD,eAAO;MACT;AACA,YAAM,YAAY,OAAO,YAAY;AACrC,UAAI,CAAC,OAAO,SAAS,SAAS,GAAG;AAC/B,eAAO;MACT;AACA,YAAM,WAAW,EAAE,IAAI,WAAW;AAClC,UAAI,aAAa,MAAM;AACrB,YAAI,oBAAoB,QAAW;AACjC,iBAAO;QACT;AACA,eAAO;UACL;UACA,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,eAAe;QAChD;MACF;AACA,UAAI,SAAS,KAAK,MAAM,IAAI;AAC1B,eAAO;MACT;AACA,YAAM,QAAQ,OAAO,QAAQ;AAC7B,UAAI,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG;AACxC,eAAO;MACT;AACA,YAAM,UAAU,QAAQ;AACxB,UAAI,CAAC,OAAO,SAAS,OAAO,GAAG;AAC7B,eAAO;MACT;AACA,aAAO,EAAE,WAAW,SAAS,IAAI,KAAK,OAAO,EAAE;IACjD;EACF;AACF;AEhDO,SAAS,mBACd,SACe;AACf,QAAM,EAAE,KAAK,MAAM,UAAU,WAAW,SAAS,IAAI;AACrD,MAAI,QAAQ,MAAM;AAChB,WAAO;EACT;AACA,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG;AACrB,QAAI,EAAE,a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CAAC,GAAG,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC;AACrD,oBAAM,QAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,iBAAiB,EAAE,CAAC;AACxD;AAAA,YACF,KAAK;AACH,yBAAW,KAAK,KAAK,SAAS,iBAAiB,CAAC,GAAG;AACjD,sBAAM,QAAQ,QAAQ,CAAC,GAAG;AAAA,kBACxB,OAAO,CAAC,kBAAkB,EAAE,IAAI,EAAE;AAAA,gBACpC,CAAC;AAAA,cACH;AACA;AAAA,UACJ;AAAA,QACF;AACA,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,mBAAO,KAAK;AAAA,cACV;AAAA,cACA;AAAA,YACF;AAAA,UACF,KAAK;AACH,mBAAO,KAAK,eAAe,SAAS,KAA0B;AAAA,UAChE,KAAK;AACH,mBAAO,KAAK,UAAU,SAAS,KAAqB;AAAA,UACtD,KAAK;AACH,mBAAO,KAAK,aAAa,SAAS,KAA2B;AAAA,QACjE;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC/lCA,IAAO,gBAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/datadog.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n sanitizeAllowedUrl,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type Entity,\n type FetchSpec,\n type FilterClause,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nconst metricQuerySchema = z.object({\n name: z\n .string()\n .min(1)\n .regex(/^[a-zA-Z0-9_]+$/, {\n message: 'Metric name must be alphanumeric / underscore',\n }),\n query: z.string().min(1),\n interval: z\n .enum(['5m', '15m', '1h', '1d'])\n .optional()\n .describe('Aggregation interval - defaults to 1h.'),\n});\n\nconst datadogSiteSchema = z\n .string()\n .trim()\n .min(1)\n .toLowerCase()\n .regex(/^(?:[a-z0-9-]+\\.)*(?:datadoghq\\.com|datadoghq\\.eu|ddog-gov\\.com)$/, {\n message:\n 'Site must be a Datadog hostname (e.g. datadoghq.com, datadoghq.eu, us3.datadoghq.com)',\n });\n\nexport const configFields = defineConfigFields(\n z.object({\n apiKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'API Key',\n description:\n 'Datadog API key. Create at Datadog → Organization Settings → API Keys.',\n placeholder: 'dd_api_key',\n secret: true,\n }),\n appKey: z.object({ $secret: z.string().min(1) }).meta({\n label: 'Application Key',\n description:\n 'Datadog Application key. Create at Datadog → Organization Settings → Application Keys. Used in tandem with the API key to authenticate REST calls.',\n placeholder: 'dd_app_key',\n secret: true,\n }),\n site: datadogSiteSchema.optional().meta({\n label: 'Site',\n description:\n 'Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`). Defaults to `datadoghq.com`.',\n placeholder: 'datadoghq.com',\n }),\n metricQueries: z.array(metricQuerySchema).nonempty().optional().meta({\n label: 'Metric queries (optional)',\n description:\n 'User-declared metric timeseries queries. Each entry produces `datadog_metric` samples named `<name>` from the Datadog Metrics Query API.',\n }),\n resources: z\n .array(\n z.enum([\n 'monitors',\n 'monitor_events',\n 'incidents',\n 'slos',\n 'metric_queries',\n ]),\n )\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n \"Which Datadog resources to sync. Omit to sync all of them. 'monitor_events' depends on 'monitors' being fetched - enabling it without 'monitors' still runs the monitors query but skips writing monitor entities.\",\n }),\n metricsLookbackHours: z.number().int().positive().max(168).optional().meta({\n label: 'Metrics lookback (hours)',\n description:\n 'Window of metric samples to pull on each sync, in hours. Defaults to 24.',\n placeholder: '24',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Datadog',\n category: 'infrastructure',\n brandColor: '#632CA6',\n tagline:\n 'Sync monitor health, monitor state-change events, incidents, SLOs, and user-declared metric queries from a Datadog org.',\n vendor: {\n name: 'Datadog',\n domain: 'datadoghq.com',\n apiDocs: 'https://docs.datadoghq.com/api/latest/',\n website: 'https://www.datadoghq.com',\n },\n auth: {\n summary:\n 'A Datadog API key and Application key are required, scoped to the org and site you want to read from. Both are stored as secrets.',\n setup: [\n 'Open Datadog → Organization Settings → API Keys and create (or copy) an API key.',\n 'Open Datadog → Organization Settings → Application Keys and create an Application key with read access to monitors, incidents, SLOs, and metrics.',\n 'Store both as secrets and reference them from the connector config as `apiKey: secret(\"DD_API_KEY\")` and `appKey: secret(\"DD_APP_KEY\")`.',\n 'Set `site` to your Datadog site host (e.g. `datadoghq.com`, `datadoghq.eu`, `us3.datadoghq.com`); it defaults to `datadoghq.com`.',\n ],\n },\n rateLimit:\n 'Datadog returns X-RateLimit-Remaining / X-RateLimit-Reset headers (reset in seconds) on the v2 endpoints, wired through the standard rate-limit policy so the host scheduler backs off on near-empty windows.',\n limitations: [\n 'Logs and RUM session data are out of scope (high volume, low dashboard signal).',\n 'Synthetic monitor results are out of scope.',\n 'Monitor entities are not cleared on a full sync - the monitor_events diff depends on the prior status being stored.',\n 'Pagination URLs are pinned to the configured `api.<site>` host.',\n 'SLI values are read per SLO from the SLO history endpoint, so the SLO phase issues one extra request per SLO each sync.',\n 'The SLO list is capped at 1000 entries per sync; orgs with more SLOs will not see the remainder.',\n ],\n});\n\nexport type DatadogResource =\n | 'monitors'\n | 'monitor_events'\n | 'incidents'\n | 'slos'\n | 'metric_queries';\n\nexport interface DatadogMetricQuery {\n name: string;\n query: string;\n interval?: '5m' | '15m' | '1h' | '1d';\n}\n\nexport interface DatadogSettings {\n site?: string;\n metricQueries?: readonly DatadogMetricQuery[];\n resources?: readonly DatadogResource[];\n metricsLookbackHours?: number;\n}\n\nconst datadogCredentials = {\n apiKey: {\n description: 'Datadog API key',\n auth: 'required' as const,\n },\n appKey: {\n description: 'Datadog Application key',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype DatadogCredentials = typeof datadogCredentials;\n\nconst datadogRateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\nconst PHASE_ORDER = ['monitors', 'incidents', 'slos', 'metrics'] as const;\n\ntype DatadogPhase = (typeof PHASE_ORDER)[number];\n\ntype DatadogSyncCursor = ChunkedSyncCursor<DatadogPhase, string>;\n\nconst isDatadogSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\ntype DatadogMonitorStatus =\n | 'OK'\n | 'Alert'\n | 'Warn'\n | 'No Data'\n | 'Ignored'\n | 'Skipped'\n | 'Unknown';\n\ninterface DatadogMonitor {\n id: number;\n name: string;\n type: string;\n status: DatadogMonitorStatus;\n priority: number | null;\n tags: string[];\n overall_state_modified?: string | null;\n created: string;\n modified: string;\n}\n\ninterface DatadogMonitorSearchResponse {\n monitors: DatadogMonitor[];\n metadata: {\n page: number;\n page_count: number;\n per_page: number;\n total_count: number;\n };\n}\n\ninterface DatadogIncident {\n id: string;\n type: 'incidents';\n attributes: {\n title: string;\n severity?: string | null;\n state?: string | null;\n customer_impact_scope?: string | null;\n created: string;\n modified?: string | null;\n resolved?: string | null;\n };\n}\n\ninterface DatadogIncidentsResponse {\n data: DatadogIncident[];\n meta?: {\n pagination?: {\n next_offset?: number | null;\n offset?: number;\n size?: number;\n };\n };\n}\n\ninterface DatadogSloThreshold {\n timeframe: string;\n target: number;\n warning?: number | null;\n}\n\ninterface DatadogSlo {\n id: string;\n name: string;\n type: string;\n thresholds: DatadogSloThreshold[];\n created_at?: number | null;\n modified_at?: number | null;\n}\n\ninterface DatadogSlosResponse {\n data: DatadogSlo[];\n}\n\ninterface DatadogSloHistoryResponse {\n data?: {\n to_ts?: number | null;\n from_ts?: number | null;\n overall?: {\n sli_value?: number | null;\n } | null;\n } | null;\n}\n\ninterface SloSliSample {\n value: number;\n ts: number;\n}\n\ninterface SlosBatchItem {\n slo: DatadogSlo;\n sli: SloSliSample | null;\n}\n\ninterface DatadogTimeseriesResponse {\n data: {\n type: 'timeseries_response';\n attributes: {\n series?: Array<{\n group_tags?: string[];\n query_index?: number;\n unit?: Array<{ name?: string } | null> | null;\n }>;\n times?: number[];\n values?: Array<Array<number | null>>;\n };\n };\n}\n\ninterface MonitorsBatchItem {\n monitor: DatadogMonitor;\n}\n\ninterface MetricsBatchItem {\n queryName: string;\n query: string;\n response: DatadogTimeseriesResponse;\n}\n\nconst idString = z.string().min(1);\n\nconst monitorSchema = z.object({\n id: z.number().int().nonnegative(),\n name: z.string(),\n type: z.string(),\n status: z.enum([\n 'OK',\n 'Alert',\n 'Warn',\n 'No Data',\n 'Ignored',\n 'Skipped',\n 'Unknown',\n ]),\n priority: z.number().int().nullable(),\n tags: z.array(z.string()),\n overall_state_modified: z.iso.datetime().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime(),\n});\n\nconst monitorSearchResponseSchema = z.object({\n monitors: z.array(monitorSchema),\n metadata: z.object({\n page: z.number().int().nonnegative(),\n page_count: z.number().int().nonnegative(),\n per_page: z.number().int().positive(),\n total_count: z.number().int().nonnegative(),\n }),\n});\n\nconst incidentSchema = z.object({\n id: idString,\n type: z.literal('incidents'),\n attributes: z.object({\n title: z.string(),\n severity: z.string().nullable().optional(),\n state: z.string().nullable().optional(),\n customer_impact_scope: z.string().nullable().optional(),\n created: z.iso.datetime(),\n modified: z.iso.datetime().nullable().optional(),\n resolved: z.iso.datetime().nullable().optional(),\n }),\n});\n\nconst incidentsResponseSchema = z.object({\n data: z.array(incidentSchema),\n meta: z\n .object({\n pagination: z\n .object({\n next_offset: z.number().int().nullable().optional(),\n offset: z.number().int().optional(),\n size: z.number().int().optional(),\n })\n .optional(),\n })\n .optional(),\n});\n\nconst sloSchema = z.object({\n id: idString,\n name: z.string(),\n type: z.string(),\n thresholds: z.array(\n z.object({\n timeframe: z.string(),\n target: z.number(),\n warning: z.number().nullable().optional(),\n }),\n ),\n created_at: z.number().nullable().optional(),\n modified_at: z.number().nullable().optional(),\n});\n\nconst slosResponseSchema = z.object({\n data: z.array(sloSchema),\n});\n\nconst sloHistoryResponseSchema = z.object({\n data: z\n .object({\n to_ts: z.number().nullable().optional(),\n from_ts: z.number().nullable().optional(),\n overall: z\n .object({\n sli_value: z.number().nullable().optional(),\n })\n .nullable()\n .optional(),\n })\n .nullable()\n .optional(),\n});\n\nconst timeseriesResponseSchema = z.object({\n data: z.object({\n type: z.literal('timeseries_response'),\n attributes: z.object({\n series: z\n .array(\n z.object({\n group_tags: z.array(z.string()).optional(),\n query_index: z.number().int().optional(),\n }),\n )\n .optional(),\n times: z.array(z.number()).optional(),\n values: z.array(z.array(z.number().nullable())).optional(),\n }),\n }),\n});\n\nconst DEFAULT_SITE = 'datadoghq.com';\nconst MONITORS_PAGE_SIZE = 100;\nconst INCIDENTS_PAGE_SIZE = 50;\nconst DEFAULT_METRICS_LOOKBACK_HOURS = 24;\nconst DEFAULT_SLO_HISTORY_WINDOW_S = 7 * 24 * 60 * 60;\nconst TIMEFRAME_UNIT_SECONDS: Record<string, number> = {\n h: 60 * 60,\n d: 24 * 60 * 60,\n w: 7 * 24 * 60 * 60,\n};\nconst INTERVAL_MS: Record<\n NonNullable<DatadogMetricQuery['interval']>,\n number\n> = {\n '5m': 5 * 60 * 1000,\n '15m': 15 * 60 * 1000,\n '1h': 60 * 60 * 1000,\n '1d': 24 * 60 * 60 * 1000,\n};\nconst DEFAULT_INTERVAL_MS = INTERVAL_MS['1h'];\n\nexport const datadogResources = defineResources({\n datadog_monitor: {\n shape: 'entity',\n filterable: [\n {\n field: 'status',\n ops: ['eq'],\n values: [\n 'OK',\n 'Alert',\n 'Warn',\n 'No Data',\n 'Ignored',\n 'Skipped',\n 'Unknown',\n ],\n },\n ],\n description:\n 'Datadog monitors with name, type, current status (OK / Alert / Warn / No Data / Ignored / Skipped / Unknown), priority, and tags.',\n endpoint: 'GET /api/v1/monitor/search',\n responses: { monitors: monitorSearchResponseSchema },\n },\n datadog_monitor_event: {\n shape: 'event',\n filterable: [],\n description:\n \"Monitor state-transition events, emitted whenever a monitor's status changes from its previously-stored value.\",\n notes:\n \"Derived by diffing each monitor's current status against the last-synced status, so it depends on the monitors phase running and on prior monitor state being stored.\",\n },\n datadog_incident: {\n shape: 'entity',\n filterable: [],\n description:\n 'Datadog incidents with title, severity, state, and created / resolved timestamps.',\n endpoint: 'GET /api/v2/incidents',\n responses: { incidents: incidentsResponseSchema },\n },\n datadog_slo: {\n shape: 'entity',\n filterable: [],\n description:\n 'Service Level Objectives with type, thresholds, primary target, and latest SLI value.',\n endpoint: 'GET /api/v1/slo',\n responses: { slos: slosResponseSchema },\n },\n datadog_slo_sli: {\n shape: 'metric',\n description:\n 'SLI value samples per SLO, one per sync, read from the SLO history endpoint over a window derived from the SLO threshold timeframes.',\n unit: 'percent',\n endpoint: 'GET /api/v1/slo/{slo_id}/history',\n dimensions: [\n { name: 'sloId', description: 'Datadog SLO id.' },\n { name: 'sloType', description: 'SLO type (metric, monitor, etc.).' },\n ],\n responses: { slo_history: sloHistoryResponseSchema },\n },\n datadog_metric: {\n shape: 'metric',\n dynamic: true,\n description:\n 'User-declared metric timeseries samples, stored as `datadog_metric.<query name>`, from the Datadog Metrics Query API.',\n endpoint: 'POST /api/v2/query/timeseries',\n dimensions: [\n { name: 'queryName', description: 'The user-declared query name.' },\n { name: 'query', description: 'The Datadog metrics query string.' },\n {\n name: 'tags',\n description:\n 'Comma-joined group tags for the series, or `*` when the series is ungrouped.',\n },\n ],\n responses: { metric_queries: timeseriesResponseSchema },\n },\n});\n\nexport const id = 'datadog';\n\nfunction parseTimeframeSeconds(timeframe: string): number | null {\n const match = /^(\\d+)([hdw])$/.exec(timeframe.trim().toLowerCase());\n if (!match) {\n return null;\n }\n const amount = Number(match[1]);\n const unitSeconds = TIMEFRAME_UNIT_SECONDS[match[2]!];\n if (!Number.isFinite(amount) || amount <= 0 || unitSeconds === undefined) {\n return null;\n }\n return amount * unitSeconds;\n}\n\nfunction pushableEq(\n filter: FilterClause[] | undefined,\n field: string,\n): string | null {\n if (!filter) {\n return null;\n }\n for (const clause of filter) {\n if (\n 'field' in clause &&\n clause.field === field &&\n clause.op === 'eq' &&\n typeof clause.value === 'string'\n ) {\n return clause.value;\n }\n }\n return null;\n}\n\nexport class DatadogConnector extends BaseConnector<\n DatadogSettings,\n DatadogCredentials\n> {\n static readonly id = id;\n\n static readonly resources = datadogResources;\n\n static readonly schemas = schemasFromResources(datadogResources);\n\n static create(input: unknown, ctx?: ConnectorContext): DatadogConnector {\n const parsed = configFields.parse(input);\n return new DatadogConnector(\n {\n site: parsed.site,\n metricQueries: parsed.metricQueries,\n resources: parsed.resources,\n metricsLookbackHours: parsed.metricsLookbackHours,\n },\n { apiKey: parsed.apiKey, appKey: parsed.appKey },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = datadogCredentials;\n\n private get apiHost(): string {\n return `api.${(this.settings.site ?? DEFAULT_SITE).toLowerCase()}`;\n }\n\n private get apiBase(): string {\n return `https://${this.apiHost}`;\n }\n\n private buildHeaders(): Record<string, string> {\n return {\n 'DD-API-KEY': this.creds.apiKey,\n 'DD-APPLICATION-KEY': this.creds.appKey,\n 'User-Agent': connectorUserAgent('datadog'),\n };\n }\n\n private fetch<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n private postJson<T>(\n url: string,\n body: unknown,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.post<T>(url, {\n resource,\n headers: {\n ...this.buildHeaders(),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n signal,\n rateLimit: datadogRateLimit,\n });\n }\n\n private activePhases(): DatadogPhase[] {\n return selectActivePhases<DatadogResource, DatadogPhase>(\n (r) => {\n switch (r) {\n case 'monitors':\n case 'monitor_events':\n return 'monitors';\n case 'incidents':\n return 'incidents';\n case 'slos':\n return 'slos';\n case 'metric_queries':\n return 'metrics';\n }\n },\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n private allowedPagePath(phase: DatadogPhase): string {\n switch (phase) {\n case 'monitors':\n return '/api/v1/monitor/search';\n case 'incidents':\n return '/api/v2/incidents';\n case 'slos':\n return '/api/v1/slo';\n case 'metrics':\n return '/api/v2/query/timeseries';\n }\n }\n\n private sanitizePageUrl(\n phase: DatadogPhase,\n pageUrl: string | null,\n ): string | null {\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: this.apiHost,\n pathname: this.allowedPagePath(phase),\n });\n }\n\n private resolveCursor(cursor: unknown): DatadogSyncCursor | undefined {\n if (!isDatadogSyncCursor(cursor)) {\n return undefined;\n }\n return {\n phase: cursor.phase,\n page: this.sanitizePageUrl(cursor.phase, cursor.page),\n };\n }\n\n private singleSpec(\n options: SyncOptions,\n resource: string,\n ): FetchSpec | undefined {\n const specs = options.fetchSpecs?.[resource];\n return specs && specs.length === 1 ? specs[0] : undefined;\n }\n\n private buildInitialMonitorsUrl(options: SyncOptions): string {\n const u = new URL(`${this.apiBase}/api/v1/monitor/search`);\n u.searchParams.set('per_page', String(MONITORS_PAGE_SIZE));\n u.searchParams.set('page', '0');\n u.searchParams.set('sort', 'status,desc');\n const status = pushableEq(\n this.singleSpec(options, 'datadog_monitor')?.filter,\n 'status',\n );\n if (status !== null) {\n u.searchParams.set('query', `status:\"${status}\"`);\n }\n return u.toString();\n }\n\n private buildNextMonitorsUrl(currentUrl: string, nextPage: number): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page', String(nextPage));\n return u.toString();\n }\n\n private buildInitialIncidentsUrl(options: SyncOptions): string {\n const u = new URL(`${this.apiBase}/api/v2/incidents`);\n u.searchParams.set('page[size]', String(INCIDENTS_PAGE_SIZE));\n u.searchParams.set('page[offset]', '0');\n u.searchParams.set('include', '');\n if (options.since) {\n u.searchParams.set('filter[created.from]', options.since);\n }\n return u.toString();\n }\n\n private buildNextIncidentsUrl(\n currentUrl: string,\n nextOffset: number,\n ): string {\n const u = new URL(currentUrl);\n u.searchParams.set('page[offset]', String(nextOffset));\n return u.toString();\n }\n\n private buildSlosUrl(): string {\n const u = new URL(`${this.apiBase}/api/v1/slo`);\n u.searchParams.set('limit', '1000');\n u.searchParams.set('offset', '0');\n return u.toString();\n }\n\n private buildSloHistoryUrl(\n sloId: string,\n fromTs: number,\n toTs: number,\n ): string {\n const u = new URL(\n `${this.apiBase}/api/v1/slo/${encodeURIComponent(sloId)}/history`,\n );\n u.searchParams.set('from_ts', String(fromTs));\n u.searchParams.set('to_ts', String(toTs));\n return u.toString();\n }\n\n private sloHistoryWindowSeconds(slo: DatadogSlo): number {\n let maxSeconds = 0;\n for (const threshold of slo.thresholds) {\n const seconds = parseTimeframeSeconds(threshold.timeframe);\n if (seconds !== null && seconds > maxSeconds) {\n maxSeconds = seconds;\n }\n }\n return maxSeconds > 0 ? maxSeconds : DEFAULT_SLO_HISTORY_WINDOW_S;\n }\n\n private buildMetricsUrl(): string {\n return `${this.apiBase}/api/v2/query/timeseries`;\n }\n\n private async fetchMonitorsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MonitorsBatchItem[]; next: string | null }> {\n const url = page ?? this.buildInitialMonitorsUrl(options);\n const res = await this.fetch<DatadogMonitorSearchResponse>(\n url,\n 'monitors',\n signal,\n );\n const meta = res.body.metadata;\n const currentPage = meta.page;\n const totalPages = meta.page_count;\n const hasNext = currentPage + 1 < totalPages;\n const next = hasNext\n ? this.sanitizePageUrl(\n 'monitors',\n this.buildNextMonitorsUrl(url, currentPage + 1),\n )\n : null;\n return {\n items: res.body.monitors.map((m) => ({ monitor: m })),\n next,\n };\n }\n\n private async fetchIncidentsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: DatadogIncident[]; next: string | null }> {\n const url = page ?? this.buildInitialIncidentsUrl(options);\n const res = await this.fetch<DatadogIncidentsResponse>(\n url,\n 'incidents',\n signal,\n );\n const nextOffset = res.body.meta?.pagination?.next_offset ?? null;\n const incidents = res.body.data;\n const cutoff = options.since\n ? (parseEpoch(options.since, 'iso') ?? null)\n : null;\n const filtered =\n cutoff !== null\n ? incidents.filter((inc) => {\n const ts = parseEpoch(inc.attributes.created, 'iso');\n return ts === null || ts >= cutoff;\n })\n : incidents;\n const lastIncident = incidents.at(-1);\n const lastTs = lastIncident\n ? parseEpoch(lastIncident.attributes.created, 'iso')\n : null;\n const cutoffReached = cutoff !== null && lastTs !== null && lastTs < cutoff;\n const next =\n !cutoffReached && nextOffset !== null\n ? this.sanitizePageUrl(\n 'incidents',\n this.buildNextIncidentsUrl(url, nextOffset),\n )\n : null;\n return { items: filtered, next };\n }\n\n private async fetchSlos(\n signal: AbortSignal | undefined,\n ): Promise<{ items: SlosBatchItem[]; next: string | null }> {\n const res = await this.fetch<DatadogSlosResponse>(\n this.buildSlosUrl(),\n 'slos',\n signal,\n );\n const nowSeconds = Math.floor(Date.now() / 1000);\n const items: SlosBatchItem[] = [];\n for (const slo of res.body.data) {\n signal?.throwIfAborted();\n const sli = await this.fetchSloSli(slo, nowSeconds, signal);\n items.push({ slo, sli });\n }\n return { items, next: null };\n }\n\n private async fetchSloSli(\n slo: DatadogSlo,\n nowSeconds: number,\n signal: AbortSignal | undefined,\n ): Promise<SloSliSample | null> {\n const fromTs = nowSeconds - this.sloHistoryWindowSeconds(slo);\n const res = await this.fetch<DatadogSloHistoryResponse>(\n this.buildSloHistoryUrl(slo.id, fromTs, nowSeconds),\n 'slos',\n signal,\n );\n const value = res.body.data?.overall?.sli_value;\n if (value === null || value === undefined || !Number.isFinite(value)) {\n return null;\n }\n const rawTs = res.body.data?.to_ts;\n const tsSeconds =\n rawTs !== null && rawTs !== undefined && Number.isFinite(rawTs)\n ? rawTs\n : nowSeconds;\n const ts = parseEpoch(tsSeconds, 's');\n if (ts === null) {\n return null;\n }\n return { value, ts };\n }\n\n private async fetchMetrics(\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: MetricsBatchItem[]; next: string | null }> {\n const queries = this.settings.metricQueries ?? [];\n if (queries.length === 0) {\n return { items: [], next: null };\n }\n const lookbackHours =\n this.settings.metricsLookbackHours ?? DEFAULT_METRICS_LOOKBACK_HOURS;\n const now = Date.now();\n const sinceMs = options.since ? parseEpoch(options.since, 'iso') : null;\n const fromMs =\n sinceMs !== null ? sinceMs : now - lookbackHours * 60 * 60 * 1000;\n const items: MetricsBatchItem[] = [];\n for (const q of queries) {\n signal?.throwIfAborted();\n const intervalMs = q.interval\n ? INTERVAL_MS[q.interval]\n : DEFAULT_INTERVAL_MS;\n const body = {\n data: {\n type: 'timeseries_request',\n attributes: {\n from: fromMs,\n to: now,\n interval: intervalMs,\n queries: [\n {\n name: 'a',\n data_source: 'metrics',\n query: q.query,\n },\n ],\n formulas: [{ formula: 'a' }],\n },\n },\n };\n const res = await this.postJson<DatadogTimeseriesResponse>(\n this.buildMetricsUrl(),\n body,\n 'metric_queries',\n signal,\n );\n items.push({\n queryName: q.name,\n query: q.query,\n response: res.body,\n });\n }\n return { items, next: null };\n }\n\n private async writeMonitorsBatch(\n storage: StorageHandle,\n items: MonitorsBatchItem[],\n ): Promise<void> {\n const writeEntities = this.isResourceEnabled('monitors');\n const writeEvents = this.isResourceEnabled('monitor_events');\n\n for (const item of items) {\n const m = item.monitor;\n const createdMs = parseEpoch(m.created, 'iso');\n const modifiedMs = parseEpoch(m.modified, 'iso');\n const stateModifiedMs =\n m.overall_state_modified !== undefined &&\n m.overall_state_modified !== null\n ? parseEpoch(m.overall_state_modified, 'iso')\n : null;\n if (createdMs === null || modifiedMs === null) {\n console.warn(\n `[connector-datadog] skipping monitor ${m.id} with unparseable created/modified timestamps`,\n );\n continue;\n }\n const updatedMs = Math.max(modifiedMs, stateModifiedMs ?? 0);\n\n const attributes: Record<string, JSONValue> = {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n status: m.status,\n priority: m.priority,\n tags: m.tags,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n stateModifiedAt: stateModifiedMs,\n };\n\n if (writeEvents) {\n const prior = await storage.getEntity('datadog_monitor', String(m.id));\n const priorStatus =\n prior !== null &&\n typeof prior.attributes === 'object' &&\n prior.attributes !== null\n ? (prior.attributes as { status?: string }).status\n : undefined;\n if (\n priorStatus !== m.status &&\n stateModifiedMs !== null &&\n Number.isFinite(stateModifiedMs)\n ) {\n await storage.event({\n name: 'datadog_monitor_event',\n start_ts: stateModifiedMs,\n end_ts: null,\n attributes: {\n monitorId: m.id,\n name: m.name,\n monitorType: m.type,\n fromStatus: priorStatus ?? null,\n toStatus: m.status,\n priority: m.priority,\n tags: m.tags,\n },\n });\n }\n }\n\n if (writeEntities) {\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n } else if (writeEvents) {\n await storage.entity({\n type: 'datadog_monitor',\n id: String(m.id),\n attributes,\n updated_at: updatedMs,\n });\n }\n }\n }\n\n private async writeIncidents(\n storage: StorageHandle,\n incidents: DatadogIncident[],\n ): Promise<void> {\n for (const inc of incidents) {\n const createdMs = parseEpoch(inc.attributes.created, 'iso');\n if (createdMs === null) {\n console.warn(\n `[connector-datadog] skipping incident ${inc.id} with unparseable created timestamp`,\n );\n continue;\n }\n const modifiedMs = inc.attributes.modified\n ? parseEpoch(inc.attributes.modified, 'iso')\n : null;\n const resolvedMs = inc.attributes.resolved\n ? parseEpoch(inc.attributes.resolved, 'iso')\n : null;\n await storage.entity({\n type: 'datadog_incident',\n id: inc.id,\n attributes: {\n incidentId: inc.id,\n title: inc.attributes.title,\n severity: inc.attributes.severity ?? null,\n state: inc.attributes.state ?? null,\n customerImpactScope: inc.attributes.customer_impact_scope ?? null,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n resolvedAt: resolvedMs,\n },\n updated_at: Math.max(createdMs, modifiedMs ?? 0, resolvedMs ?? 0),\n });\n }\n }\n\n private async writeSlos(\n storage: StorageHandle,\n items: SlosBatchItem[],\n ): Promise<void> {\n const sliSamples: Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }> = [];\n const entities: Entity[] = [];\n for (const { slo: s, sli } of items) {\n const createdMs =\n s.created_at !== null && s.created_at !== undefined\n ? parseEpoch(s.created_at, 's')\n : null;\n const modifiedMs =\n s.modified_at !== null && s.modified_at !== undefined\n ? parseEpoch(s.modified_at, 's')\n : null;\n const targets = s.thresholds.map((t) => ({\n timeframe: t.timeframe,\n target: t.target,\n }));\n const primaryTarget = s.thresholds[0]?.target ?? null;\n entities.push({\n type: 'datadog_slo',\n id: s.id,\n attributes: {\n sloId: s.id,\n name: s.name,\n sloType: s.type,\n thresholds: targets as unknown as JSONValue,\n target: primaryTarget,\n latestSliValue: sli?.value ?? null,\n createdAt: createdMs,\n modifiedAt: modifiedMs,\n },\n updated_at: modifiedMs ?? createdMs ?? Date.now(),\n });\n\n if (sli !== null) {\n sliSamples.push({\n name: 'datadog_slo_sli',\n ts: sli.ts,\n value: sli.value,\n attributes: { sloId: s.id, sloType: s.type },\n });\n }\n }\n for (const entity of entities) {\n await storage.entity(entity);\n }\n if (sliSamples.length > 0) {\n await storage.metrics(sliSamples, { names: ['datadog_slo_sli'] });\n }\n }\n\n private async writeMetrics(\n storage: StorageHandle,\n items: MetricsBatchItem[],\n ): Promise<void> {\n if (items.length === 0) {\n return;\n }\n const samplesByName: Map<\n string,\n Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }>\n > = new Map();\n for (const item of items) {\n const attrs = item.response.data.attributes;\n const times = attrs.times ?? [];\n const series = attrs.series ?? [];\n const values = attrs.values ?? [];\n for (let s = 0; s < series.length; s++) {\n const seriesValues = values[s];\n if (!seriesValues) {\n continue;\n }\n const tagsArr = series[s]?.group_tags ?? [];\n const tagsStr = tagsArr.length > 0 ? tagsArr.join(',') : '*';\n for (let t = 0; t < times.length; t++) {\n const rawTs = times[t];\n const rawValue = seriesValues[t];\n if (\n rawTs === undefined ||\n rawValue === undefined ||\n rawValue === null\n ) {\n continue;\n }\n const ts = parseEpoch(rawTs, 'ms');\n if (ts === null || !Number.isFinite(rawValue)) {\n continue;\n }\n const name = `datadog_metric.${item.queryName}`;\n let bucket = samplesByName.get(name);\n if (!bucket) {\n bucket = [];\n samplesByName.set(name, bucket);\n }\n bucket.push({\n name,\n ts,\n value: rawValue,\n attributes: {\n queryName: item.queryName,\n query: item.query,\n tags: tagsStr,\n },\n });\n }\n }\n }\n for (const [name, samples] of samplesByName) {\n await storage.metrics(samples, { names: [name] });\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<DatadogPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'monitors':\n return this.fetchMonitorsPage(page, options, sig);\n case 'incidents':\n return this.fetchIncidentsPage(page, options, sig);\n case 'slos':\n return this.fetchSlos(sig);\n case 'metrics':\n return this.fetchMetrics(options, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n switch (phase) {\n case 'monitors':\n if (this.isResourceEnabled('monitor_events')) {\n await storage.events([], { names: ['datadog_monitor_event'] });\n }\n break;\n case 'incidents':\n await storage.entities([], { types: ['datadog_incident'] });\n break;\n case 'slos':\n await storage.entities([], { types: ['datadog_slo'] });\n await storage.metrics([], { names: ['datadog_slo_sli'] });\n break;\n case 'metrics':\n for (const q of this.settings.metricQueries ?? []) {\n await storage.metrics([], {\n names: [`datadog_metric.${q.name}`],\n });\n }\n break;\n }\n }\n switch (phase) {\n case 'monitors':\n return this.writeMonitorsBatch(\n storage,\n items as MonitorsBatchItem[],\n );\n case 'incidents':\n return this.writeIncidents(storage, items as DatadogIncident[]);\n case 'slos':\n return this.writeSlos(storage, items as SlosBatchItem[]);\n case 'metrics':\n return this.writeMetrics(storage, items as MetricsBatchItem[]);\n }\n },\n });\n }\n}\n","import { DatadogConnector } from './datadog';\n\nexport {\n configFields,\n doc,\n DatadogConnector,\n id,\n datadogResources as resources,\n} from './datadog';\nexport type { DatadogResource, DatadogSettings } from './datadog';\nexport default DatadogConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AEUO,SAAS,wBACd,QACiB;AACjB,QAAM,EAAE,iBAAiB,aAAa,WAAW,gBAAgB,IAAI;AACrE,QAAM,aAAa,cAAc,MAAM,MAAO;AAC9C,SAAO;IACL,MAAM,GAAG;AACP,YAAM,eAAe,EAAE,IAAI,eAAe;AAC1C,UAAI,iBAAiB,QAAQ,aAAa,KAAK,MAAM,IAAI;AACvD,eAAO;MACT;AACA,YAAM,YAAY,OAAO,YAAY;AACrC,UAAI,CAAC,OAAO,SAAS,SAAS,GAAG;AAC/B,eAAO;MACT;AACA,YAAM,WAAW,EAAE,IAAI,WAAW;AAClC,UAAI,aAAa,MAAM;AACrB,Y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AAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,iBAAiB,EAAE,CAAC;AACxD;AAAA,YACF,KAAK;AACH,yBAAW,KAAK,KAAK,SAAS,iBAAiB,CAAC,GAAG;AACjD,sBAAM,QAAQ,QAAQ,CAAC,GAAG;AAAA,kBACxB,OAAO,CAAC,kBAAkB,EAAE,IAAI,EAAE;AAAA,gBACpC,CAAC;AAAA,cACH;AACA;AAAA,UACJ;AAAA,QACF;AACA,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,mBAAO,KAAK;AAAA,cACV;AAAA,cACA;AAAA,YACF;AAAA,UACF,KAAK;AACH,mBAAO,KAAK,eAAe,SAAS,KAA0B;AAAA,UAChE,KAAK;AACH,mBAAO,KAAK,UAAU,SAAS,KAAwB;AAAA,UACzD,KAAK;AACH,mBAAO,KAAK,aAAa,SAAS,KAA2B;AAAA,QACjE;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;AC/sCA,IAAO,gBAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rawdash/connector-datadog",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.0",
|
|
4
4
|
"description": "Rawdash connector for Datadog — metric queries, monitors, incidents, and SLOs",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"zod": "^4.4.3",
|
|
27
|
-
"@rawdash/core": "0.
|
|
27
|
+
"@rawdash/core": "0.26.0"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"fast-check": "^4.8.0",
|