@asiyst/sdk 0.1.9 → 0.1.12

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.d.cts CHANGED
@@ -217,6 +217,7 @@ declare const Asiyst: {
217
217
  close(): void;
218
218
  getConfig(): ProjectConfig;
219
219
  getConnectionStatus(): "connected" | "disconnected" | "offline";
220
+ getVerificationStatus(): "connected" | "inactive" | "not_detected" | "error";
220
221
  avatar: {
221
222
  show(): void;
222
223
  hide(): void;
package/dist/index.d.ts CHANGED
@@ -217,6 +217,7 @@ declare const Asiyst: {
217
217
  close(): void;
218
218
  getConfig(): ProjectConfig;
219
219
  getConnectionStatus(): "connected" | "disconnected" | "offline";
220
+ getVerificationStatus(): "connected" | "inactive" | "not_detected" | "error";
220
221
  avatar: {
221
222
  show(): void;
222
223
  hide(): void;
package/dist/index.js CHANGED
@@ -69,7 +69,7 @@ var ALL_ACTION_KINDS = [
69
69
  ];
70
70
 
71
71
  // src/core/constants.ts
72
- var SDK_VERSION = "0.1.9" ;
72
+ var SDK_VERSION = "0.1.11" ;
73
73
  var DEFAULT_API_BASE_URL = "https://nqhxpgsjofzqudyqkqib.supabase.co/functions/v1/api";
74
74
  var CONFIG_SCHEMA_VERSION = 1;
75
75
  var HOST_ELEMENT_ID = "asiyst-host";
@@ -432,7 +432,8 @@ var HttpTransport = class {
432
432
  "X-Asiyst-Project-Id": this.options.projectId,
433
433
  "X-Asiyst-Public-Key": this.options.publicKey,
434
434
  ...this.options.avatarId ? { "X-Asiyst-Avatar-Id": this.options.avatarId } : {},
435
- "X-Asiyst-SDK-Version": SDK_VERSION
435
+ "X-Asiyst-SDK-Version": SDK_VERSION,
436
+ ...req.authorizationToken ? { Authorization: `Bearer ${req.authorizationToken}` } : {}
436
437
  },
437
438
  body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
438
439
  signal: req.signal
@@ -458,12 +459,14 @@ var HttpTransport = class {
458
459
 
459
460
  // src/communication/CloudClient.ts
460
461
  var CloudClient = class {
461
- constructor(transport, projectId) {
462
+ constructor(transport, projectId, publicKey = "", runtimeAuth) {
462
463
  this.transport = transport;
463
464
  this.projectId = projectId;
465
+ this.publicKey = publicKey;
466
+ this.runtimeAuth = runtimeAuth;
464
467
  }
465
468
  async fetchConfig() {
466
- const response = await this.transport.request({
469
+ const response = await this.runtimeRequest({
467
470
  path: `/projects/${encodeURIComponent(this.projectId)}/avatar`,
468
471
  method: "GET"
469
472
  });
@@ -476,21 +479,40 @@ var CloudClient = class {
476
479
  return normalizeProjectConfig(response.data.config ?? response.data);
477
480
  }
478
481
  async heartbeat(metadata) {
479
- const response = await this.transport.request({
482
+ const response = await this.runtimeRequest({
480
483
  path: "/sdk/heartbeat",
481
484
  method: "POST",
482
485
  body: {
483
- projectId: this.projectId,
484
- sdkVersion: SDK_VERSION,
485
- websiteOrigin: metadata.origin,
486
+ project_id: this.projectId,
487
+ public_key: this.publicKey,
488
+ sdk_version: SDK_VERSION,
489
+ origin: metadata.origin,
486
490
  environment: metadata.environment,
487
491
  timestamp: metadata.timestamp
488
492
  }
493
+ }, "assistant:heartbeat");
494
+ const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
495
+ const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus;
496
+ const verificationStatus = rawStatus === "connected" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
497
+ return {
498
+ ok: response.ok && (verificationStatus === void 0 || verificationStatus === "connected"),
499
+ status: response.status,
500
+ verificationStatus
501
+ };
502
+ }
503
+ async registerInstallation(registration) {
504
+ const response = await this.transport.request({
505
+ path: "/sdk/installations/register",
506
+ method: "POST",
507
+ body: registration
489
508
  });
490
- return { ok: response.ok, status: response.status };
509
+ if (!response.ok) {
510
+ throw new NetworkError(`SDK installation registration failed (${response.status}).`);
511
+ }
512
+ return response.data ?? {};
491
513
  }
492
514
  async requestTask(userText, pageUrl) {
493
- const response = await this.transport.request({
515
+ const response = await this.runtimeRequest({
494
516
  path: "/tasks",
495
517
  method: "POST",
496
518
  body: {
@@ -498,28 +520,28 @@ var CloudClient = class {
498
520
  text: userText,
499
521
  pageUrl
500
522
  }
501
- });
523
+ }, "assistant:conversation");
502
524
  if (!response.ok || !response.data?.task?.id || !Array.isArray(response.data.task.steps)) {
503
525
  throw new NetworkError("Task planning is unavailable");
504
526
  }
505
527
  return response.data.task;
506
528
  }
507
529
  async fetchWorkflow(workflowId) {
508
- const response = await this.transport.request({
530
+ const response = await this.runtimeRequest({
509
531
  path: `/workflows/${encodeURIComponent(workflowId)}`,
510
532
  method: "GET"
511
- });
533
+ }, "assistant:conversation");
512
534
  if (!response.ok || !response.data?.workflow?.id || !Array.isArray(response.data.workflow.steps)) {
513
535
  throw new NetworkError("Workflow is unavailable");
514
536
  }
515
537
  return response.data.workflow;
516
538
  }
517
539
  async sendConversationMessage(text, pageUrl) {
518
- const response = await this.transport.request({
540
+ const response = await this.runtimeRequest({
519
541
  path: "/conversations/messages",
520
542
  method: "POST",
521
543
  body: { projectId: this.projectId, text, pageUrl }
522
- });
544
+ }, "assistant:conversation");
523
545
  if (!response.ok || !response.data?.message?.text) {
524
546
  throw new NetworkError("Conversation service is unavailable");
525
547
  }
@@ -539,10 +561,23 @@ var CloudClient = class {
539
561
  }
540
562
  async safePost(path, body) {
541
563
  try {
542
- await this.transport.request({ path, method: "POST", body });
564
+ await this.runtimeRequest({ path, method: "POST", body }, "assistant:telemetry");
543
565
  } catch {
544
566
  }
545
567
  }
568
+ async runtimeRequest(request, capability = "assistant:config") {
569
+ if (!this.runtimeAuth) {
570
+ return this.transport.request(request);
571
+ }
572
+ let token = await this.runtimeAuth.getToken(capability);
573
+ let response = await this.transport.request({ ...request, authorizationToken: token });
574
+ if (response.status === 401) {
575
+ this.runtimeAuth.invalidate();
576
+ token = await this.runtimeAuth.getToken(capability);
577
+ response = await this.transport.request({ ...request, authorizationToken: token });
578
+ }
579
+ return response;
580
+ }
546
581
  };
547
582
 
548
583
  // src/storage/NamespacedStorage.ts
@@ -1760,7 +1795,14 @@ var AvatarController = class {
1760
1795
 
1761
1796
  // src/interaction/permissions.ts
1762
1797
  function normalizeHost(host) {
1763
- return host.replace(/^https?:\/\//i, "").replace(/\/$/, "").toLowerCase();
1798
+ const candidate = host.trim();
1799
+ try {
1800
+ const parsed = new URL(/^[a-z][a-z\d+\-.]*:\/\//i.test(candidate) ? candidate : `https://${candidate}`);
1801
+ return (parsed.hostname ?? "").replace(/^www\./i, "").toLowerCase();
1802
+ } catch {
1803
+ const fallbackHost = candidate.replace(/^https?:\/\//i, "").split("/", 1)[0] ?? "";
1804
+ return fallbackHost.replace(/^www\./i, "").replace(/:\d+$/, "").toLowerCase();
1805
+ }
1764
1806
  }
1765
1807
  function matchesRoutePattern(pathname, pattern) {
1766
1808
  const candidate = pathname;
@@ -2353,6 +2395,134 @@ function withIsolation(fn) {
2353
2395
  }
2354
2396
  }
2355
2397
 
2398
+ // src/installation/Installation.ts
2399
+ var INSTALLATION_KEY = "installation_id";
2400
+ var INSTALLATION_ID_PATTERN = /^inst_[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
2401
+ var memoryIds = /* @__PURE__ */ new Map();
2402
+ function randomInstallationId() {
2403
+ try {
2404
+ const cryptoApi = globalThis.crypto;
2405
+ if (typeof cryptoApi?.randomUUID === "function") {
2406
+ return `inst_${cryptoApi.randomUUID()}`;
2407
+ }
2408
+ if (typeof cryptoApi?.getRandomValues === "function") {
2409
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
2410
+ return `inst_${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`;
2411
+ }
2412
+ } catch {
2413
+ return void 0;
2414
+ }
2415
+ return void 0;
2416
+ }
2417
+ function loadOrCreateInstallationId(projectId) {
2418
+ const inMemory = memoryIds.get(projectId);
2419
+ if (inMemory) return inMemory;
2420
+ const storage = new NamespacedStorage(projectId, browserLocalStorage());
2421
+ const existing = storage.read(INSTALLATION_KEY)?.trim();
2422
+ if (existing && INSTALLATION_ID_PATTERN.test(existing)) {
2423
+ memoryIds.set(projectId, existing);
2424
+ return existing;
2425
+ }
2426
+ const installationId = randomInstallationId();
2427
+ if (!installationId) return void 0;
2428
+ memoryIds.set(projectId, installationId);
2429
+ storage.write(INSTALLATION_KEY, installationId);
2430
+ return installationId;
2431
+ }
2432
+
2433
+ // src/communication/RuntimeAuth.ts
2434
+ var RUNTIME_AUDIENCE = "asiyst-sdk-runtime";
2435
+ var RUNTIME_CAPABILITIES = [
2436
+ "assistant:config",
2437
+ "assistant:conversation",
2438
+ "assistant:telemetry",
2439
+ "assistant:heartbeat"
2440
+ ];
2441
+ var RuntimeAuth = class {
2442
+ constructor(options) {
2443
+ this.options = options;
2444
+ }
2445
+ async getToken(capability) {
2446
+ if (this.token && this.isUsable(this.token) && this.token.capabilities.has(capability)) {
2447
+ return this.token.value;
2448
+ }
2449
+ if (!this.requestInFlight) {
2450
+ this.requestInFlight = this.issueToken().finally(() => {
2451
+ this.requestInFlight = void 0;
2452
+ });
2453
+ }
2454
+ const token = await this.requestInFlight;
2455
+ if (!token.capabilities.has(capability)) {
2456
+ throw new AuthenticationError("ASIYST runtime authorization does not allow this operation.");
2457
+ }
2458
+ return token.value;
2459
+ }
2460
+ invalidate() {
2461
+ this.token = void 0;
2462
+ }
2463
+ isUsable(token) {
2464
+ return token.expiresAt - Date.now() > 3e4;
2465
+ }
2466
+ async issueToken() {
2467
+ const controller = new AbortController();
2468
+ const timeout = setTimeout(() => controller.abort(), 1e4);
2469
+ let response;
2470
+ try {
2471
+ response = await fetch(`${this.options.apiBaseUrl.replace(/\/$/, "")}/sdk/runtime/token`, {
2472
+ method: "POST",
2473
+ headers: {
2474
+ Accept: "application/json",
2475
+ "Content-Type": "application/json"
2476
+ },
2477
+ body: JSON.stringify({
2478
+ projectId: this.options.projectId,
2479
+ publicKey: this.options.publicKey,
2480
+ installationId: this.options.installationId,
2481
+ origin: this.options.origin,
2482
+ environment: this.options.environment,
2483
+ sdkVersion: SDK_VERSION,
2484
+ capabilities: [...RUNTIME_CAPABILITIES]
2485
+ }),
2486
+ signal: controller.signal
2487
+ });
2488
+ } catch {
2489
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
2490
+ } finally {
2491
+ clearTimeout(timeout);
2492
+ }
2493
+ let body;
2494
+ try {
2495
+ body = await response.json();
2496
+ } catch {
2497
+ body = void 0;
2498
+ }
2499
+ if (!response.ok) {
2500
+ if (response.status === 403) {
2501
+ throw new AuthenticationError("ASIYST runtime authorization was rejected.");
2502
+ }
2503
+ if (response.status === 429) {
2504
+ throw new NetworkError("ASIYST runtime authentication is rate limited.");
2505
+ }
2506
+ throw new NetworkError("ASIYST runtime authentication is unavailable.");
2507
+ }
2508
+ const data = body?.data;
2509
+ if (!data || body?.success !== true || typeof data.token !== "string" || data.token.length < 20 || data.tokenType !== "Bearer" || data.audience !== RUNTIME_AUDIENCE || typeof data.expiresIn !== "number" || !Number.isFinite(data.expiresIn) || data.expiresIn <= 0 || typeof data.expiresAt !== "string" || !Array.isArray(data.capabilities) || data.capabilities.some((capability) => !RUNTIME_CAPABILITIES.includes(capability))) {
2510
+ throw new AuthenticationError("ASIYST returned an invalid runtime authorization response.");
2511
+ }
2512
+ const expiresAt = Date.parse(data.expiresAt);
2513
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
2514
+ throw new AuthenticationError("ASIYST runtime authorization has expired.");
2515
+ }
2516
+ const token = {
2517
+ value: data.token,
2518
+ expiresAt,
2519
+ capabilities: new Set(data.capabilities)
2520
+ };
2521
+ this.token = token;
2522
+ return token;
2523
+ }
2524
+ };
2525
+
2356
2526
  // src/core/Runtime.ts
2357
2527
  var AsiystRuntime = class {
2358
2528
  constructor(options, doc, win) {
@@ -2361,18 +2531,30 @@ var AsiystRuntime = class {
2361
2531
  this.observer = new DomObserver(() => this.rescan());
2362
2532
  this.destroyed = false;
2363
2533
  this.connectionStatus = "disconnected";
2534
+ this.verificationStatus = "not_detected";
2364
2535
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
2365
2536
  if (!doc.body) {
2366
2537
  throw new InitializationError("document.body is not available");
2367
2538
  }
2368
2539
  this.options = options;
2540
+ this.installationId = loadOrCreateInstallationId(options.projectId);
2541
+ const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
2542
+ this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
2369
2543
  const transport = new HttpTransport({
2370
2544
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2371
2545
  projectId: options.projectId,
2372
2546
  publicKey: options.publicKey,
2373
2547
  avatarId: options.avatarId
2374
2548
  });
2375
- this.cloud = new CloudClient(transport, options.projectId);
2549
+ const runtimeAuth = this.installationId ? new RuntimeAuth({
2550
+ apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
2551
+ projectId: options.projectId,
2552
+ publicKey: options.publicKey,
2553
+ installationId: this.installationId,
2554
+ origin: win.location.origin,
2555
+ environment: this.environment
2556
+ }) : void 0;
2557
+ this.cloud = new CloudClient(transport, options.projectId, options.publicKey, runtimeAuth);
2376
2558
  this.config = new ConfigManager(options, this.cloud, this.events);
2377
2559
  this.analytics = new Analytics(options.projectId, this.cloud);
2378
2560
  this.host = new HostRoot(doc);
@@ -2430,6 +2612,7 @@ var AsiystRuntime = class {
2430
2612
  const domainCheck = validateWebsiteDomain(cfg, window.location.href);
2431
2613
  if (!domainCheck.allowed) {
2432
2614
  this.connectionStatus = "disconnected";
2615
+ this.verificationStatus = "not_detected";
2433
2616
  this.events.emit("asiyst:error", {
2434
2617
  code: "domain_not_authorized",
2435
2618
  message: "This website is not authorized for the current Asiyst project."
@@ -2438,21 +2621,27 @@ var AsiystRuntime = class {
2438
2621
  }
2439
2622
  this.avatar.applyConfig(cfg);
2440
2623
  this.avatar.show();
2624
+ await this.registerInstallation();
2441
2625
  try {
2442
2626
  const heartbeat = await this.cloud.heartbeat({
2443
2627
  origin: window.location.origin,
2444
- environment: this.options.apiBaseUrl ? "development" : "production",
2628
+ environment: this.environment,
2445
2629
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
2446
2630
  });
2447
2631
  this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
2632
+ this.verificationStatus = heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
2448
2633
  } catch {
2449
2634
  this.connectionStatus = "offline";
2635
+ this.verificationStatus = "error";
2450
2636
  }
2451
2637
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
2452
2638
  }
2453
2639
  getConnectionStatus() {
2454
2640
  return this.connectionStatus;
2455
2641
  }
2642
+ getVerificationStatus() {
2643
+ return this.verificationStatus;
2644
+ }
2456
2645
  getConfig() {
2457
2646
  return this.config.get();
2458
2647
  }
@@ -2508,6 +2697,38 @@ var AsiystRuntime = class {
2508
2697
  this.events.removeAll();
2509
2698
  await this.analytics.destroy();
2510
2699
  }
2700
+ async registerInstallation() {
2701
+ const origin = window.location.origin;
2702
+ const environment = this.environment;
2703
+ const installationId = this.installationId;
2704
+ if (!installationId) {
2705
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
2706
+ console.debug("[asiyst] SDK installation identity is unavailable; registration skipped.");
2707
+ }
2708
+ return;
2709
+ }
2710
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2711
+ try {
2712
+ await this.cloud.registerInstallation({
2713
+ project_id: this.options.projectId,
2714
+ public_key: this.options.publicKey,
2715
+ installation_id: installationId,
2716
+ origin,
2717
+ environment,
2718
+ sdk_version: SDK_VERSION
2719
+ });
2720
+ return;
2721
+ } catch (error) {
2722
+ if (attempt === 1) {
2723
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
2724
+ console.debug("[asiyst] SDK installation registration failed.", error);
2725
+ }
2726
+ return;
2727
+ }
2728
+ await new Promise((resolve) => setTimeout(resolve, 250));
2729
+ }
2730
+ }
2731
+ }
2511
2732
  rescan() {
2512
2733
  withIsolation(() => {
2513
2734
  const doc = this.host.host.ownerDocument;
@@ -2575,6 +2796,9 @@ var Asiyst = {
2575
2796
  getConnectionStatus() {
2576
2797
  return requireRuntime().getConnectionStatus();
2577
2798
  },
2799
+ getVerificationStatus() {
2800
+ return requireRuntime().getVerificationStatus();
2801
+ },
2578
2802
  avatar: {
2579
2803
  show() {
2580
2804
  withIsolation(() => requireRuntime().avatarApi().show());