@synthient/synthient 1.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/feed.js ADDED
@@ -0,0 +1,313 @@
1
+ import { SynthientError, isObject } from "./errors.js";
2
+ import { limitQuery } from "./options.js";
3
+ import { drain, redirectTarget } from "./transport.js";
4
+ const MAX_EVENT_SIZE = 16 << 20;
5
+ const EXPORT_ID = /^(\d{4})-(\d{2})-(\d{2})(?:\/(\d{1,2}))?$/;
6
+ /**
7
+ * Keeps each `tunnel_id` as the exact decimal digits sent on the wire, since these
8
+ * unsigned 64-bit IDs lose precision as numbers above 2^53.
9
+ */
10
+ export const exactTunnelID = (key, value, context) => key === "tunnel_id" && typeof value === "number" && context ? context.source : value;
11
+ /**
12
+ * Returns the ID of the daily export for the UTC day containing `date`. Daily exports
13
+ * roll up a day's hourly exports once the day ends.
14
+ */
15
+ export function dailyExport(date) {
16
+ return date.toISOString().slice(0, 10);
17
+ }
18
+ /**
19
+ * Returns the ID of the hourly export for the UTC hour containing `date`, with the hour
20
+ * unpadded as in `Export.id`.
21
+ */
22
+ export function hourlyExport(date) {
23
+ return `${dailyExport(date)}/${date.getUTCHours()}`;
24
+ }
25
+ /**
26
+ * A Synthient data feed. Each feed has a real-time stream of events of type `T` and
27
+ * hourly parquet exports that roll up into daily exports. Access feeds through the
28
+ * client, such as `client.proxies`.
29
+ *
30
+ * Export IDs are "latest" for the most recent hourly export, a UTC day as
31
+ * "YYYY-MM-DD", or a UTC hour as "YYYY-MM-DD/H" (a zero-padded hour is also accepted).
32
+ * `Export.id` values and the results of {@link dailyExport} and {@link hourlyExport} can
33
+ * be passed as they are.
34
+ */
35
+ export class Feed {
36
+ #transport;
37
+ #path;
38
+ #reviver;
39
+ #exports;
40
+ /** @internal Feeds are created by the client. */
41
+ constructor(transport, path, reviver) {
42
+ this.#transport = transport;
43
+ this.#path = path;
44
+ this.#reviver = reviver;
45
+ this.#exports = new Exports(transport, path, true);
46
+ }
47
+ /**
48
+ * Streams the feed's real-time events. The connection opens on the first `next()`,
49
+ * which throws any connection error, such as an APIError with status 403 for a
50
+ * missing scope. The server can close a stream at any time, such as during a deploy,
51
+ * which ends the iteration normally; any other failure throws. Breaking out of the
52
+ * loop closes the connection. Events sent between connections are missed, so call
53
+ * `stream` again to reconnect. The client's `timeout` bounds the gap between data,
54
+ * and the server sends a keepalive about every 15 seconds.
55
+ */
56
+ async *stream(options) {
57
+ const signal = options?.signal;
58
+ const body = await this.#transport.stream({ path: `${this.#path}/stream`, accept: "application/x-ndjson", policy: "transient" }, signal);
59
+ yield* ndjson(body, signal, this.#reviver);
60
+ }
61
+ /** Returns one page of the feed's exports, newest first. Use `allExports` to iterate every page. */
62
+ listExports(options) {
63
+ return this.#exports.list(options);
64
+ }
65
+ /**
66
+ * Iterates over the feed's exports, newest first, fetching pages lazily. `options` is
67
+ * copied when `allExports` is called; errors, including invalid parameters, are
68
+ * thrown from the iteration.
69
+ */
70
+ allExports(options) {
71
+ return this.#exports.all(options);
72
+ }
73
+ /** Returns the rows and bytes the feed exported per UTC day, oldest first. */
74
+ exportVolume(options) {
75
+ return this.#exports.volume(options);
76
+ }
77
+ /** Returns the checksum, size, row count, and parquet schema of an export. */
78
+ exportMeta(id, options) {
79
+ return this.#exports.meta(id, options);
80
+ }
81
+ /**
82
+ * Returns a presigned URL for an export's parquet file, for tools that read parquet
83
+ * over HTTPS directly. The URL is valid for 24 hours and grants access without an API
84
+ * key, so treat it as a secret.
85
+ */
86
+ downloadURL(id, options) {
87
+ return this.#exports.downloadURL(id, options);
88
+ }
89
+ /**
90
+ * Downloads an export's parquet file as a byte stream. Read it to the end or cancel it
91
+ * to release the connection. The API key is sent only to the Synthient API, never to
92
+ * the storage host that serves the file, and errors never include the presigned URL.
93
+ * A non-success response from either returns an APIError.
94
+ */
95
+ download(id, options) {
96
+ return this.#exports.download(id, options);
97
+ }
98
+ }
99
+ /**
100
+ * A Synthient dataset, published as one export per UTC day with no stream and no hourly
101
+ * exports. Access datasets through the client, such as `client.geolocation`.
102
+ *
103
+ * Export IDs are "latest" for the newest day or a UTC day as "YYYY-MM-DD". `Export.id`
104
+ * values and the results of {@link dailyExport} can be passed as they are.
105
+ */
106
+ export class Dataset {
107
+ #exports;
108
+ /** @internal Datasets are created by the client. */
109
+ constructor(transport, path) {
110
+ this.#exports = new Exports(transport, path, false);
111
+ }
112
+ /** Returns one page of the dataset's exports, newest first. Use `allExports` to iterate every page. */
113
+ listExports(options) {
114
+ return this.#exports.list(options);
115
+ }
116
+ /**
117
+ * Iterates over the dataset's exports, newest first, fetching pages lazily. `options`
118
+ * is copied when `allExports` is called; errors, including invalid parameters, are
119
+ * thrown from the iteration.
120
+ */
121
+ allExports(options) {
122
+ return this.#exports.all(options);
123
+ }
124
+ /** Returns the rows and bytes the dataset exported per UTC day, oldest first. */
125
+ exportVolume(options) {
126
+ return this.#exports.volume(options);
127
+ }
128
+ /**
129
+ * Returns the checksum, size, row count, and schema of an export's file in the
130
+ * requested format, and lists every file of the day.
131
+ */
132
+ exportMeta(id, options) {
133
+ return this.#exports.meta(id, options);
134
+ }
135
+ /**
136
+ * Returns a presigned URL for an export's file. The URL is valid for 24 hours and
137
+ * grants access without an API key, so treat it as a secret.
138
+ */
139
+ downloadURL(id, options) {
140
+ return this.#exports.downloadURL(id, options);
141
+ }
142
+ /**
143
+ * Downloads an export's file as a byte stream, exactly as served: a "csv" file stays
144
+ * gzip-compressed and a WHOIS archive stays packed. Read it to the end or cancel it to
145
+ * release the connection. The API key is sent only to the Synthient API, never to the
146
+ * storage host that serves the file, and errors never include the presigned URL. A
147
+ * non-success response from either returns an APIError.
148
+ */
149
+ download(id, options) {
150
+ return this.#exports.download(id, options);
151
+ }
152
+ }
153
+ /** The export routes that feeds and datasets share under their path. */
154
+ class Exports {
155
+ #transport;
156
+ #path;
157
+ #hourly;
158
+ constructor(transport, path, hourly) {
159
+ this.#transport = transport;
160
+ this.#path = path;
161
+ this.#hourly = hourly;
162
+ }
163
+ async list(options = {}) {
164
+ const query = limitQuery(options.limit);
165
+ if (options.cursor) {
166
+ query.cursor = options.cursor;
167
+ }
168
+ if (options.day !== undefined) {
169
+ query.day = options.day;
170
+ }
171
+ if (options.variant !== undefined) {
172
+ query.variant = options.variant;
173
+ }
174
+ const page = await this.#transport.json({ path: `${this.#path}/export`, query, policy: "transient" }, options.signal);
175
+ const cursor = page.next_cursor;
176
+ if (!Array.isArray(page.feeds)) {
177
+ throw new SynthientError("export page has no feeds array");
178
+ }
179
+ if (cursor !== undefined && cursor !== null && typeof cursor !== "string") {
180
+ throw new SynthientError("export page has an invalid next_cursor");
181
+ }
182
+ return page;
183
+ }
184
+ async *all({ cursor, ...options } = {}) {
185
+ const seen = new Set([cursor ?? ""]);
186
+ for (;;) {
187
+ const page = await this.list({ ...options, cursor });
188
+ options.signal?.throwIfAborted();
189
+ for (const item of page.feeds) {
190
+ yield item;
191
+ options.signal?.throwIfAborted();
192
+ }
193
+ if (!page.next_cursor) {
194
+ return;
195
+ }
196
+ if (seen.has(page.next_cursor)) {
197
+ throw new SynthientError("export listing returned a repeated cursor");
198
+ }
199
+ seen.add(page.next_cursor);
200
+ cursor = page.next_cursor;
201
+ }
202
+ }
203
+ async volume(options = {}) {
204
+ const query = {};
205
+ if (options.days !== undefined) {
206
+ query.days = String(options.days);
207
+ }
208
+ return this.#transport.json({ path: `${this.#path}/export/daily`, query, policy: "transient" }, options.signal);
209
+ }
210
+ async meta(id, options = {}) {
211
+ const meta = await this.#transport.json({
212
+ path: `${this.#path}/export/${this.#exportPath(id)}/meta`,
213
+ query: fileQuery(options),
214
+ policy: "transient",
215
+ }, options.signal);
216
+ // The WHOIS meta once sent `"fields": null` for its archive's empty schema.
217
+ for (const { schema } of [meta, ...(meta.entities ?? [])]) {
218
+ if (schema) {
219
+ schema.fields = Array.isArray(schema.fields) ? schema.fields : [];
220
+ }
221
+ }
222
+ return meta;
223
+ }
224
+ async downloadURL(id, options = {}) {
225
+ const request = {
226
+ path: `${this.#path}/export/${this.#exportPath(id)}`,
227
+ query: fileQuery(options),
228
+ policy: "transient",
229
+ };
230
+ const [response, attempt] = await this.#transport.send(request, options.signal);
231
+ if (response.status >= 400) {
232
+ throw await this.#transport.error(response, attempt);
233
+ }
234
+ await drain(response, attempt);
235
+ if (response.status < 300 || response.status === 304) {
236
+ throw new SynthientError(`expected a redirect to the export, got status ${response.status}`);
237
+ }
238
+ return redirectTarget(new URL(this.#transport.url(request)), response);
239
+ }
240
+ async download(id, options = {}) {
241
+ const url = await this.downloadURL(id, options);
242
+ return this.#transport.download(url, options.signal);
243
+ }
244
+ /** Converts an export ID to its URL path, with the hour unpadded. */
245
+ #exportPath(id) {
246
+ if (id === "latest") {
247
+ return id;
248
+ }
249
+ const match = EXPORT_ID.exec(id);
250
+ if (match && (this.#hourly || match[4] === undefined)) {
251
+ const [, year, month, day, hour] = match;
252
+ // An invalid day or an hour past 23 rolls the date over, so it no longer matches.
253
+ const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour ?? 0)));
254
+ if (dailyExport(date) === id.slice(0, 10)) {
255
+ return hour === undefined ? dailyExport(date) : hourlyExport(date);
256
+ }
257
+ }
258
+ throw new TypeError("invalid export ID");
259
+ }
260
+ }
261
+ function fileQuery({ variant, format }) {
262
+ const query = {};
263
+ if (variant !== undefined) {
264
+ query.variant = variant;
265
+ }
266
+ if (format !== undefined) {
267
+ query.format = format;
268
+ }
269
+ return query;
270
+ }
271
+ /** Blank lines are keepalives. A final line without a newline is still an event. */
272
+ async function* ndjson(body, signal, reviver) {
273
+ const reader = body.getReader();
274
+ const decoder = new TextDecoder();
275
+ let pending = "";
276
+ try {
277
+ for (;;) {
278
+ const { done, value } = await reader.read();
279
+ signal?.throwIfAborted();
280
+ const lines = decoder.decode(value, { stream: !done }).split("\n");
281
+ lines[0] = pending + (lines[0] ?? "");
282
+ pending = done ? "" : (lines.pop() ?? "");
283
+ if (Buffer.byteLength(pending) > MAX_EVENT_SIZE ||
284
+ lines.some((line) => Buffer.byteLength(line) > MAX_EVENT_SIZE)) {
285
+ throw new SynthientError(`stream event exceeds ${MAX_EVENT_SIZE} bytes`);
286
+ }
287
+ for (const line of lines) {
288
+ const text = line.trim();
289
+ if (text === "") {
290
+ continue;
291
+ }
292
+ let event;
293
+ try {
294
+ event = JSON.parse(text, reviver);
295
+ }
296
+ catch (error) {
297
+ throw new SynthientError("invalid stream event", { cause: error });
298
+ }
299
+ if (!isObject(event)) {
300
+ throw new SynthientError("stream event is not a JSON object");
301
+ }
302
+ yield event;
303
+ signal?.throwIfAborted();
304
+ }
305
+ if (done) {
306
+ return;
307
+ }
308
+ }
309
+ }
310
+ finally {
311
+ reader.cancel().catch(() => undefined);
312
+ }
313
+ }
@@ -0,0 +1,56 @@
1
+ import { type FileDescriptorSet } from "@bufbuild/protobuf/wkt";
2
+ import { SynthientError } from "./errors.ts";
3
+ export declare const DEFAULT_ENDPOINT = "grpc.synthient.com:443";
4
+ export interface FetchSchemaOptions {
5
+ /** Sent as x-api-key metadata, which server reflection requires. Defaults to the SYNTHIENT_API_KEY environment variable. */
6
+ apiKey?: string | undefined;
7
+ /**
8
+ * The server as host:port, a bare host (port 443 is assumed), or a grpc:// or
9
+ * https:// URL. Defaults to {@link DEFAULT_ENDPOINT}.
10
+ */
11
+ endpoint?: string | undefined;
12
+ /** Disables TLS, for local development servers. */
13
+ plaintext?: boolean | undefined;
14
+ /**
15
+ * Fully qualified service or message names to resolve. Empty resolves every listed
16
+ * service except the grpc.reflection services.
17
+ */
18
+ symbols?: Iterable<string> | undefined;
19
+ /** Cancels the fetch, which rejects with the signal's reason. */
20
+ signal?: AbortSignal | undefined;
21
+ /** Milliseconds allowed for the whole fetch. Defaults to 30,000. */
22
+ timeout?: number | undefined;
23
+ }
24
+ export interface Schema {
25
+ /** The normalized address that was queried. */
26
+ endpoint: string;
27
+ /** The service or message names that were resolved. */
28
+ symbols: string[];
29
+ /** The resolved files in dependency order, each file after the files it imports. */
30
+ descriptorSet: FileDescriptorSet;
31
+ }
32
+ /** Fetching the schema failed. {@link explain} describes common causes. */
33
+ export declare class SchemaError extends SynthientError {
34
+ name: string;
35
+ /**
36
+ * The gRPC status code, as in `status` from `@grpc/grpc-js`, or undefined when the
37
+ * failure was not a gRPC status.
38
+ */
39
+ readonly code: number | undefined;
40
+ constructor(message: string, code?: number, options?: ErrorOptions);
41
+ }
42
+ /**
43
+ * Fetches the protobuf files that define `options.symbols`, or every listed service,
44
+ * along with all of their imports.
45
+ */
46
+ export declare function fetchSchema(options?: FetchSchemaOptions): Promise<Schema>;
47
+ /**
48
+ * Converts `raw`, in any form {@link FetchSchemaOptions.endpoint} accepts, to host:port.
49
+ * `host` is the bare host name, without brackets or a port.
50
+ */
51
+ export declare function normalizeEndpoint(raw: string): {
52
+ endpoint: string;
53
+ host: string;
54
+ };
55
+ /** Returns a human-readable explanation of a common fetch error, or "". */
56
+ export declare function explain(error: unknown): string;
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Fetches the protobuf schema of the Synthient gRPC API using gRPC server reflection.
3
+ * It needs the optional peer dependencies `@grpc/grpc-js` and `@bufbuild/protobuf`.
4
+ *
5
+ * @module
6
+ */
7
+ import { create, fromBinary } from "@bufbuild/protobuf";
8
+ import { BinaryReader, BinaryWriter, WireType } from "@bufbuild/protobuf/wire";
9
+ import { FileDescriptorProtoSchema, FileDescriptorSetSchema, } from "@bufbuild/protobuf/wkt";
10
+ import { Client, Metadata, credentials, status } from "@grpc/grpc-js";
11
+ import { SynthientError } from "./errors.js";
12
+ import { checkTimeout, resolveAPIKey } from "./options.js";
13
+ export const DEFAULT_ENDPOINT = "grpc.synthient.com:443";
14
+ const MAX_MESSAGE_SIZE = 32 << 20;
15
+ const METHOD = "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo";
16
+ const FILE_BY_FILENAME = 3;
17
+ const FILE_CONTAINING_SYMBOL = 4;
18
+ const LIST_SERVICES = 7;
19
+ const EXPLANATIONS = {
20
+ [status.UNAUTHENTICATED]: "Missing or invalid API key.",
21
+ [status.PERMISSION_DENIED]: "This API key does not have permission to inspect gRPC schemas.",
22
+ [status.NOT_FOUND]: "No protobuf schema found for the requested symbol. Fetch without symbols to list the available services.",
23
+ [status.UNIMPLEMENTED]: "The gRPC endpoint does not expose server reflection.",
24
+ [status.UNAVAILABLE]: "Could not reach the gRPC endpoint. Check the address, network access, and TLS settings.",
25
+ [status.DEADLINE_EXCEEDED]: "Timed out reading protobuf schemas from gRPC reflection. Use a longer timeout.",
26
+ };
27
+ /** Fetching the schema failed. {@link explain} describes common causes. */
28
+ export class SchemaError extends SynthientError {
29
+ name = "SchemaError";
30
+ /**
31
+ * The gRPC status code, as in `status` from `@grpc/grpc-js`, or undefined when the
32
+ * failure was not a gRPC status.
33
+ */
34
+ code;
35
+ constructor(message, code, options) {
36
+ super(message, options);
37
+ this.code = code;
38
+ }
39
+ }
40
+ /**
41
+ * Fetches the protobuf files that define `options.symbols`, or every listed service,
42
+ * along with all of their imports.
43
+ */
44
+ export async function fetchSchema(options = {}) {
45
+ const { endpoint, host } = normalizeEndpoint(options.endpoint ?? "");
46
+ const timeout = options.timeout ?? 30_000;
47
+ checkTimeout(timeout);
48
+ const signal = options.signal;
49
+ signal?.throwIfAborted();
50
+ const metadata = new Metadata();
51
+ const apiKey = resolveAPIKey(options.apiKey);
52
+ if (apiKey !== "") {
53
+ metadata.set("x-api-key", apiKey);
54
+ }
55
+ const client = new Client(endpoint, options.plaintext ? credentials.createInsecure() : credentials.createSsl(), { "grpc.max_receive_message_length": MAX_MESSAGE_SIZE });
56
+ const call = client.makeBidiStreamRequest(METHOD, (request) => Buffer.from(request), (response) => response, metadata, { deadline: Date.now() + timeout });
57
+ const cancel = () => {
58
+ call.cancel();
59
+ };
60
+ signal?.addEventListener("abort", cancel, { once: true });
61
+ const replies = call[Symbol.asyncIterator]();
62
+ // Sends every request before reading any reply; the server answers in request order.
63
+ const ask = async (field, values) => {
64
+ for (const value of values) {
65
+ const request = new BinaryWriter()
66
+ .tag(1, WireType.LengthDelimited)
67
+ .string(host)
68
+ .tag(field, WireType.LengthDelimited)
69
+ .string(value)
70
+ .finish();
71
+ call.write(request);
72
+ }
73
+ const answers = [];
74
+ while (answers.length < values.length) {
75
+ const next = await replies.next();
76
+ if (next.done) {
77
+ throw new SchemaError("reflection stream ended early");
78
+ }
79
+ const reply = decodeReply(next.value);
80
+ if (reply.error) {
81
+ throw new SchemaError(reply.error.message || "reflection failed", reply.error.code);
82
+ }
83
+ answers.push(reply);
84
+ }
85
+ return answers;
86
+ };
87
+ const files = new Map();
88
+ const addFiles = (reply) => {
89
+ if (!reply.files) {
90
+ throw new SchemaError("reflection response has no file descriptors");
91
+ }
92
+ for (const bytes of reply.files) {
93
+ let file;
94
+ try {
95
+ file = fromBinary(FileDescriptorProtoSchema, bytes);
96
+ }
97
+ catch (error) {
98
+ throw new SchemaError("reflection returned an invalid file descriptor", undefined, {
99
+ cause: error,
100
+ });
101
+ }
102
+ if (!file.name) {
103
+ throw new SchemaError("reflection returned a file descriptor without a name");
104
+ }
105
+ if (!files.has(file.name)) {
106
+ files.set(file.name, file);
107
+ }
108
+ }
109
+ };
110
+ try {
111
+ const requested = Array.from(options.symbols ?? [], (symbol) => symbol.trim());
112
+ let symbols = [...new Set(requested)].filter((symbol) => symbol !== "");
113
+ if (symbols.length === 0) {
114
+ const [reply] = await ask(LIST_SERVICES, [""]);
115
+ if (!reply?.services) {
116
+ throw new SchemaError("reflection response has no service list");
117
+ }
118
+ symbols = reply.services
119
+ .map((name) => name.trim())
120
+ .filter((name) => name !== "" && !name.startsWith("grpc.reflection."))
121
+ .sort();
122
+ }
123
+ if (symbols.length === 0) {
124
+ throw new SchemaError("server lists no services");
125
+ }
126
+ for (const reply of await ask(FILE_CONTAINING_SYMBOL, symbols)) {
127
+ addFiles(reply);
128
+ }
129
+ for (;;) {
130
+ const imports = [...files.values()].flatMap((file) => file.dependency);
131
+ const missing = [...new Set(imports)].filter((name) => !files.has(name)).sort();
132
+ if (missing.length === 0) {
133
+ break;
134
+ }
135
+ for (const reply of await ask(FILE_BY_FILENAME, missing)) {
136
+ addFiles(reply);
137
+ }
138
+ const unresolved = missing.find((name) => !files.has(name));
139
+ if (unresolved !== undefined) {
140
+ throw new SchemaError(`reflection did not return dependency ${unresolved}`);
141
+ }
142
+ }
143
+ return {
144
+ endpoint,
145
+ symbols,
146
+ descriptorSet: create(FileDescriptorSetSchema, { file: dependencyOrder(files) }),
147
+ };
148
+ }
149
+ catch (error) {
150
+ if (signal?.aborted) {
151
+ throw signal.reason;
152
+ }
153
+ if (error instanceof Error &&
154
+ !(error instanceof SchemaError) &&
155
+ "code" in error &&
156
+ typeof error.code === "number") {
157
+ const { details } = error;
158
+ throw new SchemaError(details || "reflection failed", error.code, { cause: error });
159
+ }
160
+ throw error;
161
+ }
162
+ finally {
163
+ signal?.removeEventListener("abort", cancel);
164
+ call.on("error", () => undefined);
165
+ call.cancel();
166
+ client.close();
167
+ }
168
+ }
169
+ /**
170
+ * Converts `raw`, in any form {@link FetchSchemaOptions.endpoint} accepts, to host:port.
171
+ * `host` is the bare host name, without brackets or a port.
172
+ */
173
+ export function normalizeEndpoint(raw) {
174
+ let value = raw.trim() || DEFAULT_ENDPOINT;
175
+ if (value.includes("://")) {
176
+ value = URL.parse(value)?.host ?? "";
177
+ }
178
+ value = value.replace(/\/$/, "");
179
+ if (value === "") {
180
+ throw new TypeError("empty gRPC endpoint");
181
+ }
182
+ let host = value;
183
+ if (value.startsWith("[")) {
184
+ const close = value.indexOf("]");
185
+ host = value.slice(1, close === -1 ? undefined : close);
186
+ if (close !== -1 && value.slice(close + 1).startsWith(":")) {
187
+ return { endpoint: value, host };
188
+ }
189
+ }
190
+ else if (value.split(":").length === 2) {
191
+ return { endpoint: value, host: value.slice(0, value.indexOf(":")) };
192
+ }
193
+ return { endpoint: host.includes(":") ? `[${host}]:443` : `${host}:443`, host };
194
+ }
195
+ /** Returns a human-readable explanation of a common fetch error, or "". */
196
+ export function explain(error) {
197
+ if (!(error instanceof SchemaError) || error.code === undefined) {
198
+ return "";
199
+ }
200
+ return EXPLANATIONS[error.code] ?? "";
201
+ }
202
+ // Decodes a ServerReflectionResponse, keeping only the fields fetchSchema uses.
203
+ function decodeReply(bytes) {
204
+ const reply = {};
205
+ try {
206
+ decode(bytes, (field, reader) => {
207
+ if (field === 4) {
208
+ const files = [];
209
+ decode(reader.bytes(), (inner, value) => {
210
+ if (inner === 1) {
211
+ files.push(value.bytes());
212
+ }
213
+ });
214
+ reply.files = files;
215
+ }
216
+ else if (field === 6) {
217
+ const services = [];
218
+ decode(reader.bytes(), (inner, value) => {
219
+ if (inner === 1) {
220
+ decode(value.bytes(), (name, service) => {
221
+ if (name === 1) {
222
+ services.push(service.string());
223
+ }
224
+ });
225
+ }
226
+ });
227
+ reply.services = services;
228
+ }
229
+ else if (field === 7) {
230
+ const error = { code: status.UNKNOWN, message: "" };
231
+ decode(reader.bytes(), (inner, value) => {
232
+ if (inner === 1) {
233
+ error.code = value.int32();
234
+ }
235
+ else if (inner === 2) {
236
+ error.message = value.string();
237
+ }
238
+ });
239
+ reply.error = error;
240
+ }
241
+ });
242
+ }
243
+ catch (error) {
244
+ throw new SchemaError("invalid reflection response", undefined, { cause: error });
245
+ }
246
+ return reply;
247
+ }
248
+ // Fields the visitor leaves unread are skipped.
249
+ function decode(bytes, visit) {
250
+ const reader = new BinaryReader(bytes);
251
+ while (reader.pos < reader.len) {
252
+ const [field, wireType] = reader.tag();
253
+ const start = reader.pos;
254
+ visit(field, reader);
255
+ if (reader.pos === start) {
256
+ reader.skip(wireType, field);
257
+ }
258
+ }
259
+ }
260
+ function dependencyOrder(files) {
261
+ const ordered = [];
262
+ const visited = new Set();
263
+ const visit = (name) => {
264
+ const file = files.get(name);
265
+ if (!file || visited.has(name)) {
266
+ return;
267
+ }
268
+ visited.add(name);
269
+ for (const dependency of [...file.dependency].sort()) {
270
+ visit(dependency);
271
+ }
272
+ ordered.push(file);
273
+ };
274
+ for (const name of [...files.keys()].sort()) {
275
+ visit(name);
276
+ }
277
+ return ordered;
278
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,23 @@
1
- export * from './client';
2
- export * from './constants';
3
- export * from './exceptions';
4
- export * from './models';
5
- export * from './utils';
1
+ /**
2
+ * The official Node.js client for the Synthient API: IP intelligence, account details,
3
+ * and real-time and bulk data feeds.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { Synthient } from "@synthient/synthient";
8
+ *
9
+ * const client = new Synthient(); // reads SYNTHIENT_API_KEY
10
+ * const info = await client.lookupIP("8.8.8.8");
11
+ * console.log(info.intelligence?.risk_score);
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+ export { DEFAULT_BASE_URL, Synthient, type ClientOptions, type LookupDomainOptions, } from "./client.ts";
17
+ export { APIConnectionError, APIError, APITimeoutError, SynthientError, type APIErrorInit, } from "./errors.ts";
18
+ export type * from "./events.ts";
19
+ export { Dataset, Feed, dailyExport, hourlyExport, type DatasetExportOptions, type ExportOptions, type ExportVolumeOptions, type ListDatasetExportsOptions, type ListExportsOptions, } from "./feed.ts";
20
+ export type { Fetch, RequestOptions, ResponseMetadata } from "./transport.ts";
21
+ export { toDate } from "./types.ts";
22
+ export type * from "./types.ts";
23
+ export { VERSION } from "./version.ts";