@alva-ai/toolkit 0.8.0 → 0.9.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 CHANGED
@@ -22,7 +22,29 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  AlvaClient: () => AlvaClient,
24
24
  AlvaError: () => AlvaError,
25
- VERSION: () => VERSION
25
+ PBSV_UPDATE_MESSAGE: () => PBSV_UPDATE_MESSAGE,
26
+ UDF_CONSENT_REQUEST_MESSAGE: () => UDF_CONSENT_REQUEST_MESSAGE,
27
+ UDF_CONSENT_RESPONSE_MESSAGE: () => UDF_CONSENT_RESPONSE_MESSAGE,
28
+ UdfAuthRequiredError: () => UdfAuthRequiredError,
29
+ UdfConsentDeniedError: () => UdfConsentDeniedError,
30
+ UdfConsentRequiredError: () => UdfConsentRequiredError,
31
+ UdfConsentTimeoutError: () => UdfConsentTimeoutError,
32
+ UdfError: () => UdfError,
33
+ UdfExecutionError: () => UdfExecutionError,
34
+ UdfFunctionDisabledError: () => UdfFunctionDisabledError,
35
+ UdfFunctionNotFoundError: () => UdfFunctionNotFoundError,
36
+ UdfInsufficientCredits: () => UdfInsufficientCredits,
37
+ UdfPidMismatchError: () => UdfPidMismatchError,
38
+ UdfRateLimitedError: () => UdfRateLimitedError,
39
+ UdfTokenExpiredError: () => UdfTokenExpiredError,
40
+ UdfTokenInvalidError: () => UdfTokenInvalidError,
41
+ UdfTransportError: () => UdfTransportError,
42
+ VERSION: () => VERSION,
43
+ getViewerToken: () => getViewerToken,
44
+ installPlaybookRuntime: () => installPlaybookRuntime,
45
+ mapUdfErrorResponse: () => mapUdfErrorResponse,
46
+ playbookIdFromToken: () => playbookIdFromToken,
47
+ udf: () => udf
26
48
  });
27
49
  module.exports = __toCommonJS(src_exports);
28
50
 
@@ -175,7 +197,8 @@ var RunResource = class {
175
197
  code: params.code,
176
198
  entry_path: params.entry_path,
177
199
  working_dir: params.working_dir,
178
- args: params.args
200
+ args: params.args,
201
+ max_heap_size_mb: params.max_heap_size_mb
179
202
  }
180
203
  });
181
204
  }
@@ -348,6 +371,60 @@ var FeedResource = class {
348
371
  }
349
372
  };
350
373
 
374
+ // src/resources/playbooks.ts
375
+ var PlaybooksResource = class {
376
+ constructor(client) {
377
+ this.client = client;
378
+ }
379
+ client;
380
+ /**
381
+ * List trending / searchable playbooks. Auth is optional: when the client
382
+ * has an API key it is forwarded, otherwise this uses the public surface.
383
+ *
384
+ * The gateway returns a frontend-oriented preview payload; this SDK projects
385
+ * it into a smaller, agent-friendly shape.
386
+ */
387
+ async trending(params = {}) {
388
+ const query = {};
389
+ if (params.cursor) query.cursor = params.cursor;
390
+ if (params.current) query.current = params.current;
391
+ if (params.limit !== void 0) query.limit = params.limit;
392
+ if (params.dir) query.dir = params.dir;
393
+ if (params.sort) query.sort = params.sort;
394
+ if (params.keyword) query.keyword = params.keyword;
395
+ if (params.tags && params.tags.length > 0) {
396
+ query.tags = params.tags.join(",");
397
+ }
398
+ const raw = await this.client._request(
399
+ "GET",
400
+ "/api/v1/playbooks/trending",
401
+ { query }
402
+ );
403
+ return {
404
+ playbooks: (raw.playbooks ?? []).map(toAgentPlaybook),
405
+ has_next: raw.has_next ?? false
406
+ };
407
+ }
408
+ };
409
+ function toAgentPlaybook(raw) {
410
+ const username = raw.creator?.name ?? "";
411
+ const name = raw.name ?? "";
412
+ const ref = username && name ? `${username}/${name}` : name;
413
+ return {
414
+ id: raw.id === void 0 ? "" : String(raw.id),
415
+ ref,
416
+ username,
417
+ name,
418
+ display_name: raw.display_name ?? "",
419
+ description: raw.description ?? "",
420
+ tags: raw.tags ?? [],
421
+ follow_count: raw.follow_count ?? 0,
422
+ url_path: username && name ? `/${username}/playbooks/${name}` : "",
423
+ ...raw.readme ? { readme: raw.readme } : {},
424
+ cursor: raw.cursor ?? ""
425
+ };
426
+ }
427
+
351
428
  // src/resources/secrets.ts
352
429
  var SecretsResource = class {
353
430
  constructor(client) {
@@ -417,6 +494,26 @@ var SdkDocsResource = class {
417
494
 
418
495
  // src/resources/skillTiers.ts
419
496
  var SKILL_ENDPOINT_METADATA = [
497
+ {
498
+ skill: "arrays-data-api-crypto-futures-data",
499
+ file: "binance-perp-usdt-kline",
500
+ method: "GET",
501
+ path: "/api/v1/crypto/binance/perp/usdt/kline",
502
+ tier: "public",
503
+ required_subscription_tier: "free",
504
+ access: "free_and_pro",
505
+ pro_required: false
506
+ },
507
+ {
508
+ skill: "arrays-data-api-spot-market-price-and-volume",
509
+ file: "binance-spot-usdt-kline",
510
+ method: "GET",
511
+ path: "/api/v1/crypto/binance/spot/usdt/kline",
512
+ tier: "public",
513
+ required_subscription_tier: "free",
514
+ access: "free_and_pro",
515
+ pro_required: false
516
+ },
420
517
  {
421
518
  skill: "arrays-data-api-spot-market-price-and-volume",
422
519
  file: "crypto-detail",
@@ -448,10 +545,10 @@ var SKILL_ENDPOINT_METADATA = [
448
545
  pro_required: false
449
546
  },
450
547
  {
451
- skill: "arrays-data-api-spot-market-price-and-volume",
452
- file: "crypto-futures-ohlcv",
548
+ skill: "arrays-data-api-crypto-futures-data",
549
+ file: "hyperliquid-perp-usdc-kline",
453
550
  method: "GET",
454
- path: "/api/v1/crypto/futures/ohlcv",
551
+ path: "/api/v1/crypto/hyperliquid/perp/usdc/kline",
455
552
  tier: "public",
456
553
  required_subscription_tier: "free",
457
554
  access: "free_and_pro",
@@ -459,9 +556,9 @@ var SKILL_ENDPOINT_METADATA = [
459
556
  },
460
557
  {
461
558
  skill: "arrays-data-api-spot-market-price-and-volume",
462
- file: "crypto-kline",
559
+ file: "hyperliquid-spot-usdc-kline",
463
560
  method: "GET",
464
- path: "/api/v1/crypto/kline",
561
+ path: "/api/v1/crypto/hyperliquid/spot/usdc/kline",
465
562
  tier: "public",
466
563
  required_subscription_tier: "free",
467
564
  access: "free_and_pro",
@@ -507,16 +604,6 @@ var SKILL_ENDPOINT_METADATA = [
507
604
  access: "free_and_pro",
508
605
  pro_required: false
509
606
  },
510
- {
511
- skill: "arrays-data-api-spot-market-price-and-volume",
512
- file: "crypto-ohlcv",
513
- method: "GET",
514
- path: "/api/v1/crypto/ohlcv",
515
- tier: "public",
516
- required_subscription_tier: "free",
517
- access: "free_and_pro",
518
- pro_required: false
519
- },
520
607
  {
521
608
  skill: "arrays-data-api-crypto-futures-data",
522
609
  file: "open-interest",
@@ -1207,16 +1294,6 @@ var SKILL_ENDPOINT_METADATA = [
1207
1294
  access: "pro_only",
1208
1295
  pro_required: true
1209
1296
  },
1210
- {
1211
- skill: "arrays-data-api-equity-ownership-and-flow",
1212
- file: "senate-trade",
1213
- method: "GET",
1214
- path: "/api/v1/stocks/company/senate-trade",
1215
- tier: "alternative",
1216
- required_subscription_tier: "pro",
1217
- access: "pro_only",
1218
- pro_required: true
1219
- },
1220
1297
  {
1221
1298
  skill: "arrays-data-api-stock-metrics",
1222
1299
  file: "darkpool",
@@ -1456,6 +1533,50 @@ var SKILL_ENDPOINT_METADATA = [
1456
1533
  required_subscription_tier: "pro",
1457
1534
  access: "pro_only",
1458
1535
  pro_required: true
1536
+ },
1537
+ {
1538
+ // TODO(audit): verify tier — auto-defaulted to pro
1539
+ skill: "arrays-data-api-social-feeds",
1540
+ file: "x-by-handle",
1541
+ method: "GET",
1542
+ path: "/api/v1/social-feeds/x/by-handle",
1543
+ tier: "alternative",
1544
+ required_subscription_tier: "pro",
1545
+ access: "pro_only",
1546
+ pro_required: true
1547
+ },
1548
+ {
1549
+ // TODO(audit): verify tier — auto-defaulted to pro
1550
+ skill: "arrays-data-api-social-feeds",
1551
+ file: "x-by-url",
1552
+ method: "GET",
1553
+ path: "/api/v1/social-feeds/x/by-url",
1554
+ tier: "alternative",
1555
+ required_subscription_tier: "pro",
1556
+ access: "pro_only",
1557
+ pro_required: true
1558
+ },
1559
+ {
1560
+ // TODO(audit): verify tier — auto-defaulted to pro
1561
+ skill: "arrays-data-api-social-feeds",
1562
+ file: "x-entities-handle",
1563
+ method: "GET",
1564
+ path: "/api/v1/social-feeds/x/entities/handle/{twitter_handle}",
1565
+ tier: "alternative",
1566
+ required_subscription_tier: "pro",
1567
+ access: "pro_only",
1568
+ pro_required: true
1569
+ },
1570
+ {
1571
+ // TODO(audit): verify tier — auto-defaulted to pro
1572
+ skill: "arrays-data-api-social-feeds",
1573
+ file: "x-entities-handles",
1574
+ method: "GET",
1575
+ path: "/api/v1/social-feeds/x/entities/handles",
1576
+ tier: "alternative",
1577
+ required_subscription_tier: "pro",
1578
+ access: "pro_only",
1579
+ pro_required: true
1459
1580
  }
1460
1581
  ];
1461
1582
  function getSkillEndpointMetadata(skill, file) {
@@ -1850,6 +1971,38 @@ function buildQuery(params) {
1850
1971
  return q;
1851
1972
  }
1852
1973
 
1974
+ // src/resources/notificationPreferences.ts
1975
+ var NotificationPreferencesResource = class {
1976
+ constructor(client) {
1977
+ this.client = client;
1978
+ }
1979
+ client;
1980
+ /**
1981
+ * List the caller's notification preference settings. Server defaults
1982
+ * are included even when the caller has not explicitly stored a setting.
1983
+ */
1984
+ async list() {
1985
+ this.client._requireAuth();
1986
+ return this.client._request(
1987
+ "GET",
1988
+ "/api/v1/me/notifications/preferences"
1989
+ );
1990
+ }
1991
+ /**
1992
+ * Enable or disable one notification preference.
1993
+ */
1994
+ async update(params) {
1995
+ this.client._requireAuth();
1996
+ return this.client._request(
1997
+ "PATCH",
1998
+ `/api/v1/me/notifications/preferences/${encodeURIComponent(params.key)}`,
1999
+ {
2000
+ body: { enabled: params.enabled }
2001
+ }
2002
+ );
2003
+ }
2004
+ };
2005
+
1853
2006
  // src/resources/pushSubscriptions.ts
1854
2007
  var PushSubscriptionsResource = class {
1855
2008
  constructor(client) {
@@ -1995,12 +2148,17 @@ var AlvaClient = class {
1995
2148
  baseUrl;
1996
2149
  arraysBaseUrl;
1997
2150
  viewer_token;
2151
+ pbsvToken;
1998
2152
  apiKey;
2153
+ gaClientId;
2154
+ gaSessionId;
2155
+ utmParams;
1999
2156
  _fs;
2000
2157
  _run;
2001
2158
  _deploy;
2002
2159
  _release;
2003
2160
  _feed;
2161
+ _playbooks;
2004
2162
  _secrets;
2005
2163
  _sdk;
2006
2164
  _dataSkills;
@@ -2012,13 +2170,18 @@ var AlvaClient = class {
2012
2170
  _trading;
2013
2171
  _arraysJwt;
2014
2172
  _notifications;
2173
+ _notificationPreferences;
2015
2174
  _pushSubscriptions;
2016
2175
  _channelGroupSubscriptions;
2017
2176
  constructor(config) {
2018
2177
  this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
2019
2178
  this.arraysBaseUrl = config.arraysBaseUrl ?? DEFAULT_ARRAYS_BASE_URL;
2020
2179
  this.viewer_token = config.viewer_token;
2180
+ this.pbsvToken = config.pbsvToken;
2021
2181
  this.apiKey = config.apiKey;
2182
+ this.gaClientId = config.gaClientId;
2183
+ this.gaSessionId = config.gaSessionId;
2184
+ this.utmParams = config.utmParams;
2022
2185
  }
2023
2186
  get fs() {
2024
2187
  return this._fs ??= new FsResource(this);
@@ -2035,6 +2198,9 @@ var AlvaClient = class {
2035
2198
  get feed() {
2036
2199
  return this._feed ??= new FeedResource(this);
2037
2200
  }
2201
+ get playbooks() {
2202
+ return this._playbooks ??= new PlaybooksResource(this);
2203
+ }
2038
2204
  get secrets() {
2039
2205
  return this._secrets ??= new SecretsResource(this);
2040
2206
  }
@@ -2068,6 +2234,9 @@ var AlvaClient = class {
2068
2234
  get notifications() {
2069
2235
  return this._notifications ??= new NotificationsResource(this);
2070
2236
  }
2237
+ get notificationPreferences() {
2238
+ return this._notificationPreferences ??= new NotificationPreferencesResource(this);
2239
+ }
2071
2240
  get pushSubscriptions() {
2072
2241
  return this._pushSubscriptions ??= new PushSubscriptionsResource(this);
2073
2242
  }
@@ -2075,10 +2244,10 @@ var AlvaClient = class {
2075
2244
  return this._channelGroupSubscriptions ??= new ChannelGroupSubscriptionsResource(this);
2076
2245
  }
2077
2246
  _requireAuth() {
2078
- if (!this.viewer_token && !this.apiKey) {
2247
+ if (!this.pbsvToken && !this.viewer_token && !this.apiKey) {
2079
2248
  throw new AlvaError(
2080
2249
  "UNAUTHENTICATED",
2081
- "Authentication is required. Pass viewer_token or apiKey in the constructor.",
2250
+ "Authentication is required. Pass pbsvToken, viewer_token, or apiKey in the constructor.",
2082
2251
  401
2083
2252
  );
2084
2253
  }
@@ -2100,12 +2269,24 @@ var AlvaClient = class {
2100
2269
  }
2101
2270
  const headers = {};
2102
2271
  if (!options?.noAuth) {
2103
- if (this.viewer_token) {
2272
+ if (this.pbsvToken) {
2273
+ headers.Authorization = `Bearer ${this.pbsvToken}`;
2274
+ headers["X-Pbsv"] = "1";
2275
+ } else if (this.viewer_token) {
2104
2276
  headers["x-Playbook-Viewer"] = this.viewer_token;
2105
2277
  } else if (this.apiKey) {
2106
2278
  headers["X-Alva-Api-Key"] = this.apiKey;
2107
2279
  }
2108
2280
  }
2281
+ if (this.gaClientId) {
2282
+ headers["X-Alva-GA-Client-ID"] = this.gaClientId;
2283
+ }
2284
+ if (this.gaSessionId) {
2285
+ headers["X-Alva-GA-Session-ID"] = this.gaSessionId;
2286
+ }
2287
+ if (this.utmParams) {
2288
+ headers["X-Alva-UTM-Params"] = this.utmParams;
2289
+ }
2109
2290
  let fetchBody;
2110
2291
  if (options?.rawBody !== void 0) {
2111
2292
  headers["Content-Type"] = "application/octet-stream";
@@ -2165,12 +2346,381 @@ var AlvaClient = class {
2165
2346
  }
2166
2347
  };
2167
2348
 
2349
+ // src/playbookRuntime.ts
2350
+ var UdfError = class extends Error {
2351
+ code;
2352
+ metadata;
2353
+ status;
2354
+ constructor(message, {
2355
+ code,
2356
+ metadata = {},
2357
+ status
2358
+ }) {
2359
+ super(message);
2360
+ this.name = new.target.name;
2361
+ this.code = code;
2362
+ this.metadata = metadata;
2363
+ this.status = status;
2364
+ }
2365
+ };
2366
+ var UdfAuthRequiredError = class extends UdfError {
2367
+ constructor() {
2368
+ super("Sign in to use this UDF.", { code: "AUTH_REQUIRED" });
2369
+ }
2370
+ };
2371
+ var UdfTokenExpiredError = class extends UdfError {
2372
+ };
2373
+ var UdfTokenInvalidError = class extends UdfError {
2374
+ };
2375
+ var UdfPidMismatchError = class extends UdfError {
2376
+ };
2377
+ var UdfConsentRequiredError = class extends UdfError {
2378
+ };
2379
+ var UdfConsentDeniedError = class extends UdfError {
2380
+ constructor() {
2381
+ super("UDF consent was denied.", { code: "CONSENT_DENIED" });
2382
+ }
2383
+ };
2384
+ var UdfConsentTimeoutError = class extends UdfError {
2385
+ constructor() {
2386
+ super("UDF consent timed out.", { code: "CONSENT_TIMEOUT" });
2387
+ }
2388
+ };
2389
+ var UdfInsufficientCredits = class extends UdfError {
2390
+ };
2391
+ var UdfFunctionNotFoundError = class extends UdfError {
2392
+ };
2393
+ var UdfFunctionDisabledError = class extends UdfError {
2394
+ };
2395
+ var UdfRateLimitedError = class extends UdfError {
2396
+ };
2397
+ var UdfExecutionError = class extends UdfError {
2398
+ };
2399
+ var UdfTransportError = class extends UdfError {
2400
+ };
2401
+ var PBSV_UPDATE_MESSAGE = "alva:pbsv:update";
2402
+ var UDF_CONSENT_REQUEST_MESSAGE = "alva:udf:consent-request";
2403
+ var UDF_CONSENT_RESPONSE_MESSAGE = "alva:udf:consent-response";
2404
+ var DEFAULT_API_ORIGIN = "https://api.alva.ai";
2405
+ var CONSENT_TIMEOUT_MS = 5 * 60 * 1e3;
2406
+ var cachedToken = null;
2407
+ var expectedParentOrigin = null;
2408
+ var apiOrigin = DEFAULT_API_ORIGIN;
2409
+ var playbookIdFromBoot = null;
2410
+ var runtimeWindow = null;
2411
+ var installed = false;
2412
+ var pendingConsents = /* @__PURE__ */ new Map();
2413
+ var decodeBase64Url = (value) => {
2414
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
2415
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
2416
+ return atob(padded);
2417
+ };
2418
+ var playbookIdFromToken = (token) => {
2419
+ if (!token) return null;
2420
+ const [, payload] = token.split(".");
2421
+ if (!payload) return null;
2422
+ try {
2423
+ const parsed = JSON.parse(decodeBase64Url(payload));
2424
+ if (typeof parsed.pid === "number") return String(parsed.pid);
2425
+ if (typeof parsed.pid === "string") return parsed.pid;
2426
+ } catch {
2427
+ return null;
2428
+ }
2429
+ return null;
2430
+ };
2431
+ var getViewerToken = () => cachedToken;
2432
+ var stripPbsvFromUrl = (targetWindow) => {
2433
+ const url = new URL(targetWindow.location.href);
2434
+ url.searchParams.delete("_pbsv");
2435
+ targetWindow.history.replaceState(
2436
+ null,
2437
+ "",
2438
+ url.pathname + url.search + url.hash
2439
+ );
2440
+ };
2441
+ var parseBootParams = (targetWindow) => {
2442
+ const params = new URLSearchParams(targetWindow.location.search);
2443
+ cachedToken = params.get("_pbsv");
2444
+ expectedParentOrigin = params.get("parent_origin");
2445
+ apiOrigin = (params.get("api_origin") || DEFAULT_API_ORIGIN).replace(
2446
+ /\/$/,
2447
+ ""
2448
+ );
2449
+ playbookIdFromBoot = playbookIdFromToken(cachedToken);
2450
+ if (cachedToken) stripPbsvFromUrl(targetWindow);
2451
+ };
2452
+ var safeJson = async (response) => {
2453
+ try {
2454
+ return await response.json();
2455
+ } catch {
2456
+ return {};
2457
+ }
2458
+ };
2459
+ var errorMetadata = (body) => body.error?.metadata || body.details?.metadata || {};
2460
+ var mapUdfErrorResponse = (body, status) => {
2461
+ const code = body.error?.code || "TRANSPORT";
2462
+ const message = body.error?.message || code;
2463
+ const metadata = errorMetadata(body);
2464
+ const props = { code, metadata, status };
2465
+ switch (code) {
2466
+ case "PBSV_EXPIRED":
2467
+ return new UdfTokenExpiredError(message, props);
2468
+ case "PBSV_INVALID":
2469
+ case "UNAUTHENTICATED":
2470
+ return new UdfTokenInvalidError(message, props);
2471
+ case "PBSV_PID_MISMATCH":
2472
+ return new UdfPidMismatchError(message, props);
2473
+ case "CONSENT_REQUIRED":
2474
+ return new UdfConsentRequiredError(message, props);
2475
+ case "INSUFFICIENT_CREDITS":
2476
+ return new UdfInsufficientCredits(message, props);
2477
+ case "FUNCTION_NOT_FOUND":
2478
+ return new UdfFunctionNotFoundError(message, props);
2479
+ case "FUNCTION_DISABLED":
2480
+ return new UdfFunctionDisabledError(message, props);
2481
+ case "RESOURCE_EXHAUSTED":
2482
+ return new UdfRateLimitedError(message, props);
2483
+ case "EXECUTION_FAILED":
2484
+ return new UdfExecutionError(message, props);
2485
+ default:
2486
+ return new UdfTransportError(message, props);
2487
+ }
2488
+ };
2489
+ var onMessage = (event) => {
2490
+ if (!runtimeWindow || !expectedParentOrigin) return;
2491
+ if (event.origin !== expectedParentOrigin) return;
2492
+ if (event.source !== runtimeWindow.parent) return;
2493
+ if (!event.data || typeof event.data !== "object") return;
2494
+ const data = event.data;
2495
+ if (data.type === PBSV_UPDATE_MESSAGE) {
2496
+ if (typeof data.token === "string" && data.token.length > 0) {
2497
+ cachedToken = data.token;
2498
+ playbookIdFromBoot = playbookIdFromToken(data.token);
2499
+ }
2500
+ return;
2501
+ }
2502
+ if (data.type !== UDF_CONSENT_RESPONSE_MESSAGE) return;
2503
+ if (typeof data.request_id !== "string") return;
2504
+ const pending = pendingConsents.get(data.request_id);
2505
+ if (!pending) return;
2506
+ clearTimeout(pending.timer);
2507
+ pendingConsents.delete(data.request_id);
2508
+ pending.resolve(data.granted === true ? "granted" : "denied");
2509
+ };
2510
+ var randomRequestId = () => {
2511
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();
2512
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2513
+ };
2514
+ var playbookIdForInvoke = () => {
2515
+ if (!playbookIdFromBoot) return null;
2516
+ const numericId = Number(playbookIdFromBoot);
2517
+ return Number.isSafeInteger(numericId) ? numericId : null;
2518
+ };
2519
+ var requestConsent = async (playbookId, minAllowance) => {
2520
+ if (!runtimeWindow || !expectedParentOrigin) return "denied";
2521
+ const targetOrigin = expectedParentOrigin;
2522
+ const requestId = randomRequestId();
2523
+ return new Promise((resolve) => {
2524
+ const timer = setTimeout(() => {
2525
+ pendingConsents.delete(requestId);
2526
+ resolve("timeout");
2527
+ }, CONSENT_TIMEOUT_MS);
2528
+ pendingConsents.set(requestId, { resolve, timer });
2529
+ runtimeWindow?.parent.postMessage(
2530
+ {
2531
+ type: UDF_CONSENT_REQUEST_MESSAGE,
2532
+ request_id: requestId,
2533
+ playbook_id: playbookId,
2534
+ min_allowance: minAllowance
2535
+ },
2536
+ targetOrigin
2537
+ );
2538
+ });
2539
+ };
2540
+ var call = async (functionName, params, retried = false) => {
2541
+ const token = getViewerToken();
2542
+ if (!token) throw new UdfAuthRequiredError();
2543
+ if (!playbookIdFromBoot) {
2544
+ throw new UdfPidMismatchError("Missing playbook id.", {
2545
+ code: "PBSV_PID_MISMATCH"
2546
+ });
2547
+ }
2548
+ const playbookId = playbookIdForInvoke();
2549
+ if (!playbookId) {
2550
+ throw new UdfPidMismatchError("Invalid playbook id.", {
2551
+ code: "PBSV_PID_MISMATCH"
2552
+ });
2553
+ }
2554
+ let response;
2555
+ try {
2556
+ response = await fetch(`${apiOrigin}/api/v1/service/invoke`, {
2557
+ method: "POST",
2558
+ headers: {
2559
+ Authorization: `Bearer ${token}`,
2560
+ "X-Pbsv": "1",
2561
+ "Content-Type": "application/json"
2562
+ },
2563
+ body: JSON.stringify({
2564
+ playbook_id: playbookId,
2565
+ function_name: functionName,
2566
+ parameters_json: JSON.stringify(params)
2567
+ })
2568
+ });
2569
+ } catch {
2570
+ throw new UdfTransportError("Network error while invoking UDF.", {
2571
+ code: "TRANSPORT"
2572
+ });
2573
+ }
2574
+ const body = await safeJson(response);
2575
+ if (response.ok) {
2576
+ return body.result;
2577
+ }
2578
+ if (body.error?.code === "CONSENT_REQUIRED" && !retried) {
2579
+ const metadata = errorMetadata(body);
2580
+ const playbookId2 = typeof metadata.playbook_id === "string" ? metadata.playbook_id : playbookIdFromBoot;
2581
+ const minAllowance = typeof metadata.min_allowance_suggested === "number" ? metadata.min_allowance_suggested : 1;
2582
+ const consent = await requestConsent(playbookId2, minAllowance);
2583
+ if (consent === "granted") return call(functionName, params, true);
2584
+ if (consent === "timeout") throw new UdfConsentTimeoutError();
2585
+ throw new UdfConsentDeniedError();
2586
+ }
2587
+ throw mapUdfErrorResponse(body, response.status);
2588
+ };
2589
+ var list = async () => {
2590
+ const token = getViewerToken();
2591
+ if (!token) throw new UdfAuthRequiredError();
2592
+ if (!playbookIdFromBoot) {
2593
+ throw new UdfPidMismatchError("Missing playbook id.", {
2594
+ code: "PBSV_PID_MISMATCH"
2595
+ });
2596
+ }
2597
+ const url = new URL(`${apiOrigin}/api/v1/service/functions`);
2598
+ url.searchParams.set("playbook_id", playbookIdFromBoot);
2599
+ const response = await fetch(url.toString(), {
2600
+ headers: {
2601
+ Authorization: `Bearer ${token}`,
2602
+ "X-Pbsv": "1"
2603
+ }
2604
+ });
2605
+ const body = await safeJson(response);
2606
+ if (!response.ok) throw mapUdfErrorResponse(body, response.status);
2607
+ const functions = body.functions;
2608
+ return Array.isArray(functions) ? functions : [];
2609
+ };
2610
+ var dispatchButtonEvent = (button, name, detail) => {
2611
+ button.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }));
2612
+ };
2613
+ var resolveButtonTarget = (target) => {
2614
+ if (typeof target !== "string") return target;
2615
+ const root = runtimeWindow?.document;
2616
+ const element = root?.querySelector(target);
2617
+ if (element && "appendChild" in element) {
2618
+ return element;
2619
+ }
2620
+ throw new Error(`UDF button target not found: ${target}`);
2621
+ };
2622
+ var renderButton = (target, options) => {
2623
+ if (!runtimeWindow) throw new Error("Playbook runtime is not installed.");
2624
+ const container = resolveButtonTarget(target);
2625
+ const button = runtimeWindow.document.createElement("button");
2626
+ const label = options.label || options.functionName;
2627
+ const loadingLabel = options.loadingLabel || "Running...";
2628
+ const disabledLabel = options.disabledLabel || "Sign in to run";
2629
+ button.type = "button";
2630
+ button.className = "alva-udf-button";
2631
+ button.textContent = getViewerToken() ? label : disabledLabel;
2632
+ button.disabled = !getViewerToken();
2633
+ button.setAttribute("data-function-name", options.functionName);
2634
+ if (button.disabled) button.setAttribute("aria-disabled", "true");
2635
+ button.addEventListener("click", async () => {
2636
+ if (button.disabled) return;
2637
+ button.disabled = true;
2638
+ button.textContent = loadingLabel;
2639
+ dispatchButtonEvent(button, "alva:udf-button:loading", {
2640
+ functionName: options.functionName
2641
+ });
2642
+ try {
2643
+ const result = await call(options.functionName, options.params ?? {});
2644
+ dispatchButtonEvent(button, "alva:udf-button:result", {
2645
+ functionName: options.functionName,
2646
+ result
2647
+ });
2648
+ } catch (error) {
2649
+ dispatchButtonEvent(button, "alva:udf-button:error", {
2650
+ functionName: options.functionName,
2651
+ error
2652
+ });
2653
+ } finally {
2654
+ button.disabled = !getViewerToken();
2655
+ button.textContent = button.disabled ? disabledLabel : label;
2656
+ }
2657
+ });
2658
+ container.appendChild(button);
2659
+ return button;
2660
+ };
2661
+ var udf = {
2662
+ call,
2663
+ list,
2664
+ getViewerToken,
2665
+ renderButton,
2666
+ UdfError,
2667
+ UdfAuthRequiredError,
2668
+ UdfTokenExpiredError,
2669
+ UdfTokenInvalidError,
2670
+ UdfPidMismatchError,
2671
+ UdfConsentRequiredError,
2672
+ UdfConsentDeniedError,
2673
+ UdfConsentTimeoutError,
2674
+ UdfInsufficientCredits,
2675
+ UdfFunctionNotFoundError,
2676
+ UdfFunctionDisabledError,
2677
+ UdfRateLimitedError,
2678
+ UdfExecutionError,
2679
+ UdfTransportError
2680
+ };
2681
+ var installPlaybookRuntime = (targetWindow) => {
2682
+ const nextWindow = targetWindow ?? (typeof window === "undefined" ? void 0 : window);
2683
+ if (!nextWindow || installed) return;
2684
+ runtimeWindow = nextWindow;
2685
+ installed = true;
2686
+ parseBootParams(nextWindow);
2687
+ nextWindow.addEventListener("message", onMessage);
2688
+ const target = nextWindow;
2689
+ const existing = target.alva || {};
2690
+ target.alva = {
2691
+ ...existing,
2692
+ udf
2693
+ };
2694
+ };
2695
+
2168
2696
  // src/index.ts
2169
- var VERSION = true ? "0.8.0" : "dev";
2697
+ var VERSION = true ? "0.9.0" : "dev";
2170
2698
  // Annotate the CommonJS export names for ESM import in node:
2171
2699
  0 && (module.exports = {
2172
2700
  AlvaClient,
2173
2701
  AlvaError,
2174
- VERSION
2702
+ PBSV_UPDATE_MESSAGE,
2703
+ UDF_CONSENT_REQUEST_MESSAGE,
2704
+ UDF_CONSENT_RESPONSE_MESSAGE,
2705
+ UdfAuthRequiredError,
2706
+ UdfConsentDeniedError,
2707
+ UdfConsentRequiredError,
2708
+ UdfConsentTimeoutError,
2709
+ UdfError,
2710
+ UdfExecutionError,
2711
+ UdfFunctionDisabledError,
2712
+ UdfFunctionNotFoundError,
2713
+ UdfInsufficientCredits,
2714
+ UdfPidMismatchError,
2715
+ UdfRateLimitedError,
2716
+ UdfTokenExpiredError,
2717
+ UdfTokenInvalidError,
2718
+ UdfTransportError,
2719
+ VERSION,
2720
+ getViewerToken,
2721
+ installPlaybookRuntime,
2722
+ mapUdfErrorResponse,
2723
+ playbookIdFromToken,
2724
+ udf
2175
2725
  });
2176
2726
  //# sourceMappingURL=index.cjs.map