@tangle-network/hub-sdk 0.20.0-develop.20260812124431.b971fd8 → 0.20.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.js CHANGED
@@ -1,7 +1,217 @@
1
1
  import { SSEChunkParser } from "@tangle-network/sdk-telemetry";
2
+ //#region src/json-init.ts
3
+ /** The init of a request whose body is JSON. Every client builds its bodies
4
+ * here, so the content type cannot drift from the encoding. */
5
+ function jsonInit(method, body) {
6
+ return {
7
+ method,
8
+ body: JSON.stringify(body),
9
+ headers: { "Content-Type": "application/json" }
10
+ };
11
+ }
12
+ //#endregion
13
+ //#region src/allowances.ts
14
+ var HubAllowancesClient = class {
15
+ constructor(request) {
16
+ this.request = request;
17
+ }
18
+ async plan(meter) {
19
+ return (await this.request(this.path(meter), { method: "GET" })).plan;
20
+ }
21
+ async setPlan(meter, plan) {
22
+ return (await this.request(this.path(meter), this.body("PUT", plan))).plan;
23
+ }
24
+ /** Admit one turn or refuse it. Retrying the same `turnId` never counts twice. */
25
+ async admit(meter, input) {
26
+ return (await this.request(`${this.path(meter)}/turns`, this.body("POST", input))).allowance;
27
+ }
28
+ /** What the member's next turn would get, without counting anything. */
29
+ async status(meter, subject) {
30
+ const query = new URLSearchParams();
31
+ if (subject.role) query.set("role", subject.role);
32
+ if (subject.payer) query.set("payer", subject.payer);
33
+ if (subject.payerRole) query.set("payerRole", subject.payerRole);
34
+ const suffix = query.size ? `?${query}` : "";
35
+ return (await this.request(`${this.memberPath(meter, subject.member)}${suffix}`, { method: "GET" })).allowance;
36
+ }
37
+ /** Move a member to the paid allowance until `expiresAt` (the paid period's end). */
38
+ async grant(meter, member, input) {
39
+ return (await this.request(`${this.memberPath(meter, member)}/grant`, this.body("PUT", {
40
+ tier: "paid",
41
+ ...input
42
+ }))).grant;
43
+ }
44
+ async revoke(meter, member) {
45
+ await this.request(`${this.memberPath(meter, member)}/grant`, { method: "DELETE" });
46
+ }
47
+ /** Turns per member and per line on one UTC day (default today). */
48
+ async usage(meter, day) {
49
+ const suffix = day ? `?day=${encodeURIComponent(day)}` : "";
50
+ return (await this.request(`${this.path(meter)}/usage${suffix}`, { method: "GET" })).usage;
51
+ }
52
+ path(meter) {
53
+ return `/v1/hub/allowances/${encodeURIComponent(meter)}`;
54
+ }
55
+ memberPath(meter, member) {
56
+ return `${this.path(meter)}/members/${encodeURIComponent(member)}`;
57
+ }
58
+ body(method, body) {
59
+ return jsonInit(method, body);
60
+ }
61
+ };
62
+ //#endregion
63
+ //#region src/apps.ts
64
+ function encodedId(id) {
65
+ if (typeof id !== "string" || !id || id.length > 256 || id === "." || id === "..") throw new Error("A bounded app or grant id is required");
66
+ return encodeURIComponent(id);
67
+ }
68
+ var HubAppsClient = class {
69
+ grants;
70
+ constructor(request) {
71
+ this.request = request;
72
+ this.grants = {
73
+ list: () => this.request("/v1/me/app-grants", { method: "GET" }),
74
+ revoke: async (grantId) => this.request(`/v1/me/app-grants/${encodedId(grantId)}/revoke`, { method: "POST" })
75
+ };
76
+ }
77
+ list() {
78
+ return this.request("/v1/apps", { method: "GET" });
79
+ }
80
+ /** The secret is returned only by creation; keep it in your server vault. */
81
+ create(input) {
82
+ return this.request("/v1/apps", jsonInit("POST", input));
83
+ }
84
+ /** Immutable association of two existing records with the same owner. */
85
+ async linkOAuthClient(appId, clientId) {
86
+ return this.request(`/v1/apps/${encodedId(appId)}/oidc-client`, jsonInit("POST", { clientId }));
87
+ }
88
+ async revoke(appId) {
89
+ return this.request(`/v1/apps/${encodedId(appId)}/revoke`, { method: "POST" });
90
+ }
91
+ };
92
+ //#endregion
93
+ //#region src/inbound-webhooks.ts
94
+ var HubInboundWebhooksClient = class {
95
+ constructor(request) {
96
+ this.request = request;
97
+ }
98
+ async create(connectionId, options = {}) {
99
+ return this.request(this.path(connectionId), jsonInit("POST", options));
100
+ }
101
+ async get(connectionId) {
102
+ return this.request(this.path(connectionId), { method: "GET" });
103
+ }
104
+ /** Add one owned Linq WhatsApp number without rotating the webhook secret. */
105
+ async ensurePhoneNumber(connectionId, phoneNumberId) {
106
+ if (!phoneNumberId || phoneNumberId.length > 128 || !/^[\x21-\x7e]+$/.test(phoneNumberId)) throw new Error("A bounded phone-number id is required");
107
+ return this.request(`${this.path(connectionId)}/phone-numbers/ensure`, jsonInit("POST", { phoneNumberId }));
108
+ }
109
+ /** Remove event subscriptions first. This does not silently rotate a live URL. */
110
+ async delete(connectionId) {
111
+ return this.request(this.path(connectionId), { method: "DELETE" });
112
+ }
113
+ path(connectionId) {
114
+ if (!connectionId || connectionId.length > 256) throw new Error("A bounded connection id is required");
115
+ return `/v1/hub/connections/${encodeURIComponent(connectionId)}/inbound-webhook`;
116
+ }
117
+ };
118
+ //#endregion
119
+ //#region src/lines.ts
120
+ /** Line calls share HubClient authentication and envelope handling. */
121
+ var HubLinesClient = class {
122
+ members;
123
+ checkins;
124
+ constructor(request, createWorkflow) {
125
+ this.request = request;
126
+ this.createWorkflow = createWorkflow;
127
+ this.members = { list: async (lineId) => (await this.request(`/v1/hub/lines/${encodeURIComponent(lineId)}/members`, { method: "GET" })).members };
128
+ this.checkins = { schedule: (cron, options) => {
129
+ const name = options.name ?? `line-checkin-${crypto.randomUUID().slice(0, 8)}`;
130
+ const yaml = [
131
+ `name: ${JSON.stringify(name)}`,
132
+ "on:",
133
+ ` schedule: { cron: ${JSON.stringify(cron)}, timezone: ${JSON.stringify(options.timezone)} }`,
134
+ "do:",
135
+ " - agent.run:",
136
+ " line:",
137
+ ` id: ${JSON.stringify(options.lineId)}`,
138
+ ` member: ${JSON.stringify(options.member)}`,
139
+ ` prompt: ${JSON.stringify(options.prompt)}`
140
+ ].join("\n");
141
+ return this.createWorkflow(yaml);
142
+ } };
143
+ }
144
+ async context() {
145
+ return this.request("/v1/hub/lines/context", { method: "GET" });
146
+ }
147
+ async send(lineId, input) {
148
+ return this.request(`/v1/hub/lines/${encodeURIComponent(lineId)}/send`, jsonInit("POST", input));
149
+ }
150
+ async remind(lineId, input) {
151
+ return this.request(`/v1/hub/lines/${encodeURIComponent(lineId)}/remind`, jsonInit("POST", input));
152
+ }
153
+ };
154
+ //#endregion
155
+ //#region src/managed-numbers.ts
156
+ /** Administrative number operations through Hub's authenticated transport.
157
+ * A mutation is one attempt; an uncertain create reuses its quote and reference. */
158
+ var HubManagedNumbersClient = class {
159
+ constructor(request) {
160
+ this.request = request;
161
+ }
162
+ readiness() {
163
+ return this.request("/v1/hub/numbers/readiness", { method: "GET" });
164
+ }
165
+ /** One page of orders. Scope by `clientReference` to ask about one binding,
166
+ * and follow `nextCursor` for the rest; a page is never ownership evidence. */
167
+ list(query = {}) {
168
+ const params = new URLSearchParams();
169
+ if (query.clientReference !== void 0) params.set("clientReference", query.clientReference);
170
+ if (query.cursor !== void 0) params.set("cursor", query.cursor);
171
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
172
+ const search = params.toString();
173
+ return this.request(`/v1/hub/numbers${search ? `?${search}` : ""}`, { method: "GET" });
174
+ }
175
+ get(id) {
176
+ return this.request(this.path(id), { method: "GET" });
177
+ }
178
+ quote(input) {
179
+ return this.request("/v1/hub/numbers/quote", this.post(input));
180
+ }
181
+ /** `clientReference` and `transport`, when given, must match the signed
182
+ * quote or Hub refuses the purchase with a conflict. */
183
+ create(input) {
184
+ return this.request("/v1/hub/numbers", this.post(input));
185
+ }
186
+ /** Fences references so no order can take them again. Call it as the last
187
+ * step before retiring the resource they name: a purchase that races the
188
+ * retirement is then refused (`409 number_reference_fenced`) instead of
189
+ * binding a line to a resource that is gone. Refused with
190
+ * `409 number_reference_held` while a live order holds one of them; cancel
191
+ * it first. A cancelled order no longer holds its reference, so the fence
192
+ * succeeds as soon as `cancel` returns, whether or not its release is still
193
+ * pending. Repeating a fence is harmless. */
194
+ fence(input) {
195
+ return this.request("/v1/hub/numbers/fences", this.post(input));
196
+ }
197
+ advance(id) {
198
+ return this.request(`${this.path(id)}/advance`, this.post({}));
199
+ }
200
+ cancel(id) {
201
+ return this.request(`${this.path(id)}/cancel`, this.post({}));
202
+ }
203
+ path(id) {
204
+ if (!/^num_[a-f0-9]{36}$/.test(id)) throw new Error("Invalid managed number order id");
205
+ return `/v1/hub/numbers/${encodeURIComponent(id)}`;
206
+ }
207
+ post(body) {
208
+ return jsonInit("POST", body);
209
+ }
210
+ };
211
+ //#endregion
2
212
  //#region src/redaction.ts
3
213
  const SECRET_KEY_PATTERN = /(api[_-]?key|authorization|capability[_-]?token|token|secret)/i;
4
- const SECRET_VALUE_PATTERN = /\b(?:sk-tan[-_]|hubcap_|hct_|gh[pousr]_)[A-Za-z0-9_=-]+\b/g;
214
+ const SECRET_VALUE_PATTERN = /\b(?:sk-tan[-_]|hubcap_|hct_|lrc_|gh[pousr]_)[A-Za-z0-9_.=-]+\b/g;
5
215
  function redactHubValue(value) {
6
216
  if (typeof value === "string") return value.replace(SECRET_VALUE_PATTERN, "[REDACTED]");
7
217
  if (Array.isArray(value)) return value.map((item) => redactHubValue(item));
@@ -52,8 +262,10 @@ function isHubSuccessEnvelope(value) {
52
262
  function isRecord$1(value) {
53
263
  return typeof value === "object" && value !== null;
54
264
  }
55
- function optString(value) {
56
- return typeof value === "string" ? value : "";
265
+ /** Read a wire field as a string, or "" when the server sent anything else.
266
+ * `raw` is that field straight off the parsed payload, before any check. */
267
+ function optString(raw) {
268
+ return typeof raw === "string" ? raw : "";
57
269
  }
58
270
  /** An agent iteration's terminal status (`iteration.ended`) — only ever
59
271
  * succeeded/failed; an iteration is never guard-skipped. */
@@ -81,63 +293,63 @@ function isRunDoneStatus(value) {
81
293
  * malformed `token` can never reach a consumer as `{ delta: undefined }`, and
82
294
  * new server event kinds don't break older clients.
83
295
  */
84
- function toRunStreamEvent(eventType, data) {
296
+ function toRunStreamEvent(eventType, raw) {
85
297
  if (eventType === "ping") return { type: "ping" };
86
- if (!isRecord$1(data)) return null;
298
+ if (!isRecord$1(raw)) return null;
87
299
  switch (eventType) {
88
- case "snapshot": return typeof data.id === "string" && typeof data.workflowId === "string" && typeof data.status === "string" && Array.isArray(data.actionResults) ? {
300
+ case "snapshot": return typeof raw.id === "string" && typeof raw.workflowId === "string" && typeof raw.status === "string" && Array.isArray(raw.actionResults) ? {
89
301
  type: "snapshot",
90
- run: data
302
+ run: raw
91
303
  } : null;
92
- case "token": return typeof data.delta === "string" && typeof data.actionIndex === "number" ? {
304
+ case "token": return typeof raw.delta === "string" && typeof raw.actionIndex === "number" ? {
93
305
  type: "token",
94
- actionIndex: data.actionIndex,
95
- delta: data.delta,
96
- at: optString(data.at)
306
+ actionIndex: raw.actionIndex,
307
+ delta: raw.delta,
308
+ at: optString(raw.at)
97
309
  } : null;
98
- case "run.done": return isRunDoneStatus(data.status) ? {
310
+ case "run.done": return isRunDoneStatus(raw.status) ? {
99
311
  type: "run.done",
100
- status: data.status,
101
- error: typeof data.error === "string" ? data.error : null,
102
- ...typeof data.at === "string" ? { at: data.at } : {}
312
+ status: raw.status,
313
+ error: typeof raw.error === "string" ? raw.error : null,
314
+ ...typeof raw.at === "string" ? { at: raw.at } : {}
103
315
  } : null;
104
- case "run.waiting": return typeof data.decisionId === "string" && data.decisionId.length > 0 ? {
316
+ case "run.waiting": return typeof raw.decisionId === "string" && raw.decisionId.length > 0 ? {
105
317
  type: "run.waiting",
106
- decisionId: data.decisionId,
107
- ...typeof data.at === "string" ? { at: data.at } : {}
318
+ decisionId: raw.decisionId,
319
+ ...typeof raw.at === "string" ? { at: raw.at } : {}
108
320
  } : null;
109
- case "action.started": return typeof data.index === "number" && typeof data.kind === "string" && typeof data.at === "string" ? {
321
+ case "action.started": return typeof raw.index === "number" && typeof raw.kind === "string" && typeof raw.at === "string" ? {
110
322
  type: "action.started",
111
- index: data.index,
112
- kind: data.kind,
113
- at: data.at
323
+ index: raw.index,
324
+ kind: raw.kind,
325
+ at: raw.at
114
326
  } : null;
115
- case "action.finished": return typeof data.index === "number" && typeof data.kind === "string" && isActionFinishedStatus(data.status) && typeof data.at === "string" ? {
327
+ case "action.finished": return typeof raw.index === "number" && typeof raw.kind === "string" && isActionFinishedStatus(raw.status) && typeof raw.at === "string" ? {
116
328
  type: "action.finished",
117
- index: data.index,
118
- kind: data.kind,
119
- status: data.status,
120
- at: data.at,
121
- ...typeof data.costUsd === "number" ? { costUsd: data.costUsd } : {},
122
- ...typeof data.error === "string" ? { error: data.error } : {}
329
+ index: raw.index,
330
+ kind: raw.kind,
331
+ status: raw.status,
332
+ at: raw.at,
333
+ ...typeof raw.costUsd === "number" ? { costUsd: raw.costUsd } : {},
334
+ ...typeof raw.error === "string" ? { error: raw.error } : {}
123
335
  } : null;
124
- case "iteration.started": return typeof data.actionIndex === "number" && typeof data.iterationIndex === "number" && typeof data.at === "string" ? {
336
+ case "iteration.started": return typeof raw.actionIndex === "number" && typeof raw.iterationIndex === "number" && typeof raw.at === "string" ? {
125
337
  type: "iteration.started",
126
- actionIndex: data.actionIndex,
127
- iterationIndex: data.iterationIndex,
128
- at: data.at,
129
- ...typeof data.model === "string" ? { model: data.model } : {}
338
+ actionIndex: raw.actionIndex,
339
+ iterationIndex: raw.iterationIndex,
340
+ at: raw.at,
341
+ ...typeof raw.model === "string" ? { model: raw.model } : {}
130
342
  } : null;
131
- case "iteration.ended": return typeof data.actionIndex === "number" && typeof data.iterationIndex === "number" && isIterationStatus(data.status) && typeof data.at === "string" ? {
343
+ case "iteration.ended": return typeof raw.actionIndex === "number" && typeof raw.iterationIndex === "number" && isIterationStatus(raw.status) && typeof raw.at === "string" ? {
132
344
  type: "iteration.ended",
133
- actionIndex: data.actionIndex,
134
- iterationIndex: data.iterationIndex,
135
- status: data.status,
136
- at: data.at,
137
- ...typeof data.outputPreview === "string" ? { outputPreview: data.outputPreview } : {},
138
- ...typeof data.inputTokens === "number" ? { inputTokens: data.inputTokens } : {},
139
- ...typeof data.outputTokens === "number" ? { outputTokens: data.outputTokens } : {},
140
- ...typeof data.costUsd === "number" ? { costUsd: data.costUsd } : {}
345
+ actionIndex: raw.actionIndex,
346
+ iterationIndex: raw.iterationIndex,
347
+ status: raw.status,
348
+ at: raw.at,
349
+ ...typeof raw.outputPreview === "string" ? { outputPreview: raw.outputPreview } : {},
350
+ ...typeof raw.inputTokens === "number" ? { inputTokens: raw.inputTokens } : {},
351
+ ...typeof raw.outputTokens === "number" ? { outputTokens: raw.outputTokens } : {},
352
+ ...typeof raw.costUsd === "number" ? { costUsd: raw.costUsd } : {}
141
353
  } : null;
142
354
  default: return null;
143
355
  }
@@ -145,8 +357,8 @@ function toRunStreamEvent(eventType, data) {
145
357
  /** True for an aborted/timed-out fetch (or any abort). fetch rejects with the
146
358
  * signal's reason — a DOMException named `AbortError` (caller) or `TimeoutError`
147
359
  * (AbortSignal.timeout). */
148
- function isAbortError(err) {
149
- return err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError");
360
+ function isAbortError(cause) {
361
+ return cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError");
150
362
  }
151
363
  /** A signal that aborts when the caller's signal aborts OR `timeoutMs` elapses.
152
364
  * Returns undefined when neither bound applies (no per-request abort needed). */
@@ -225,8 +437,11 @@ var HubClient = class HubClient {
225
437
  fetch;
226
438
  apiKey;
227
439
  authHeaders;
440
+ allowances;
441
+ apps;
228
442
  connections;
229
443
  channels;
444
+ numbers;
230
445
  eventSubscriptions;
231
446
  permissions;
232
447
  tokens;
@@ -235,11 +450,15 @@ var HubClient = class HubClient {
235
450
  audit;
236
451
  githubApp;
237
452
  workflows;
453
+ lines;
238
454
  constructor(options) {
239
455
  this.baseUrl = options.baseUrl.replace(/\/+$/, "");
240
456
  this.apiKey = options.apiKey;
241
457
  this.authHeaders = options.authHeaders;
242
458
  this.fetch = options.fetch ?? fetch.bind(globalThis);
459
+ this.allowances = new HubAllowancesClient((path, init) => this.request(path, init));
460
+ this.apps = new HubAppsClient((path, init) => this.request(path, init));
461
+ this.numbers = new HubManagedNumbersClient((path, init) => this.request(path, init));
243
462
  this.connections = new HubConnectionsClient((path, init) => this.request(path, init));
244
463
  this.channels = new HubChannelsClient((path, init) => this.request(path, init));
245
464
  this.eventSubscriptions = new HubEventSubscriptionsClient((path, init) => this.request(path, init));
@@ -250,6 +469,7 @@ var HubClient = class HubClient {
250
469
  this.audit = new HubAuditClient((path, init) => this.request(path, init));
251
470
  this.githubApp = new HubGithubAppClient((path, init) => this.request(path, init));
252
471
  this.workflows = new HubWorkflowsClient((path, init) => this.request(path, init), (path, init) => this.stream(path, init), (path, init) => this.requestBytes(path, init));
472
+ this.lines = new HubLinesClient((path, init) => this.request(path, init), (yaml) => this.workflows.create(yaml));
253
473
  }
254
474
  static fromEnv(options = {}) {
255
475
  const env = options.env ?? readProcessEnv();
@@ -362,11 +582,7 @@ var HubTokensClient = class {
362
582
  this.request = request;
363
583
  }
364
584
  async mint(options) {
365
- return this.request("/v1/hub/tokens", {
366
- method: "POST",
367
- body: JSON.stringify(options),
368
- headers: { "Content-Type": "application/json" }
369
- });
585
+ return this.request("/v1/hub/tokens", jsonInit("POST", options));
370
586
  }
371
587
  async list(options = {}) {
372
588
  const searchParams = new URLSearchParams();
@@ -400,38 +616,22 @@ var HubPermissionsClient = class {
400
616
  return this.request(`/v1/hub/policies?connectionId=${encodeURIComponent(connectionId)}`, { method: "GET" });
401
617
  }
402
618
  async set(input) {
403
- return this.request("/v1/hub/policies", {
404
- method: "PUT",
405
- body: JSON.stringify(input),
406
- headers: { "Content-Type": "application/json" }
407
- });
619
+ return this.request("/v1/hub/policies", jsonInit("PUT", input));
408
620
  }
409
621
  /** Reset an action to its default by deleting any stored override. */
410
622
  async delete(input) {
411
- return this.request("/v1/hub/policies", {
412
- method: "DELETE",
413
- body: JSON.stringify(input),
414
- headers: { "Content-Type": "application/json" }
415
- });
623
+ return this.request("/v1/hub/policies", jsonInit("DELETE", input));
416
624
  }
417
625
  /** Bulk-allow every write action of a connection's provider. Reads are
418
626
  * already allowed for sandbox agents; destructive actions stay `ask`.
419
627
  * Idempotent: actions with an existing policy are left untouched. */
420
628
  async allowWrites(connectionId) {
421
- return this.request("/v1/hub/policies/allow-writes", {
422
- method: "POST",
423
- body: JSON.stringify({ connectionId }),
424
- headers: { "Content-Type": "application/json" }
425
- });
629
+ return this.request("/v1/hub/policies/allow-writes", jsonInit("POST", { connectionId }));
426
630
  }
427
631
  /** Inverse of `allowWrites`: delete only the rows it created for this
428
632
  * connection. Manual per-action decisions are left intact. */
429
633
  async revertWrites(connectionId) {
430
- return this.request("/v1/hub/policies/revert-writes", {
431
- method: "POST",
432
- body: JSON.stringify({ connectionId }),
433
- headers: { "Content-Type": "application/json" }
434
- });
634
+ return this.request("/v1/hub/policies/revert-writes", jsonInit("POST", { connectionId }));
435
635
  }
436
636
  };
437
637
  var HubToolsClient = class {
@@ -439,34 +639,32 @@ var HubToolsClient = class {
439
639
  this.request = request;
440
640
  }
441
641
  async search(query, options = {}) {
442
- return this.request("/v1/hub/tools/search", {
443
- method: "POST",
444
- body: JSON.stringify({
445
- query,
446
- provider: options.provider,
447
- limit: options.limit
448
- }),
449
- headers: { "Content-Type": "application/json" }
450
- });
642
+ return this.request("/v1/hub/tools/search", jsonInit("POST", {
643
+ query,
644
+ provider: options.provider,
645
+ limit: options.limit
646
+ }));
451
647
  }
452
648
  async sources() {
453
649
  return this.request("/v1/hub/tools/sources", { method: "GET" });
454
650
  }
455
651
  async describe(path) {
456
- return this.request("/v1/hub/tools/describe", {
457
- method: "POST",
458
- body: JSON.stringify({ path }),
459
- headers: { "Content-Type": "application/json" }
460
- });
652
+ return this.request("/v1/hub/tools/describe", jsonInit("POST", { path }));
461
653
  }
462
- async invoke(path, input, options = {}) {
463
- const execInit = this.buildExecInit(path, input, options.connectionId);
654
+ /**
655
+ * Run one hub tool. `raw` is the tool input: the SDK forwards it verbatim as
656
+ * the request body's `input`, and the server validates it against the tool's
657
+ * own schema, so the client never gives it a shape.
658
+ */
659
+ async invoke(path, raw, options = {}) {
660
+ const execInit = this.buildExecInit(path, raw, options);
464
661
  try {
465
662
  return await this.request("/v1/hub/exec", execInit);
466
663
  } catch (error) {
467
664
  if (!(error instanceof HubSdkError) || !requiresCapabilityToken(error)) throw error;
665
+ const approvalId = getApprovalId(error);
666
+ if (approvalId && options.approve !== true) throw error;
468
667
  if (options.approve) {
469
- const approvalId = getApprovalId(error);
470
668
  if (!approvalId) throw error;
471
669
  const approved = await this.request(`/v1/hub/approvals/${encodeURIComponent(approvalId)}/approve`, { method: "POST" });
472
670
  validateApprovedExecution(approved, path, options.connectionId);
@@ -484,15 +682,11 @@ var HubToolsClient = class {
484
682
  });
485
683
  }
486
684
  }
487
- const minted = await this.request("/v1/hub/tokens", {
488
- method: "POST",
489
- body: JSON.stringify({
490
- actionPath: path,
491
- connectionId: options.connectionId,
492
- provider: options.connectionId ? void 0 : path.split(".")[0]
493
- }),
494
- headers: { "Content-Type": "application/json" }
495
- });
685
+ const minted = await this.request("/v1/hub/tokens", jsonInit("POST", {
686
+ actionPath: path,
687
+ connectionId: options.connectionId,
688
+ provider: options.connectionId ? void 0 : path.split(".")[0]
689
+ }));
496
690
  return this.request("/v1/hub/exec", {
497
691
  ...execInit,
498
692
  headers: {
@@ -501,16 +695,13 @@ var HubToolsClient = class {
501
695
  }
502
696
  });
503
697
  }
504
- buildExecInit(path, input, connectionId) {
505
- return {
506
- method: "POST",
507
- body: JSON.stringify({
508
- path,
509
- input,
510
- connectionId
511
- }),
512
- headers: { "Content-Type": "application/json" }
513
- };
698
+ buildExecInit(path, raw, options) {
699
+ return jsonInit("POST", {
700
+ path,
701
+ input: raw,
702
+ connectionId: options.connectionId,
703
+ idempotencyKey: options.idempotencyKey
704
+ });
514
705
  }
515
706
  };
516
707
  function requiresCapabilityToken(error) {
@@ -540,6 +731,17 @@ function validateApprovedExecution(approved, path, connectionId) {
540
731
  }
541
732
  });
542
733
  }
734
+ const GITHUB_EXACT_CONNECT_SCOPES = [
735
+ "read:user",
736
+ "repo",
737
+ "read:org"
738
+ ];
739
+ function sameOAuthScopeSet(left, right) {
740
+ if (!Array.isArray(left)) return false;
741
+ const leftSet = new Set(left);
742
+ const rightSet = new Set(right);
743
+ return leftSet.size === left.length && rightSet.size === right.length && leftSet.size === rightSet.size && [...leftSet].every((scope) => rightSet.has(scope));
744
+ }
543
745
  var HubChannelsClient = class {
544
746
  constructor(request) {
545
747
  this.request = request;
@@ -548,11 +750,7 @@ var HubChannelsClient = class {
548
750
  return this.request("/v1/hub/channels", { method: "GET" });
549
751
  }
550
752
  async createEmail(input = {}) {
551
- return this.request("/v1/hub/channels/email", {
552
- method: "POST",
553
- body: JSON.stringify(input),
554
- headers: { "Content-Type": "application/json" }
555
- });
753
+ return this.request("/v1/hub/channels/email", jsonInit("POST", input));
556
754
  }
557
755
  async delete(channelId) {
558
756
  return this.request(`/v1/hub/channels/${encodeURIComponent(channelId)}`, { method: "DELETE" });
@@ -566,19 +764,17 @@ var HubEventSubscriptionsClient = class {
566
764
  return this.request("/v1/hub/event-subscriptions", { method: "GET" });
567
765
  }
568
766
  async create(input) {
569
- return this.request("/v1/hub/event-subscriptions", {
570
- method: "POST",
571
- body: JSON.stringify(input),
572
- headers: { "Content-Type": "application/json" }
573
- });
767
+ return this.request("/v1/hub/event-subscriptions", jsonInit("POST", input));
574
768
  }
575
769
  async delete(subscriptionId) {
576
770
  return this.request(`/v1/hub/event-subscriptions/${encodeURIComponent(subscriptionId)}`, { method: "DELETE" });
577
771
  }
578
772
  };
579
773
  var HubConnectionsClient = class {
774
+ inboundWebhook;
580
775
  constructor(request) {
581
776
  this.request = request;
777
+ this.inboundWebhook = new HubInboundWebhooksClient(request);
582
778
  }
583
779
  async list() {
584
780
  return this.request("/v1/hub/connections", { method: "GET" });
@@ -590,40 +786,38 @@ var HubConnectionsClient = class {
590
786
  return this.request("/v1/hub/providers", { method: "GET" });
591
787
  }
592
788
  async start(provider, options = {}) {
593
- return this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/start`, {
594
- method: "POST",
595
- body: JSON.stringify({
596
- returnUrl: options.returnUrl,
597
- cli: options.cli,
598
- connectionParameters: options.connectionParameters
599
- }),
600
- headers: { "Content-Type": "application/json" }
789
+ if (options.requestedScopes !== void 0 && (provider !== "github" || !sameOAuthScopeSet(options.requestedScopes, GITHUB_EXACT_CONNECT_SCOPES))) throw new HubSdkError({
790
+ code: "HUB_INVALID_INPUT",
791
+ message: "GitHub requestedScopes must be read:user, repo, and read:org"
792
+ });
793
+ const started = await this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/start`, jsonInit("POST", {
794
+ returnUrl: options.returnUrl,
795
+ cli: options.cli,
796
+ connectionParameters: options.connectionParameters,
797
+ requestedScopes: options.requestedScopes
798
+ }));
799
+ if (options.requestedScopes !== void 0 && (started.provider !== provider || !sameOAuthScopeSet(started.scopes, options.requestedScopes))) throw new HubSdkError({
800
+ code: "HUB_CONFIG_MISSING",
801
+ message: "Hub did not preserve the requested OAuth scopes"
601
802
  });
803
+ return started;
602
804
  }
603
805
  async startWhatsappEmbeddedSignup(options = {}) {
604
- return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/start", {
605
- method: "POST",
606
- body: JSON.stringify({ returnUrl: options.returnUrl }),
607
- headers: { "Content-Type": "application/json" }
608
- });
806
+ return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/start", jsonInit("POST", { returnUrl: options.returnUrl }));
609
807
  }
610
808
  async completeWhatsappEmbeddedSignup(input) {
611
- return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/complete", {
612
- method: "POST",
613
- body: JSON.stringify(input),
614
- headers: { "Content-Type": "application/json" }
615
- });
809
+ return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/complete", jsonInit("POST", input));
616
810
  }
617
811
  /** Connect a non-OAuth (api-key) connector by submitting the user's key.
618
812
  * The server validates the key with a live probe before persisting and
619
813
  * returns the created (or reconnected) connection — there is no redirect,
620
- * unlike `start`. */
621
- async connectApiKey(provider, apiKey) {
622
- return this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/connect-key`, {
623
- method: "POST",
624
- body: JSON.stringify({ apiKey }),
625
- headers: { "Content-Type": "application/json" }
626
- });
814
+ * unlike `start`. Cloudbeds requires propertyId metadata and PriceLabs
815
+ * requires listing ID/PMS pairs; other providers have no metadata. */
816
+ async connectApiKey(provider, apiKey, metadata) {
817
+ return this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/connect-key`, jsonInit("POST", {
818
+ apiKey,
819
+ ...metadata === void 0 ? {} : { metadata }
820
+ }));
627
821
  }
628
822
  async revoke(connectionId) {
629
823
  return this.request(`/v1/hub/connections/${encodeURIComponent(connectionId)}`, { method: "DELETE" });
@@ -651,11 +845,7 @@ var HubGithubAppClient = class {
651
845
  this.request = request;
652
846
  }
653
847
  async mintInstallationToken(input) {
654
- return this.request("/v1/hub/github-app/mint-installation-token", {
655
- method: "POST",
656
- body: JSON.stringify(input),
657
- headers: { "Content-Type": "application/json" }
658
- });
848
+ return this.request("/v1/hub/github-app/mint-installation-token", jsonInit("POST", input));
659
849
  }
660
850
  /** Every installation the caller may act through — their own and any org's
661
851
  * they were verified against. The management surface's read. */
@@ -730,11 +920,7 @@ var HubWorkflowsClient = class {
730
920
  return this.request(`/v1/workflows/${encodeURIComponent(id)}`, { method: "GET" });
731
921
  }
732
922
  async create(yaml) {
733
- return this.request("/v1/workflows", {
734
- method: "POST",
735
- body: JSON.stringify({ yaml }),
736
- headers: { "Content-Type": "application/json" }
737
- });
923
+ return this.request("/v1/workflows", jsonInit("POST", { yaml }));
738
924
  }
739
925
  /**
740
926
  * Replace the workflow's definition from YAML (recompiled server-side,
@@ -745,14 +931,10 @@ var HubWorkflowsClient = class {
745
931
  * concurrent modification, `NOT_FOUND` for an unknown/foreign id.
746
932
  */
747
933
  async update(id, yaml, opts = {}) {
748
- return this.request(`/v1/workflows/${encodeURIComponent(id)}`, {
749
- method: "PUT",
750
- body: JSON.stringify({
751
- yaml,
752
- ...opts.note !== void 0 ? { note: opts.note } : {}
753
- }),
754
- headers: { "Content-Type": "application/json" }
755
- });
934
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}`, jsonInit("PUT", {
935
+ yaml,
936
+ ...opts.note !== void 0 ? { note: opts.note } : {}
937
+ }));
756
938
  }
757
939
  async delete(id) {
758
940
  await this.request(`/v1/workflows/${encodeURIComponent(id)}`, { method: "DELETE" });
@@ -763,11 +945,7 @@ var HubWorkflowsClient = class {
763
945
  * via `update`, but it can still be paused/resumed here).
764
946
  */
765
947
  async setEnabled(id, enabled) {
766
- return this.request(`/v1/workflows/${encodeURIComponent(id)}`, {
767
- method: "PATCH",
768
- body: JSON.stringify({ enabled }),
769
- headers: { "Content-Type": "application/json" }
770
- });
948
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}`, jsonInit("PATCH", { enabled }));
771
949
  }
772
950
  /**
773
951
  * One page of run history, newest first. Pass the previous page's
@@ -795,9 +973,7 @@ var HubWorkflowsClient = class {
795
973
  async run(id, inputs, opts = {}) {
796
974
  const hasInputs = inputs !== void 0 && Object.keys(inputs).length > 0;
797
975
  return this.request(`/v1/workflows/${encodeURIComponent(id)}/run`, {
798
- method: "POST",
799
- body: JSON.stringify(hasInputs ? { inputs } : {}),
800
- headers: { "Content-Type": "application/json" },
976
+ ...jsonInit("POST", hasInputs ? { inputs } : {}),
801
977
  ...opts.signal ? { signal: opts.signal } : {}
802
978
  });
803
979
  }
@@ -976,11 +1152,7 @@ var HubWorkflowsClient = class {
976
1152
  * YAML no longer compiles, `CONFLICT` on a concurrent modification.
977
1153
  */
978
1154
  async rollback(id, rev) {
979
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/rollback`, {
980
- method: "POST",
981
- body: JSON.stringify({ rev }),
982
- headers: { "Content-Type": "application/json" }
983
- });
1155
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/rollback`, jsonInit("POST", { rev }));
984
1156
  }
985
1157
  /**
986
1158
  * Deterministic health stats over the workflow's last N terminal runs
@@ -1001,11 +1173,7 @@ var HubWorkflowsClient = class {
1001
1173
  * until an owner approves.
1002
1174
  */
1003
1175
  async propose(id, input) {
1004
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals`, {
1005
- method: "POST",
1006
- body: JSON.stringify(input),
1007
- headers: { "Content-Type": "application/json" }
1008
- });
1176
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals`, jsonInit("POST", input));
1009
1177
  }
1010
1178
  /**
1011
1179
  * Pending (proposed) and declined (rejected) revisions, newest first, with
@@ -1032,11 +1200,7 @@ var HubWorkflowsClient = class {
1032
1200
  * pending proposal.
1033
1201
  */
1034
1202
  async rejectProposal(id, rev, opts = {}) {
1035
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals/${encodeURIComponent(String(rev))}/reject`, {
1036
- method: "POST",
1037
- body: JSON.stringify(opts.reason !== void 0 ? { reason: opts.reason } : {}),
1038
- headers: { "Content-Type": "application/json" }
1039
- });
1203
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals/${encodeURIComponent(String(rev))}/reject`, jsonInit("POST", opts.reason !== void 0 ? { reason: opts.reason } : {}));
1040
1204
  }
1041
1205
  /**
1042
1206
  * Mint a fresh webhook hook token, retiring the current one immediately.
@@ -1112,29 +1276,24 @@ var HubWorkflowsClient = class {
1112
1276
  /**
1113
1277
  * Upsert a key; returns the entry with its NEW version (increments on every
1114
1278
  * write). Throws `HubSdkError(KV_VALUE_TOO_LARGE)` past the 64KiB value cap
1115
- * or `KV_KEY_LIMIT` past the per-workflow key cap.
1279
+ * or `KV_KEY_LIMIT` past the per-workflow key cap. `raw` is the caller's
1280
+ * value, stored and read back verbatim, so the client never gives it a shape.
1116
1281
  */
1117
- async putKv(id, key, value) {
1118
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}`, {
1119
- method: "PUT",
1120
- body: JSON.stringify({ value }),
1121
- headers: { "Content-Type": "application/json" }
1122
- });
1282
+ async putKv(id, key, raw) {
1283
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}`, jsonInit("PUT", { value: raw }));
1123
1284
  }
1124
1285
  /**
1125
1286
  * Compare-and-swap: the write lands only when the stored version still
1126
1287
  * equals `expectedVersion`; otherwise `HubSdkError(KV_VERSION_CONFLICT)`
1127
- * (409) — re-read and retry. Creation is {@link putKv}'s job.
1288
+ * (409) — re-read and retry. Creation is {@link putKv}'s job. `raw` is the
1289
+ * caller's value, stored and read back verbatim, so the client never gives it
1290
+ * a shape.
1128
1291
  */
1129
- async casKv(id, key, expectedVersion, value) {
1130
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}/cas`, {
1131
- method: "POST",
1132
- body: JSON.stringify({
1133
- expectedVersion,
1134
- value
1135
- }),
1136
- headers: { "Content-Type": "application/json" }
1137
- });
1292
+ async casKv(id, key, expectedVersion, raw) {
1293
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}/cas`, jsonInit("POST", {
1294
+ expectedVersion,
1295
+ value: raw
1296
+ }));
1138
1297
  }
1139
1298
  /** Delete a key; idempotent — `deleted` reports whether a row was removed. */
1140
1299
  async deleteKv(id, key) {
@@ -1154,11 +1313,7 @@ var HubWorkflowsClient = class {
1154
1313
  * (400); an unknown template id throws `NOT_FOUND`.
1155
1314
  */
1156
1315
  async instantiateTemplate(templateId, parameters) {
1157
- return this.request(`/v1/workflows/templates/${encodeURIComponent(templateId)}/instantiate`, {
1158
- method: "POST",
1159
- body: JSON.stringify(parameters ? { parameters } : {}),
1160
- headers: { "Content-Type": "application/json" }
1161
- });
1316
+ return this.request(`/v1/workflows/templates/${encodeURIComponent(templateId)}/instantiate`, jsonInit("POST", parameters ? { parameters } : {}));
1162
1317
  }
1163
1318
  /**
1164
1319
  * The caller's open decisions across all workflows — the always-available
@@ -1185,11 +1340,7 @@ var HubWorkflowsClient = class {
1185
1340
  * (409 — answered, timed out, or cancelled first).
1186
1341
  */
1187
1342
  async resolveRunDecision(id, runId, input) {
1188
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/runs/${encodeURIComponent(runId)}/decision/resolve`, {
1189
- method: "POST",
1190
- body: JSON.stringify(input),
1191
- headers: { "Content-Type": "application/json" }
1192
- });
1343
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/runs/${encodeURIComponent(runId)}/decision/resolve`, jsonInit("POST", input));
1193
1344
  }
1194
1345
  /**
1195
1346
  * Dry-run a YAML definition against the platform compiler without saving it.
@@ -1202,14 +1353,10 @@ var HubWorkflowsClient = class {
1202
1353
  * the unconnected providers is the point.
1203
1354
  */
1204
1355
  async validate(yaml, opts = {}) {
1205
- return this.request("/v1/workflows/validate", {
1206
- method: "POST",
1207
- body: JSON.stringify({
1208
- yaml,
1209
- ...opts.structural ? { structural: true } : {}
1210
- }),
1211
- headers: { "Content-Type": "application/json" }
1212
- });
1356
+ return this.request("/v1/workflows/validate", jsonInit("POST", {
1357
+ yaml,
1358
+ ...opts.structural ? { structural: true } : {}
1359
+ }));
1213
1360
  }
1214
1361
  async schema() {
1215
1362
  return this.request("/v1/workflows/schema", { method: "GET" });
@@ -1473,6 +1620,6 @@ function requestFailure(code, status, error, headers) {
1473
1620
  };
1474
1621
  }
1475
1622
  //#endregion
1476
- export { HUB_API_KEY_ENV_VAR, HUB_CAPABILITY_TOKEN_ENV_VAR, HUB_URL_ENV_VAR, HubApprovalsClient, HubAuditClient, HubChannelsClient, HubClient, HubConnectionsClient, HubEventDeliveryError, HubEventSubscriptionsClient, HubGithubAppClient, HubPermissionsClient, HubSdkError, HubTokensClient, HubToolsClient, HubWorkflowsClient, authenticateHubEventRequest, deriveHubEventCallbackSecret, parseHubEventDelivery, redactHubValue, resolveHubAuth, resolveHubBaseUrl, verifyHubEventSignature };
1623
+ export { HUB_API_KEY_ENV_VAR, HUB_CAPABILITY_TOKEN_ENV_VAR, HUB_URL_ENV_VAR, HubAllowancesClient, HubApprovalsClient, HubAppsClient, HubAuditClient, HubChannelsClient, HubClient, HubConnectionsClient, HubEventDeliveryError, HubEventSubscriptionsClient, HubGithubAppClient, HubInboundWebhooksClient, HubLinesClient, HubManagedNumbersClient, HubPermissionsClient, HubSdkError, HubTokensClient, HubToolsClient, HubWorkflowsClient, authenticateHubEventRequest, deriveHubEventCallbackSecret, parseHubEventDelivery, redactHubValue, resolveHubAuth, resolveHubBaseUrl, verifyHubEventSignature };
1477
1624
 
1478
1625
  //# sourceMappingURL=index.js.map