@constellationspace/client 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Client: () => Client,
24
+ ConstellationError: () => ConstellationError,
25
+ DEFAULT_API_URL: () => DEFAULT_API_URL,
26
+ PAGE_RECORDS: () => PAGE_RECORDS,
27
+ SCHEMA: () => SCHEMA,
28
+ actionState: () => actionState,
29
+ plain: () => plain,
30
+ unpack: () => unpack,
31
+ whole: () => whole
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+
35
+ // src/results.ts
36
+ var SCHEMA = "constellation.item/v2";
37
+ var PAGE_RECORDS = 400;
38
+ function actionState(item) {
39
+ const status = item.action_status ?? null;
40
+ if (status !== null && status !== "approved") return status === "rejected" ? "rejected" : "pending";
41
+ const action = item.action;
42
+ if (!action || Object.keys(action).length === 0) return status === null ? null : "pending";
43
+ return status === "approved" ? "approved" : "advice";
44
+ }
45
+ function plain(value) {
46
+ if ("kvlistValue" in value)
47
+ return Object.fromEntries((value.kvlistValue.values ?? []).map((kv) => [kv.key, plain(kv.value)]));
48
+ if ("arrayValue" in value) return (value.arrayValue.values ?? []).map(plain);
49
+ if ("intValue" in value) return Number(value.intValue);
50
+ for (const key of ["doubleValue", "boolValue", "stringValue"]) if (key in value) return value[key];
51
+ return null;
52
+ }
53
+ var attributes = (kvs = []) => Object.fromEntries(kvs.map((kv) => [kv.key, plain(kv.value)]));
54
+ function unpack(entry, consumer, log) {
55
+ const parts = [];
56
+ for (const logs of entry.otlp.resourceLogs) {
57
+ const resource = attributes(logs.resource?.attributes);
58
+ if (consumer && resource["constellation.connection"] !== consumer) continue;
59
+ const records = (logs.scopeLogs ?? []).flatMap((s) => s.logRecords ?? []);
60
+ const newer = new Set(records.map((r) => attributes(r.attributes)["constellation.schema"]));
61
+ newer.delete(SCHEMA);
62
+ if (newer.size) {
63
+ log(`skipped run ${resource["constellation.run_id"]}: its items are ${[...newer].join(", ")} and this client reads ${SCHEMA}`);
64
+ continue;
65
+ }
66
+ const output = JSON.parse(resource["constellation.output"] || "{}");
67
+ parts.push({
68
+ resource,
69
+ items: records.map((r) => plain(r.body)),
70
+ settings: output?.mapping?.settings ?? {},
71
+ run: {
72
+ workflow: resource["constellation.workflow"],
73
+ workflow_version: resource["constellation.workflow_version"],
74
+ run_id: resource["constellation.run_id"],
75
+ window_from: resource["constellation.window.from"],
76
+ window_to: resource["constellation.window.to"]
77
+ }
78
+ });
79
+ }
80
+ return parts;
81
+ }
82
+ async function whole(entry, fetchPage) {
83
+ const resourceLogs = entry.otlp.resourceLogs.map((l) => ({
84
+ ...l,
85
+ scopeLogs: (l.scopeLogs ?? []).map((s) => ({ ...s, logRecords: [...s.logRecords ?? []] }))
86
+ }));
87
+ const byResource = new Map(resourceLogs.map((l) => [JSON.stringify(l.resource), l]));
88
+ let next = entry.next_page;
89
+ while (next) {
90
+ const more = await fetchPage(entry.cursor, next);
91
+ for (const logs of more.otlp.resourceLogs) {
92
+ const key = JSON.stringify(logs.resource);
93
+ const known = byResource.get(key)?.scopeLogs?.[0];
94
+ if (known) known.logRecords.push(...logs.scopeLogs?.[0]?.logRecords ?? []);
95
+ else {
96
+ resourceLogs.push(logs);
97
+ byResource.set(key, logs);
98
+ }
99
+ }
100
+ next = more.next_page;
101
+ }
102
+ return { cursor: entry.cursor, otlp: { ...entry.otlp, resourceLogs } };
103
+ }
104
+
105
+ // src/client.ts
106
+ var DEFAULT_API_URL = "https://api.constellation.space";
107
+ function site(apiUrl) {
108
+ let host = "";
109
+ try {
110
+ host = new URL(apiUrl ?? "").hostname;
111
+ } catch {
112
+ }
113
+ if (host.startsWith("api.")) return `https://platform.${host.slice(4)}`;
114
+ const at = host.indexOf(".api.");
115
+ if (at > 0) return `https://${host.slice(0, at)}-platform.${host.slice(at + 5)}`;
116
+ return "https://platform.constellation.space";
117
+ }
118
+ function loopback(url) {
119
+ let host = "";
120
+ try {
121
+ host = new URL(url).hostname.replace(/^\[|\]$/g, "");
122
+ } catch {
123
+ }
124
+ return host === "localhost" || host === "::1" || /^127\.\d+\.\d+\.\d+$/.test(host);
125
+ }
126
+ function keySafe(url) {
127
+ let scheme = "";
128
+ try {
129
+ scheme = new URL(url).protocol;
130
+ } catch {
131
+ }
132
+ return scheme === "https:" || scheme === "http:" && loopback(url);
133
+ }
134
+ var env = (name) => globalThis.process?.env[name];
135
+ var MAX_RETRY_AFTER_S = 60;
136
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
137
+ var ConstellationError = class extends Error {
138
+ constructor(status, body, apiUrl) {
139
+ const b = body;
140
+ const inner = b && typeof b === "object" ? typeof b.detail === "object" && b.detail ? b.detail : b : {};
141
+ super(describe(status, inner, b, site(apiUrl)));
142
+ this.status = status;
143
+ this.body = body;
144
+ this.name = "ConstellationError";
145
+ this.detail = inner;
146
+ this.code = typeof inner.error === "string" ? inner.error : void 0;
147
+ }
148
+ status;
149
+ body;
150
+ /** The API's machine error, e.g. plan_required, insufficient_scope, unknown_cursor. */
151
+ code;
152
+ /** The error object: the body's `detail` when it is an object, else the body. */
153
+ detail;
154
+ /** 401 or 403: neither clears by asking again, so a bridge stops on one. */
155
+ get refused() {
156
+ return this.status === 401 || this.status === 403;
157
+ }
158
+ };
159
+ function describe(status, d, body, home) {
160
+ const fix = `make a key with predictions:read on ${home}/keys and set it as CONSTELLATION_API_KEY`;
161
+ if (status === 401) return `Constellation does not accept the API key (HTTP 401; wrong, revoked or expired): ${fix}`;
162
+ if (status === 403) {
163
+ if (d.error === "plan_required")
164
+ return `this account's plan does not include ${d.feature} (HTTP 403 plan_required); the ${d.plan} plan does. Upgrade on ${home}/billing`;
165
+ if (d.error === "insufficient_scope") return `the API key lacks ${d.required} (HTTP 403): ${fix}`;
166
+ if (d.error === "live_key_required") return `the API key is a test key; this takes a live one (HTTP 403): ${fix}`;
167
+ return `Constellation refused the API key (HTTP 403 ${d.error ?? "forbidden"}): ${fix}`;
168
+ }
169
+ return `Constellation answered ${status}: ${JSON.stringify(body)?.slice(0, 300)}`;
170
+ }
171
+ var Client = class {
172
+ baseUrl;
173
+ apiKey;
174
+ retries;
175
+ retryDelayMs;
176
+ timeoutMs;
177
+ fetchFn;
178
+ log;
179
+ constructor(options = {}) {
180
+ this.apiKey = (options.apiKey ?? env("CONSTELLATION_API_KEY") ?? "").trim();
181
+ this.baseUrl = (options.baseUrl ?? env("CONSTELLATION_API_URL") ?? DEFAULT_API_URL).replace(/\/+$/, "");
182
+ this.retries = options.retries ?? 4;
183
+ this.retryDelayMs = options.retryDelayMs ?? 500;
184
+ this.timeoutMs = options.timeoutMs ?? 6e4;
185
+ this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
186
+ this.log = options.log ?? ((m) => console.warn(`constellation: ${m}`));
187
+ }
188
+ /** Whether it has an API key to send. */
189
+ get hasKey() {
190
+ return this.apiKey !== "";
191
+ }
192
+ /** Any API call: `query` values left undefined are dropped. Returns the parsed JSON body, or undefined. */
193
+ async request(method, path, options = {}) {
194
+ const query = Object.entries(options.query ?? {}).filter(([, v]) => v !== void 0);
195
+ const url = `${this.baseUrl}${path}${query.length ? `?${new URLSearchParams(query.map(([k, v]) => [k, String(v)]))}` : ""}`;
196
+ if (this.apiKey && !keySafe(this.baseUrl))
197
+ throw new Error(`not sending the API key to ${this.baseUrl}: it is not https (plain http only to localhost)`);
198
+ const init = {
199
+ method,
200
+ headers: { ...this.apiKey && { "x-api-key": this.apiKey }, "content-type": "application/json", accept: "application/json" },
201
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body)
202
+ };
203
+ for (let attempt = 0; ; attempt++) {
204
+ let response;
205
+ let text;
206
+ try {
207
+ response = await this.fetchFn(url, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
208
+ text = await response.text();
209
+ } catch (error) {
210
+ if (attempt >= this.retries) throw error;
211
+ await sleep(this.retryDelayMs * 2 ** attempt);
212
+ continue;
213
+ }
214
+ const body = text ? parse(text) : void 0;
215
+ if (response.ok) return body;
216
+ const retryable = response.status === 429 || response.status >= 500;
217
+ if (!retryable || attempt >= this.retries) throw new ConstellationError(response.status, body, this.baseUrl);
218
+ const after = Math.min(Number(response.headers.get("retry-after")), MAX_RETRY_AFTER_S);
219
+ if (after > 0) this.log(`answered ${response.status}; retrying in ${after} s (Retry-After)`);
220
+ await sleep(after > 0 ? after * 1e3 : this.retryDelayMs * 2 ** attempt);
221
+ }
222
+ }
223
+ /**
224
+ * One page of workflow results after `after`: whole entries, or first pages when `pageRecords` is set.
225
+ * `from: "latest"` asks where a first start reads from instead: no entries, and `next` just before
226
+ * the newest run with something for `consumer`.
227
+ */
228
+ resultsPage(options = {}) {
229
+ return this.request("GET", "/predictions/feed", {
230
+ query: {
231
+ from: options.from,
232
+ after: options.after ?? "",
233
+ limit: options.limit,
234
+ consumer: options.consumer,
235
+ page_records: options.pageRecords
236
+ }
237
+ });
238
+ }
239
+ /**
240
+ * Runs with results after `after`, oldest first, each joined whole and unpacked; a cursor older than
241
+ * the oldest entry the feed holds is logged (the runs between expired unread). Ends when the API
242
+ * has no more, unless `pollMs` is set: then it waits that long and asks again, for as long as the
243
+ * caller iterates or until `signal` aborts.
244
+ */
245
+ async *results(options = {}) {
246
+ const { consumer } = options;
247
+ let after = options.after ?? "";
248
+ while (!options.signal?.aborted) {
249
+ const page = await this.resultsPage({ after, consumer, limit: 1, pageRecords: PAGE_RECORDS });
250
+ if (after && page.oldest && after < page.oldest)
251
+ this.log(`the feed no longer holds cursor ${after}: any runs after it and before the oldest it holds, ${page.oldest}, expired unread; reading on from there`);
252
+ for (const entry of page.entries) {
253
+ const full = await whole(
254
+ entry,
255
+ (cursor, n) => this.request("GET", "/predictions/feed", {
256
+ query: { cursor, page: n, page_records: PAGE_RECORDS, consumer }
257
+ })
258
+ );
259
+ yield { cursor: entry.cursor, parts: unpack(full, consumer, this.log) };
260
+ after = entry.cursor;
261
+ }
262
+ if (page.entries.length) continue;
263
+ if (options.pollMs === void 0) return;
264
+ await sleep(options.pollMs);
265
+ }
266
+ }
267
+ /** Registers a custom bridge's manifest; it waits for approval on Integrations. */
268
+ checkIn(manifest) {
269
+ const { name, title, description, settings } = manifest;
270
+ const body = {
271
+ consumer: name,
272
+ system: "custom",
273
+ manifest: { name, title, ...description !== void 0 && { description }, ...settings && { settings } },
274
+ bridge_version: manifest.version ?? "0.1.0",
275
+ target: title
276
+ };
277
+ return this.request("POST", "/predictions/feed/checkin", { body });
278
+ }
279
+ /** Tells Constellation what the run at `cursor` became in the system, shown in Constellation. */
280
+ report(consumer, cursor, applied, target) {
281
+ const body = { consumer, run_id: cursor.slice(cursor.indexOf("#") + 1), cursor, applied, target };
282
+ return this.request("POST", "/predictions/feed/deliveries", { body });
283
+ }
284
+ };
285
+ function parse(text) {
286
+ try {
287
+ return JSON.parse(text);
288
+ } catch {
289
+ return text;
290
+ }
291
+ }
292
+ // Annotate the CommonJS export names for ESM import in node:
293
+ 0 && (module.exports = {
294
+ Client,
295
+ ConstellationError,
296
+ DEFAULT_API_URL,
297
+ PAGE_RECORDS,
298
+ SCHEMA,
299
+ actionState,
300
+ plain,
301
+ unpack,
302
+ whole
303
+ });