@telemai/sdk 0.6.0 → 0.8.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 +37 -6
- package/dist/{chunk-TST6J3VA.js → chunk-274HRD4N.js} +34 -6
- package/dist/index.cjs +348 -92
- package/dist/index.d.cts +105 -4
- package/dist/index.d.ts +105 -4
- package/dist/index.js +323 -83
- package/dist/vercel/index.cjs +10 -4
- package/dist/vercel/index.d.cts +6 -1
- package/dist/vercel/index.d.ts +6 -1
- package/dist/vercel/index.js +11 -5
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -50,6 +50,7 @@ var TelemError = class extends Error {
|
|
|
50
50
|
this.status = options.status;
|
|
51
51
|
this.code = options.code;
|
|
52
52
|
this.details = options.details;
|
|
53
|
+
if (options.retryAfter !== void 0) this.retryAfter = options.retryAfter;
|
|
53
54
|
}
|
|
54
55
|
};
|
|
55
56
|
var TimeoutError = class extends TelemError {
|
|
@@ -60,7 +61,7 @@ var TimeoutError = class extends TelemError {
|
|
|
60
61
|
};
|
|
61
62
|
|
|
62
63
|
// src/version.ts
|
|
63
|
-
var VERSION = "0.
|
|
64
|
+
var VERSION = "0.8.0";
|
|
64
65
|
|
|
65
66
|
// src/config.ts
|
|
66
67
|
var DEFAULT_BASE_URL = "https://router.telem.ai";
|
|
@@ -195,6 +196,11 @@ function asObject(value) {
|
|
|
195
196
|
function asArray(value) {
|
|
196
197
|
return Array.isArray(value) ? value : [];
|
|
197
198
|
}
|
|
199
|
+
var optString = (v) => typeof v === "string" ? v : null;
|
|
200
|
+
var optStrings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null;
|
|
201
|
+
var optInt = (v) => Number.isInteger(v) ? v : null;
|
|
202
|
+
var optBool = (v) => typeof v === "boolean" ? v : null;
|
|
203
|
+
var optObject = (v) => isObject(v) ? v : null;
|
|
198
204
|
function invalidRequest(message) {
|
|
199
205
|
return new TelemError(message, { code: "invalid_request" });
|
|
200
206
|
}
|
|
@@ -245,12 +251,13 @@ function defaultMessage(status) {
|
|
|
245
251
|
return `Unexpected status code ${status}`;
|
|
246
252
|
}
|
|
247
253
|
var BLOCKED_MESSAGE = "The request was blocked by a firewall before it reached Telem; the text may have characters that are not allowed.";
|
|
248
|
-
function statusError(status, body) {
|
|
254
|
+
function statusError(status, body, retryAfter = null) {
|
|
249
255
|
const fallback = status === 403 && !isObject(body) ? BLOCKED_MESSAGE : defaultMessage(status);
|
|
250
256
|
return new TelemError(detailFromBody(body) ?? fallback, {
|
|
251
257
|
status,
|
|
252
258
|
code: codeFromBody(body),
|
|
253
|
-
details: body
|
|
259
|
+
details: body,
|
|
260
|
+
retryAfter: retryAfter !== null && /^\s*\d+\s*$/.test(retryAfter) ? Number(retryAfter) : void 0
|
|
254
261
|
});
|
|
255
262
|
}
|
|
256
263
|
function connectionError(url, cause) {
|
|
@@ -264,6 +271,16 @@ function connectionError(url, cause) {
|
|
|
264
271
|
function isRetryable(status) {
|
|
265
272
|
return status >= 500 || status === 429;
|
|
266
273
|
}
|
|
274
|
+
var NEVER_SENT = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]);
|
|
275
|
+
function neverSent(failure) {
|
|
276
|
+
const codes = (value) => {
|
|
277
|
+
if (typeof value !== "object" || value === null) return [];
|
|
278
|
+
const error = value;
|
|
279
|
+
return Array.isArray(error.errors) ? error.errors.flatMap(codes) : [error.code];
|
|
280
|
+
};
|
|
281
|
+
const found = codes(failure?.cause);
|
|
282
|
+
return found.length > 0 && found.every((code) => typeof code === "string" && NEVER_SENT.has(code));
|
|
283
|
+
}
|
|
267
284
|
function shouldRetry(mode, status, body) {
|
|
268
285
|
if (mode === "all") return isRetryable(status);
|
|
269
286
|
if (status === 429) return true;
|
|
@@ -282,7 +299,10 @@ function jittered(ms) {
|
|
|
282
299
|
return ms + Math.random() * Math.max(1e3, ms / 2);
|
|
283
300
|
}
|
|
284
301
|
function idempotentDelay(retryAfter, attempt) {
|
|
285
|
-
|
|
302
|
+
return idempotentWait(retryAfter !== null && /^\s*\d+\s*$/.test(retryAfter) ? Number(retryAfter) : null, attempt);
|
|
303
|
+
}
|
|
304
|
+
function idempotentWait(seconds, attempt) {
|
|
305
|
+
if (seconds !== null) return jittered(seconds * 1e3);
|
|
286
306
|
return Math.min(jittered(BASE_DELAY_MS * 2 ** attempt), MAX_IDEMPOTENT_BACKOFF_MS);
|
|
287
307
|
}
|
|
288
308
|
async function request(config, method, path, body, abort, retry = "all", extra = {}) {
|
|
@@ -310,7 +330,7 @@ async function request(config, method, path, body, abort, retry = "all", extra =
|
|
|
310
330
|
});
|
|
311
331
|
abortion?.catch(() => {
|
|
312
332
|
});
|
|
313
|
-
const
|
|
333
|
+
const pause2 = (ms) => abortion ? Promise.race([config.sleep(ms), abortion]) : config.sleep(ms);
|
|
314
334
|
try {
|
|
315
335
|
return await attempts();
|
|
316
336
|
} finally {
|
|
@@ -354,26 +374,28 @@ async function request(config, method, path, body, abort, retry = "all", extra =
|
|
|
354
374
|
const wait = delay(null, attempt);
|
|
355
375
|
if (signal?.aborted) {
|
|
356
376
|
if (retry === "idempotent" && attempt < maxRetries && fits(wait)) {
|
|
357
|
-
await
|
|
377
|
+
await pause2(wait);
|
|
358
378
|
continue;
|
|
359
379
|
}
|
|
360
380
|
throw new TimeoutError(`request to ${url} timed out after ${config.timeoutMs}ms`, cause);
|
|
361
381
|
}
|
|
362
|
-
if (retry === "rate_limit" ||
|
|
363
|
-
|
|
382
|
+
if (retry === "rate_limit" || retry === "metered" && !neverSent(cause)) throw connectionError(url, cause);
|
|
383
|
+
if (attempt >= maxRetries || !fits(wait)) throw connectionError(url, cause);
|
|
384
|
+
await pause2(wait);
|
|
364
385
|
continue;
|
|
365
386
|
} finally {
|
|
366
387
|
signal?.removeEventListener("abort", onAbort2);
|
|
367
388
|
}
|
|
368
389
|
if (received.status >= 200 && received.status < 300) return received.body;
|
|
369
|
-
|
|
390
|
+
const lostReply = retry === "idempotent" && extra.lostReplyStatuses?.includes(received.status) === true;
|
|
391
|
+
if ((lostReply || shouldRetry(retry, received.status, received.body)) && attempt < maxRetries) {
|
|
370
392
|
const wait = delay(received.retryAfter, attempt);
|
|
371
393
|
if (fits(wait)) {
|
|
372
|
-
await
|
|
394
|
+
await pause2(wait);
|
|
373
395
|
continue;
|
|
374
396
|
}
|
|
375
397
|
}
|
|
376
|
-
throw statusError(received.status, received.body);
|
|
398
|
+
throw statusError(received.status, received.body, received.retryAfter);
|
|
377
399
|
}
|
|
378
400
|
}
|
|
379
401
|
}
|
|
@@ -562,23 +584,24 @@ function fetchBody(url, options, defaults) {
|
|
|
562
584
|
function fetchResult(run) {
|
|
563
585
|
const row = asObject(asArray(asObject(run.output_payload).fetched_results)[0]);
|
|
564
586
|
return {
|
|
565
|
-
url: row.url || run.query || "",
|
|
566
|
-
canonicalUrl: row.canonical_url
|
|
567
|
-
title: row.title || "",
|
|
568
|
-
status: row.status || run.status || "",
|
|
569
|
-
content: row.content
|
|
570
|
-
contentTruncated: row.content_truncated
|
|
571
|
-
contentFormat: row.content_format
|
|
572
|
-
contentSha256: row.content_sha256
|
|
573
|
-
contentType: row.content_type
|
|
574
|
-
contentRef: row.content_ref
|
|
575
|
-
provider: row.provider || "",
|
|
576
|
-
httpStatus: row.http_status
|
|
577
|
-
fetchedAt: row.fetched_at
|
|
578
|
-
// Key presence, not truthiness: a row that really reported 0 ms keeps its 0.
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
587
|
+
url: optString(row.url) || optString(run.query) || "",
|
|
588
|
+
canonicalUrl: optString(row.canonical_url),
|
|
589
|
+
title: optString(row.title) || "",
|
|
590
|
+
status: optString(row.status) || optString(run.status) || "",
|
|
591
|
+
content: optString(row.content),
|
|
592
|
+
contentTruncated: optBool(row.content_truncated),
|
|
593
|
+
contentFormat: optString(row.content_format),
|
|
594
|
+
contentSha256: optString(row.content_sha256),
|
|
595
|
+
contentType: optString(row.content_type),
|
|
596
|
+
contentRef: optObject(row.content_ref),
|
|
597
|
+
provider: optString(row.provider) || "",
|
|
598
|
+
httpStatus: optInt(row.http_status),
|
|
599
|
+
fetchedAt: optString(row.fetched_at),
|
|
600
|
+
// Key presence, not truthiness: a row that really reported 0 ms keeps its 0. A
|
|
601
|
+
// malformed row value falls back to the run's, as a missing one does.
|
|
602
|
+
latencyMs: optInt(row.latency_ms) ?? optInt(run.latency_ms),
|
|
603
|
+
providerMetadata: optObject(row.provider_metadata),
|
|
604
|
+
error: optObject(row.error) || optObject(run.error) || null,
|
|
582
605
|
batchIndex: run.batch_index ?? 0,
|
|
583
606
|
raw: row
|
|
584
607
|
};
|
|
@@ -596,7 +619,7 @@ function buildFetchResponse(interaction) {
|
|
|
596
619
|
}
|
|
597
620
|
async function fetchUrls(config, url, options) {
|
|
598
621
|
const body = fetchBody(url, options, config.fetchDefaults);
|
|
599
|
-
return buildFetchResponse(await request(config, "POST", "/v1/fetch", body, options.signal));
|
|
622
|
+
return buildFetchResponse(await request(config, "POST", "/v1/fetch", body, options.signal, "metered"));
|
|
600
623
|
}
|
|
601
624
|
|
|
602
625
|
// src/methods/search.ts
|
|
@@ -698,18 +721,21 @@ function assertV2(data) {
|
|
|
698
721
|
}
|
|
699
722
|
function searchResults(envelope, provider) {
|
|
700
723
|
return asArray(envelope.results).filter(isObject).map((row) => ({
|
|
701
|
-
url: row.url || "",
|
|
702
|
-
title: row.title || "",
|
|
703
|
-
summary: row.summary
|
|
704
|
-
excerpt: row.excerpt
|
|
705
|
-
fullContent: row.full_content
|
|
706
|
-
publishDate: row.publish_date
|
|
707
|
-
rank: row.rank
|
|
708
|
-
thumbnail: row.thumbnail
|
|
709
|
-
favicon: row.favicon
|
|
710
|
-
source: row.source
|
|
711
|
-
enrichments: row.enrichments
|
|
712
|
-
fetchMeta: row.fetch_meta
|
|
724
|
+
url: optString(row.url) || "",
|
|
725
|
+
title: optString(row.title) || "",
|
|
726
|
+
summary: optString(row.summary),
|
|
727
|
+
excerpt: optStrings(row.excerpt),
|
|
728
|
+
fullContent: optObject(row.full_content),
|
|
729
|
+
publishDate: optString(row.publish_date),
|
|
730
|
+
rank: optInt(row.rank),
|
|
731
|
+
thumbnail: optString(row.thumbnail),
|
|
732
|
+
favicon: optString(row.favicon),
|
|
733
|
+
source: optObject(row.source),
|
|
734
|
+
enrichments: optObject(row.enrichments),
|
|
735
|
+
fetchMeta: optObject(row.fetch_meta),
|
|
736
|
+
imageUrl: optString(row.image_url),
|
|
737
|
+
imageWidth: optInt(row.image_width),
|
|
738
|
+
imageHeight: optInt(row.image_height),
|
|
713
739
|
provider,
|
|
714
740
|
raw: row
|
|
715
741
|
}));
|
|
@@ -756,7 +782,7 @@ function buildSearchResponse(interaction) {
|
|
|
756
782
|
}
|
|
757
783
|
async function search(config, query, options) {
|
|
758
784
|
const body = searchBody(config, query, options);
|
|
759
|
-
const data = await request(config, "POST", "/v1/interactions", body, options.signal);
|
|
785
|
+
const data = await request(config, "POST", "/v1/interactions", body, options.signal, "metered");
|
|
760
786
|
assertV2(data);
|
|
761
787
|
return buildSearchResponse(data);
|
|
762
788
|
}
|
|
@@ -779,7 +805,7 @@ function agentStateFrom(data) {
|
|
|
779
805
|
needsAttention: data.needs_attention === true,
|
|
780
806
|
planVersion: typeof data.plan_version === "number" ? data.plan_version : null,
|
|
781
807
|
nextRunAt: typeof data.next_run_at === "string" ? data.next_run_at : null,
|
|
782
|
-
watermark:
|
|
808
|
+
watermark: finite(data.watermark),
|
|
783
809
|
// No compile job yet is null, not an object of empty strings.
|
|
784
810
|
compile: isObject(data.compile) ? {
|
|
785
811
|
jobId: String(data.compile.job_id ?? ""),
|
|
@@ -821,10 +847,17 @@ function agentDocumentFrom(body) {
|
|
|
821
847
|
if (typeof data.spend_usd === "number") document.spendUsd = data.spend_usd;
|
|
822
848
|
return document;
|
|
823
849
|
}
|
|
850
|
+
function position(value, field) {
|
|
851
|
+
const n = typeof value === "number" ? value : typeof value === "string" && /^\d+$/.test(value) ? Number(value) : NaN;
|
|
852
|
+
if (Number.isSafeInteger(n) && n >= 0) return n;
|
|
853
|
+
const sent = value === void 0 ? "missing" : JSON.stringify(value) ?? String(value);
|
|
854
|
+
const shown = sent.length > 40 ? `${sent.slice(0, 40)}\u2026` : sent;
|
|
855
|
+
throw new TelemError(`${field} is not a stream position: ${shown}`, { code: "invalid_response", details: value });
|
|
856
|
+
}
|
|
824
857
|
function changeRecordFrom(entry) {
|
|
825
858
|
const subject = asObject(entry.subject);
|
|
826
859
|
return {
|
|
827
|
-
seq:
|
|
860
|
+
seq: position(entry.seq, "change seq"),
|
|
828
861
|
type: String(entry.type ?? ""),
|
|
829
862
|
kind: String(entry.kind ?? ""),
|
|
830
863
|
monitorId: String(entry.monitor_id ?? ""),
|
|
@@ -844,8 +877,8 @@ function changesPageFrom(body) {
|
|
|
844
877
|
const data = asObject(body);
|
|
845
878
|
return {
|
|
846
879
|
changes: asArray(data.changes).filter(isObject).map(changeRecordFrom),
|
|
847
|
-
nextCursor:
|
|
848
|
-
watermark:
|
|
880
|
+
nextCursor: position(data.next_cursor, "changes page next_cursor"),
|
|
881
|
+
watermark: position(data.watermark, "changes page watermark")
|
|
849
882
|
};
|
|
850
883
|
}
|
|
851
884
|
function monitorsChangesPageFrom(body) {
|
|
@@ -953,6 +986,45 @@ function dataMapFrom(body) {
|
|
|
953
986
|
raw: data
|
|
954
987
|
};
|
|
955
988
|
}
|
|
989
|
+
function finite(value) {
|
|
990
|
+
const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
|
|
991
|
+
return Number.isFinite(n) ? n : 0;
|
|
992
|
+
}
|
|
993
|
+
function companyFrom(entry) {
|
|
994
|
+
return {
|
|
995
|
+
companyId: String(entry.company_id ?? ""),
|
|
996
|
+
name: String(entry.name ?? ""),
|
|
997
|
+
domain: String(entry.domain ?? ""),
|
|
998
|
+
priority: entry.priority === true,
|
|
999
|
+
aliases: asArray(entry.aliases).map(String),
|
|
1000
|
+
ticker: String(entry.ticker ?? ""),
|
|
1001
|
+
xHandle: String(entry.x_handle ?? ""),
|
|
1002
|
+
newsroomUrl: String(entry.newsroom_url ?? ""),
|
|
1003
|
+
teamPage: String(entry.team_page ?? ""),
|
|
1004
|
+
tier: String(entry.tier ?? ""),
|
|
1005
|
+
rank: finite(entry.rank),
|
|
1006
|
+
raw: entry
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
function companyListFrom(body) {
|
|
1010
|
+
const data = asObject(body);
|
|
1011
|
+
return {
|
|
1012
|
+
total: finite(data.total),
|
|
1013
|
+
priorityCount: finite(data.priority_count),
|
|
1014
|
+
offset: finite(data.offset),
|
|
1015
|
+
limit: finite(data.limit),
|
|
1016
|
+
nextOffset: typeof data.next_offset === "number" ? data.next_offset : null,
|
|
1017
|
+
companies: asArray(data.companies).filter(isObject).map(companyFrom),
|
|
1018
|
+
raw: data
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
function companiesQuery(options) {
|
|
1022
|
+
const params = new URLSearchParams();
|
|
1023
|
+
if (options.offset !== void 0) params.set("offset", String(options.offset));
|
|
1024
|
+
if (options.limit !== void 0) params.set("limit", String(options.limit));
|
|
1025
|
+
const query = params.toString();
|
|
1026
|
+
return query ? `?${query}` : "";
|
|
1027
|
+
}
|
|
956
1028
|
function listQuery(options) {
|
|
957
1029
|
const params = new URLSearchParams();
|
|
958
1030
|
if (options.limit !== void 0) params.set("limit", String(options.limit));
|
|
@@ -991,6 +1063,140 @@ function acrossQuery(scope, options) {
|
|
|
991
1063
|
if (options.cursor !== void 0) params.set("cursor", options.cursor);
|
|
992
1064
|
return readQuery(params, options);
|
|
993
1065
|
}
|
|
1066
|
+
function createBody(config, query, options) {
|
|
1067
|
+
const given = options ?? {};
|
|
1068
|
+
const agent = given.agent == null ? true : Boolean(given.agent);
|
|
1069
|
+
if (agent && !given.ttl) throw invalidRequest(given.inputs == null ? NEEDS_TTL : NEEDS_TTL_INPUTS);
|
|
1070
|
+
const key = given.idempotencyKey ?? globalThis.crypto.randomUUID();
|
|
1071
|
+
if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key)) {
|
|
1072
|
+
throw invalidRequest("idempotencyKey must be 1 to 255 visible ASCII characters");
|
|
1073
|
+
}
|
|
1074
|
+
const monitorOptions = {};
|
|
1075
|
+
if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
|
|
1076
|
+
if (given.includeDomains !== void 0) {
|
|
1077
|
+
monitorOptions.include_domains = given.includeDomains;
|
|
1078
|
+
}
|
|
1079
|
+
if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
|
|
1080
|
+
const body = { query, options: monitorOptions };
|
|
1081
|
+
if (given.metadata !== void 0) body.metadata = given.metadata;
|
|
1082
|
+
if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
|
|
1083
|
+
if (given.ttl !== void 0) body.ttl = given.ttl;
|
|
1084
|
+
if (given.inputs != null) {
|
|
1085
|
+
body.inputs = given.inputs;
|
|
1086
|
+
const vertical = config.defaults.vertical;
|
|
1087
|
+
if (vertical !== void 0 && !("vertical" in given.inputs)) {
|
|
1088
|
+
body.inputs = { ...given.inputs, vertical };
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
body.agent = agent;
|
|
1092
|
+
if (given.preset != null) body.preset = given.preset;
|
|
1093
|
+
if (given.tags != null) body.tags = given.tags;
|
|
1094
|
+
return { body, key };
|
|
1095
|
+
}
|
|
1096
|
+
var MAY_EXIST = "The monitor may exist: list monitors before you create it again.";
|
|
1097
|
+
var MAY_EXIST_MANY = "The monitors may exist: list monitors before you create them again.";
|
|
1098
|
+
function mayExist(note) {
|
|
1099
|
+
return (error) => {
|
|
1100
|
+
if (error instanceof TimeoutError) throw new TimeoutError(`${error.message}. ${note}`, error.cause);
|
|
1101
|
+
throw error;
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
var BATCH_SIZE = 10;
|
|
1105
|
+
var GATEWAY_TIMEOUTS = [502, 504];
|
|
1106
|
+
var ITEM_FIELDS = /* @__PURE__ */ new Set([
|
|
1107
|
+
"query",
|
|
1108
|
+
"frequency",
|
|
1109
|
+
"search",
|
|
1110
|
+
"includeDomains",
|
|
1111
|
+
"metadata",
|
|
1112
|
+
"webhookUrl",
|
|
1113
|
+
"tags",
|
|
1114
|
+
"idempotencyKey",
|
|
1115
|
+
"ttl",
|
|
1116
|
+
"agent",
|
|
1117
|
+
"inputs",
|
|
1118
|
+
"preset"
|
|
1119
|
+
]);
|
|
1120
|
+
function invalidBatch(message) {
|
|
1121
|
+
return new TelemError(message, { code: "invalid_response" });
|
|
1122
|
+
}
|
|
1123
|
+
function batchAnswer(data, sent, keys) {
|
|
1124
|
+
const answer = /* @__PURE__ */ new Map();
|
|
1125
|
+
const results = isObject(data) ? data.results : void 0;
|
|
1126
|
+
const count = `the batch answer does not have one result for each of the ${sent.length} monitors sent`;
|
|
1127
|
+
if (!Array.isArray(results)) return { answer, problem: invalidBatch(count) };
|
|
1128
|
+
let problem = results.length !== sent.length ? invalidBatch(count) : null;
|
|
1129
|
+
for (const entry of results) {
|
|
1130
|
+
try {
|
|
1131
|
+
const [position2, result] = batchEntry(entry, sent, keys, answer);
|
|
1132
|
+
answer.set(position2, result);
|
|
1133
|
+
} catch (error) {
|
|
1134
|
+
if (!(error instanceof TelemError)) throw error;
|
|
1135
|
+
problem ??= error;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
return { answer, problem };
|
|
1139
|
+
}
|
|
1140
|
+
function batchEntry(entry, sent, keys, answer) {
|
|
1141
|
+
const index = isObject(entry) ? entry.index : void 0;
|
|
1142
|
+
if (!isObject(entry) || !Number.isInteger(index) || index < 0 || index >= sent.length) {
|
|
1143
|
+
throw invalidBatch("a batch result has no valid index");
|
|
1144
|
+
}
|
|
1145
|
+
if (!Number.isInteger(entry.status)) throw invalidBatch(`batch result ${index} has no status`);
|
|
1146
|
+
const position2 = sent[index];
|
|
1147
|
+
if (answer.has(position2)) throw invalidBatch(`two batch results have index ${index}`);
|
|
1148
|
+
return [
|
|
1149
|
+
position2,
|
|
1150
|
+
{
|
|
1151
|
+
index: position2,
|
|
1152
|
+
status: entry.status,
|
|
1153
|
+
monitor: isObject(entry.monitor) ? monitorFrom(entry.monitor) : null,
|
|
1154
|
+
replayed: entry.replayed === true,
|
|
1155
|
+
error: optObject(entry.error),
|
|
1156
|
+
retryAfter: optInt(entry.retry_after),
|
|
1157
|
+
idempotencyKey: keys[position2],
|
|
1158
|
+
raw: entry
|
|
1159
|
+
}
|
|
1160
|
+
];
|
|
1161
|
+
}
|
|
1162
|
+
function comesBack(result) {
|
|
1163
|
+
if (result === void 0 || result.status === 429) return true;
|
|
1164
|
+
return result.status === 409 && isObject(result.error) && result.error.code === "idempotency_in_progress";
|
|
1165
|
+
}
|
|
1166
|
+
function failed(error, results, keys) {
|
|
1167
|
+
const message = withNote(error.message);
|
|
1168
|
+
const { status, code, details, retryAfter } = error;
|
|
1169
|
+
const thrown = error instanceof TimeoutError ? new TimeoutError(message, error.cause) : new TelemError(message, { status, code, details, retryAfter, cause: error });
|
|
1170
|
+
return attach(thrown, results, keys);
|
|
1171
|
+
}
|
|
1172
|
+
function aborted(reason, results, keys) {
|
|
1173
|
+
const thrown = new TelemError(withNote("monitors.createMany() was aborted"), { code: "aborted", cause: reason });
|
|
1174
|
+
return attach(thrown, results, keys);
|
|
1175
|
+
}
|
|
1176
|
+
function withNote(message) {
|
|
1177
|
+
return `${message}${message.endsWith(".") ? "" : "."} ${MAY_EXIST_MANY}`;
|
|
1178
|
+
}
|
|
1179
|
+
function attach(thrown, results, keys) {
|
|
1180
|
+
const answered = results.filter((result) => result !== void 0);
|
|
1181
|
+
Object.defineProperty(thrown, "results", { value: answered, writable: true, configurable: true });
|
|
1182
|
+
Object.defineProperty(thrown, "idempotencyKeys", { value: [...keys], writable: true, configurable: true });
|
|
1183
|
+
return thrown;
|
|
1184
|
+
}
|
|
1185
|
+
async function pause(config, ms, signal) {
|
|
1186
|
+
if (!signal) return config.sleep(ms);
|
|
1187
|
+
if (signal.aborted) throw signal.reason ?? new Error("aborted");
|
|
1188
|
+
let onAbort = () => {
|
|
1189
|
+
};
|
|
1190
|
+
const aborted2 = new Promise((_, reject) => {
|
|
1191
|
+
onAbort = () => reject(signal.reason ?? new Error("aborted"));
|
|
1192
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1193
|
+
});
|
|
1194
|
+
try {
|
|
1195
|
+
await Promise.race([config.sleep(ms), aborted2]);
|
|
1196
|
+
} finally {
|
|
1197
|
+
signal.removeEventListener("abort", onAbort);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
994
1200
|
function createMonitors(config) {
|
|
995
1201
|
const path = (monitorId, suffix = "") => {
|
|
996
1202
|
if (!monitorId || /^\.+$/.test(monitorId)) throw invalidRequest("a monitor id is required");
|
|
@@ -1018,50 +1224,89 @@ function createMonitors(config) {
|
|
|
1018
1224
|
return {
|
|
1019
1225
|
/** Create a monitor. Telem runs `query` on the schedule, and its agent keeps what matches. */
|
|
1020
1226
|
async create(query, options) {
|
|
1021
|
-
const
|
|
1022
|
-
const agent = given.agent == null ? true : Boolean(given.agent);
|
|
1023
|
-
if (agent && !given.ttl) throw invalidRequest(given.inputs == null ? NEEDS_TTL : NEEDS_TTL_INPUTS);
|
|
1024
|
-
const key = given.idempotencyKey ?? globalThis.crypto.randomUUID();
|
|
1025
|
-
if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key)) {
|
|
1026
|
-
throw invalidRequest("idempotencyKey must be 1 to 255 visible ASCII characters");
|
|
1027
|
-
}
|
|
1028
|
-
const monitorOptions = {};
|
|
1029
|
-
if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
|
|
1030
|
-
if (given.includeDomains !== void 0) {
|
|
1031
|
-
monitorOptions.include_domains = given.includeDomains;
|
|
1032
|
-
}
|
|
1033
|
-
if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
|
|
1034
|
-
const body = { query, options: monitorOptions };
|
|
1035
|
-
if (given.metadata !== void 0) body.metadata = given.metadata;
|
|
1036
|
-
if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
|
|
1037
|
-
if (given.ttl !== void 0) body.ttl = given.ttl;
|
|
1038
|
-
if (given.inputs != null) {
|
|
1039
|
-
body.inputs = given.inputs;
|
|
1040
|
-
const vertical = config.defaults.vertical;
|
|
1041
|
-
if (vertical !== void 0 && !("vertical" in given.inputs)) {
|
|
1042
|
-
body.inputs = { ...given.inputs, vertical };
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
body.agent = agent;
|
|
1046
|
-
if (given.preset != null) body.preset = given.preset;
|
|
1047
|
-
if (given.tags != null) body.tags = given.tags;
|
|
1227
|
+
const { body, key } = createBody(config, query, options);
|
|
1048
1228
|
const extra = {
|
|
1049
1229
|
headers: { "Idempotency-Key": key },
|
|
1050
1230
|
maxRetries: config.createMaxRetries,
|
|
1051
1231
|
budgetMs: CREATE_RETRY_BUDGET_MS
|
|
1052
1232
|
};
|
|
1053
|
-
const data = await request(config, "POST", "/v1/monitors", body,
|
|
1054
|
-
(
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1233
|
+
const data = await request(config, "POST", "/v1/monitors", body, options?.signal, "idempotent", extra).catch(
|
|
1234
|
+
mayExist(MAY_EXIST)
|
|
1235
|
+
);
|
|
1236
|
+
return monitorFrom(data);
|
|
1237
|
+
},
|
|
1238
|
+
/** Create many monitors, ten per call, one call after another. */
|
|
1239
|
+
async createMany(items, options = {}) {
|
|
1240
|
+
if (!Array.isArray(items)) throw invalidRequest("createMany takes an array of monitors");
|
|
1241
|
+
const given = /* @__PURE__ */ new Map();
|
|
1242
|
+
const bodies = items.map((item, index) => {
|
|
1243
|
+
try {
|
|
1244
|
+
if (!isObject(item)) throw invalidRequest("a monitor must be an object of create's options");
|
|
1245
|
+
const unknown = Object.keys(item).find((key2) => !ITEM_FIELDS.has(key2));
|
|
1246
|
+
if (unknown !== void 0) throw invalidRequest(`unknown option ${JSON.stringify(unknown)}`);
|
|
1247
|
+
if (item.query == null) throw invalidRequest("query is required");
|
|
1248
|
+
const { body, key } = createBody(config, item.query, item);
|
|
1249
|
+
try {
|
|
1250
|
+
JSON.stringify(body);
|
|
1251
|
+
} catch (cause) {
|
|
1252
|
+
throw invalidRequest(`not JSON: ${cause?.message ?? String(cause)}`);
|
|
1060
1253
|
}
|
|
1254
|
+
return { ...body, idempotency_key: key };
|
|
1255
|
+
} catch (error) {
|
|
1256
|
+
if (error instanceof TelemError) throw invalidRequest(`monitor ${index}: ${error.message}`);
|
|
1061
1257
|
throw error;
|
|
1062
1258
|
}
|
|
1063
|
-
);
|
|
1064
|
-
|
|
1259
|
+
});
|
|
1260
|
+
items.forEach((item, index) => {
|
|
1261
|
+
if (item.idempotencyKey == null) return;
|
|
1262
|
+
const first = given.get(item.idempotencyKey) ?? index;
|
|
1263
|
+
given.set(item.idempotencyKey, first);
|
|
1264
|
+
if (first !== index) throw invalidRequest(`monitors ${first} and ${index} have the same idempotencyKey`);
|
|
1265
|
+
});
|
|
1266
|
+
const keys = bodies.map((body) => body.idempotency_key);
|
|
1267
|
+
const results = Array(bodies.length).fill(void 0);
|
|
1268
|
+
let sent = false;
|
|
1269
|
+
const fail = (error) => {
|
|
1270
|
+
if (!sent) return error;
|
|
1271
|
+
if (!(error instanceof TelemError)) {
|
|
1272
|
+
if (!options.signal?.aborted) return error;
|
|
1273
|
+
return aborted(error, results, keys);
|
|
1274
|
+
}
|
|
1275
|
+
return failed(error, results, keys);
|
|
1276
|
+
};
|
|
1277
|
+
for (let offset = 0; offset < bodies.length; offset += BATCH_SIZE) {
|
|
1278
|
+
let pending = keys.slice(offset, offset + BATCH_SIZE).map((_, i) => offset + i);
|
|
1279
|
+
const started = Date.now();
|
|
1280
|
+
for (let attempt = 0; ; attempt++) {
|
|
1281
|
+
const extra = {
|
|
1282
|
+
maxRetries: config.createMaxRetries,
|
|
1283
|
+
budgetMs: CREATE_RETRY_BUDGET_MS - (Date.now() - started),
|
|
1284
|
+
lostReplyStatuses: GATEWAY_TIMEOUTS
|
|
1285
|
+
};
|
|
1286
|
+
const body = { monitors: pending.map((i) => bodies[i]) };
|
|
1287
|
+
let data;
|
|
1288
|
+
try {
|
|
1289
|
+
sent ||= !options.signal?.aborted;
|
|
1290
|
+
data = await request(config, "POST", "/v1/monitors:batch", body, options.signal, "idempotent", extra);
|
|
1291
|
+
} catch (error) {
|
|
1292
|
+
throw fail(error);
|
|
1293
|
+
}
|
|
1294
|
+
const { answer, problem } = batchAnswer(data, pending, keys);
|
|
1295
|
+
for (const [position2, result] of answer) results[position2] = result;
|
|
1296
|
+
if (problem) throw fail(problem);
|
|
1297
|
+
pending = pending.filter((i) => comesBack(results[i]));
|
|
1298
|
+
if (!pending.length || attempt >= config.createMaxRetries) break;
|
|
1299
|
+
const known = pending.map((i) => results[i].retryAfter).filter((n) => n !== null && n >= 0);
|
|
1300
|
+
const wait = idempotentWait(known.length ? Math.max(...known) : null, attempt);
|
|
1301
|
+
if (Date.now() - started + wait > CREATE_RETRY_BUDGET_MS) break;
|
|
1302
|
+
try {
|
|
1303
|
+
await pause(config, wait, options.signal);
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
throw fail(error);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
return results;
|
|
1065
1310
|
},
|
|
1066
1311
|
/** List your monitors, newest first. `listPage` also gives the next cursor. */
|
|
1067
1312
|
async list(options = {}) {
|
|
@@ -1166,25 +1411,36 @@ function createMonitors(config) {
|
|
|
1166
1411
|
async dataMap(monitorId, options = {}) {
|
|
1167
1412
|
const route = path(monitorId, "/agent/data-map");
|
|
1168
1413
|
return dataMapFrom(await request(config, "GET", route, void 0, options.signal));
|
|
1414
|
+
},
|
|
1415
|
+
/** One page of the monitor's companies, in rank order. */
|
|
1416
|
+
async companies(monitorId, options = {}) {
|
|
1417
|
+
const route = `${path(monitorId, "/agent/companies")}${companiesQuery(options)}`;
|
|
1418
|
+
return companyListFrom(await request(config, "GET", route, void 0, options.signal));
|
|
1169
1419
|
}
|
|
1170
1420
|
};
|
|
1171
1421
|
}
|
|
1172
1422
|
async function verifyWebhook(body, header, secret, toleranceSeconds = 300) {
|
|
1173
|
-
const parts =
|
|
1174
|
-
|
|
1175
|
-
);
|
|
1176
|
-
|
|
1177
|
-
const
|
|
1423
|
+
const parts = header.split(",").map((item) => item.trim()).filter((item) => item.includes("=")).map((item) => [item.slice(0, item.indexOf("=")), item.slice(item.indexOf("=") + 1)]);
|
|
1424
|
+
const timestamps = parts.filter(([name]) => name === "t").map(([, value]) => value);
|
|
1425
|
+
const signatures = parts.filter(([name, value]) => name === "v1" && /^[0-9a-f]{64}$/.test(value)).map(([, value]) => value);
|
|
1426
|
+
if (timestamps.length !== 1 || signatures.length === 0) return false;
|
|
1427
|
+
const t = timestamps[0];
|
|
1178
1428
|
if (!/^\d+$/.test(t) || Math.abs(Date.now() / 1e3 - Number(t)) > toleranceSeconds) return false;
|
|
1179
|
-
if (!/^([0-9a-f]{2})+$/.test(v1)) return false;
|
|
1180
1429
|
const encoder = new TextEncoder();
|
|
1181
1430
|
const raw = typeof body === "string" ? encoder.encode(body) : body;
|
|
1182
1431
|
const signed = new Uint8Array([...encoder.encode(`${t}.`), ...raw]);
|
|
1183
1432
|
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
|
|
1184
|
-
"
|
|
1433
|
+
"sign"
|
|
1185
1434
|
]);
|
|
1186
|
-
const
|
|
1187
|
-
|
|
1435
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, signed));
|
|
1436
|
+
const expected = Array.from(mac, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1437
|
+
return signatures.some((signature) => sameText(signature, expected));
|
|
1438
|
+
}
|
|
1439
|
+
function sameText(a, b) {
|
|
1440
|
+
if (a.length !== b.length) return false;
|
|
1441
|
+
let diff = 0;
|
|
1442
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
1443
|
+
return diff === 0;
|
|
1188
1444
|
}
|
|
1189
1445
|
|
|
1190
1446
|
// src/methods/providers.ts
|
|
@@ -1272,7 +1528,7 @@ var Telem = class {
|
|
|
1272
1528
|
* `agent`, `changes` and `iterateChanges`, the read across monitors `changesAcross` and
|
|
1273
1529
|
* `iterateChangesAcross`, `feedback`, what a monitor created with
|
|
1274
1530
|
* `inputs` collects (`onboarding`, `applyOnboarding`, `expansions`, `confirmExpansion`,
|
|
1275
|
-
* `revertExpansion`, `dataMap`), and the deprecated `poll`. */
|
|
1531
|
+
* `revertExpansion`, `dataMap`, `companies`), and the deprecated `poll`. */
|
|
1276
1532
|
monitors;
|
|
1277
1533
|
#config;
|
|
1278
1534
|
/**
|