@asiyst/sdk 0.1.22 → 0.1.23

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
@@ -82,6 +82,17 @@ interface AsiystEventMap {
82
82
  "asiyst:conversation:closed": {
83
83
  conversationId: string;
84
84
  };
85
+ "asiyst:runtime:connected": {
86
+ projectId: string;
87
+ status: "connected" | "verified";
88
+ environment?: string;
89
+ origin?: string;
90
+ };
91
+ "asiyst:runtime:disconnected": {
92
+ projectId: string;
93
+ reason: string;
94
+ status?: string;
95
+ };
85
96
  "asiyst:error": {
86
97
  code: string;
87
98
  message: string;
@@ -107,6 +118,7 @@ interface InitOptions {
107
118
  avatarId?: string;
108
119
  position?: AnchorPosition;
109
120
  apiBaseUrl?: string;
121
+ environment?: "production" | "development" | "preview";
110
122
  mode?: AssistantMode;
111
123
  allowedActions?: ActionKind[];
112
124
  observeHistory?: boolean;
@@ -259,6 +271,7 @@ declare const Asiyst: {
259
271
  getConfig(): ProjectConfig;
260
272
  getConnectionStatus(): "connected" | "disconnected" | "offline";
261
273
  getVerificationStatus(): "connected" | "inactive" | "not_detected" | "error";
274
+ isRuntimeConnected(): boolean;
262
275
  avatar: {
263
276
  show(): void;
264
277
  hide(): void;
package/dist/index.d.ts CHANGED
@@ -82,6 +82,17 @@ interface AsiystEventMap {
82
82
  "asiyst:conversation:closed": {
83
83
  conversationId: string;
84
84
  };
85
+ "asiyst:runtime:connected": {
86
+ projectId: string;
87
+ status: "connected" | "verified";
88
+ environment?: string;
89
+ origin?: string;
90
+ };
91
+ "asiyst:runtime:disconnected": {
92
+ projectId: string;
93
+ reason: string;
94
+ status?: string;
95
+ };
85
96
  "asiyst:error": {
86
97
  code: string;
87
98
  message: string;
@@ -107,6 +118,7 @@ interface InitOptions {
107
118
  avatarId?: string;
108
119
  position?: AnchorPosition;
109
120
  apiBaseUrl?: string;
121
+ environment?: "production" | "development" | "preview";
110
122
  mode?: AssistantMode;
111
123
  allowedActions?: ActionKind[];
112
124
  observeHistory?: boolean;
@@ -259,6 +271,7 @@ declare const Asiyst: {
259
271
  getConfig(): ProjectConfig;
260
272
  getConnectionStatus(): "connected" | "disconnected" | "offline";
261
273
  getVerificationStatus(): "connected" | "inactive" | "not_detected" | "error";
274
+ isRuntimeConnected(): boolean;
262
275
  avatar: {
263
276
  show(): void;
264
277
  hide(): void;
package/dist/index.js CHANGED
@@ -75,7 +75,7 @@ var ALL_ACTION_KINDS = [
75
75
  // src/core/constants.ts
76
76
  function resolveSdkVersion() {
77
77
  {
78
- return "0.1.21";
78
+ return "0.1.22";
79
79
  }
80
80
  }
81
81
  var SDK_VERSION = resolveSdkVersion();
@@ -93,6 +93,7 @@ var AVATAR_VIEWPORT_PADDING = 12;
93
93
  var AVATAR_TARGET_GAP = 16;
94
94
  var WEBSITE_MAP_TEXT_LIMIT = 80;
95
95
  var CONFIG_CACHE_TTL_MS = 1e3 * 60 * 10;
96
+ var HEARTBEAT_INTERVAL_MS = 45e3;
96
97
 
97
98
  // src/security/selectors.ts
98
99
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -135,11 +136,12 @@ var ANCHORS = [
135
136
  "top-left"
136
137
  ];
137
138
  var PUBLIC_IDENTIFIER_PATTERN = /^(?=.{1,128}$)[A-Za-z0-9_][A-Za-z0-9_-]*$/;
139
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
138
140
  function isValidPublicIdentifier(value) {
139
141
  if (typeof value !== "string") return false;
140
142
  const trimmed = value.trim();
141
143
  if (!trimmed || trimmed.length > 128) return false;
142
- if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(trimmed)) {
144
+ if (UUID_PATTERN.test(trimmed)) {
143
145
  return false;
144
146
  }
145
147
  return PUBLIC_IDENTIFIER_PATTERN.test(trimmed);
@@ -754,7 +756,7 @@ var CloudClient = class {
754
756
  throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
755
757
  }
756
758
  async heartbeat(metadata) {
757
- const response = await this.runtimeRequest({
759
+ let response = await this.runtimeRequest({
758
760
  path: "/sdk/heartbeat",
759
761
  method: "POST",
760
762
  idempotent: true,
@@ -767,6 +769,21 @@ var CloudClient = class {
767
769
  timestamp: metadata.timestamp
768
770
  }
769
771
  }, "assistant:heartbeat");
772
+ if (response.status === 404) {
773
+ response = await this.runtimeRequest({
774
+ path: "/api/v1/sdk/heartbeat",
775
+ method: "POST",
776
+ idempotent: true,
777
+ body: {
778
+ project_id: this.projectId,
779
+ public_key: this.publicKey,
780
+ sdk_version: SDK_VERSION,
781
+ origin: metadata.origin,
782
+ environment: metadata.environment,
783
+ timestamp: metadata.timestamp
784
+ }
785
+ }, "assistant:heartbeat");
786
+ }
770
787
  const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
771
788
  const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
772
789
  const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
@@ -779,13 +796,22 @@ var CloudClient = class {
779
796
  };
780
797
  }
781
798
  async registerInstallation(registration) {
782
- const response = await this.transport.request({
799
+ let response = await this.transport.request({
783
800
  path: "/sdk/installations/register",
784
801
  method: "POST",
785
802
  body: registration,
786
803
  idempotent: true,
787
804
  sessionId: this.sessionId
788
805
  });
806
+ if (response.status === 404) {
807
+ response = await this.transport.request({
808
+ path: "/api/v1/sdk/installations/register",
809
+ method: "POST",
810
+ body: registration,
811
+ idempotent: true,
812
+ sessionId: this.sessionId
813
+ });
814
+ }
789
815
  if (!response.ok) {
790
816
  throw new NetworkError(`SDK installation registration failed (${response.status}).`);
791
817
  }
@@ -3014,6 +3040,9 @@ function isLikelyJavaScriptUrl(value) {
3014
3040
  const lower = value.trim().toLowerCase();
3015
3041
  return lower.startsWith("javascript:") || lower.startsWith("data:") || lower.startsWith("vbscript:") || lower.includes("eval(") || lower.includes("new function") || lower.includes("document.cookie");
3016
3042
  }
3043
+ function isLocalHost(host) {
3044
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
3045
+ }
3017
3046
  function validateWebsiteDomain(config, currentUrl) {
3018
3047
  const allowedDomains = config.allowedDomains.map((domain) => normalizeHost(domain));
3019
3048
  if (allowedDomains.length === 0) {
@@ -3022,7 +3051,16 @@ function validateWebsiteDomain(config, currentUrl) {
3022
3051
  try {
3023
3052
  const parsed = new URL(currentUrl);
3024
3053
  const host = normalizeHost(parsed.host);
3025
- const allowed = allowedDomains.some((domain) => host === domain || host.endsWith(`.${domain}`));
3054
+ const hostIsLocal = isLocalHost(host);
3055
+ const allowed = allowedDomains.some((domain) => {
3056
+ if (host === domain || host.endsWith(`.${domain}`)) {
3057
+ return true;
3058
+ }
3059
+ if (hostIsLocal && isLocalHost(domain)) {
3060
+ return true;
3061
+ }
3062
+ return false;
3063
+ });
3026
3064
  if (!allowed) {
3027
3065
  return { allowed: false, reason: "DOMAIN_NOT_AUTHORIZED" };
3028
3066
  }
@@ -3674,23 +3712,36 @@ var RuntimeAuth = class {
3674
3712
  const timeout = setTimeout(() => controller.abort(), 1e4);
3675
3713
  let response;
3676
3714
  try {
3677
- response = await fetch(`${this.options.apiBaseUrl.replace(/\/$/, "")}/sdk/runtime/token`, {
3715
+ const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
3716
+ const payload = JSON.stringify({
3717
+ projectId: this.options.projectId,
3718
+ publicKey: this.options.publicKey,
3719
+ installationId: this.options.installationId,
3720
+ origin: this.options.origin,
3721
+ environment: this.options.environment,
3722
+ sdkVersion: SDK_VERSION,
3723
+ capabilities: [...RUNTIME_CAPABILITIES]
3724
+ });
3725
+ response = await fetch(`${baseUrl}/sdk/runtime/token`, {
3678
3726
  method: "POST",
3679
3727
  headers: {
3680
3728
  Accept: "application/json",
3681
3729
  "Content-Type": "application/json"
3682
3730
  },
3683
- body: JSON.stringify({
3684
- projectId: this.options.projectId,
3685
- publicKey: this.options.publicKey,
3686
- installationId: this.options.installationId,
3687
- origin: this.options.origin,
3688
- environment: this.options.environment,
3689
- sdkVersion: SDK_VERSION,
3690
- capabilities: [...RUNTIME_CAPABILITIES]
3691
- }),
3731
+ body: payload,
3692
3732
  signal: controller.signal
3693
3733
  });
3734
+ if (response.status === 404) {
3735
+ response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
3736
+ method: "POST",
3737
+ headers: {
3738
+ Accept: "application/json",
3739
+ "Content-Type": "application/json"
3740
+ },
3741
+ body: payload,
3742
+ signal: controller.signal
3743
+ });
3744
+ }
3694
3745
  } catch {
3695
3746
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
3696
3747
  } finally {
@@ -3837,6 +3888,9 @@ var AsiystRuntime = class {
3837
3888
  this.connectionStatus = "disconnected";
3838
3889
  this.verificationStatus = "not_detected";
3839
3890
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
3891
+ this.isHeartbeatInFlight = false;
3892
+ this.lastHeartbeatTime = 0;
3893
+ this.registrationSucceeded = false;
3840
3894
  if (!doc.body) {
3841
3895
  throw new InitializationError("document.body is not available");
3842
3896
  }
@@ -3844,7 +3898,7 @@ var AsiystRuntime = class {
3844
3898
  this.installationId = loadOrCreateInstallationId(options.projectId);
3845
3899
  this.visitorSessionId = options.visitorSessionId || `vsess_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
3846
3900
  const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
3847
- this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
3901
+ this.environment = options.environment || (isLocalOrigin ? "development" : "production");
3848
3902
  const transport = new HttpTransport({
3849
3903
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
3850
3904
  projectId: options.projectId,
@@ -3941,82 +3995,9 @@ var AsiystRuntime = class {
3941
3995
  sdkVersion: SDK_VERSION
3942
3996
  });
3943
3997
  await this.registerInstallation();
3944
- const previousConnection = this.connectionStatus === "connected";
3945
- try {
3946
- const heartbeat = await this.cloud.heartbeat({
3947
- origin: window.location.origin,
3948
- environment: this.environment,
3949
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
3950
- });
3951
- this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
3952
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
3953
- if (heartbeat.ok) {
3954
- this.lifecycle.emit("sdk.connected", {
3955
- projectId: this.options.projectId,
3956
- origin: window.location.origin,
3957
- environment: this.environment,
3958
- installationId: this.installationId,
3959
- sdkVersion: SDK_VERSION
3960
- });
3961
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
3962
- this.lifecycle.emit("sdk.verified", {
3963
- projectId: this.options.projectId,
3964
- origin: window.location.origin,
3965
- environment: this.environment,
3966
- installationId: this.installationId,
3967
- sdkVersion: SDK_VERSION
3968
- });
3969
- }
3970
- if (heartbeat.versionOutdated) {
3971
- this.lifecycle.emit("sdk.version_outdated", {
3972
- projectId: this.options.projectId,
3973
- origin: window.location.origin,
3974
- environment: this.environment,
3975
- installationId: this.installationId,
3976
- sdkVersion: SDK_VERSION
3977
- });
3978
- }
3979
- } else {
3980
- const reason = heartbeat.verificationStatus ?? "unverified";
3981
- this.lifecycle.emit("sdk.verification_failed", {
3982
- projectId: this.options.projectId,
3983
- origin: window.location.origin,
3984
- environment: this.environment,
3985
- status: reason,
3986
- reason: "heartbeat_failed"
3987
- });
3988
- if (previousConnection) {
3989
- this.lifecycle.emit("sdk.disconnected", {
3990
- projectId: this.options.projectId,
3991
- origin: window.location.origin,
3992
- environment: this.environment,
3993
- installationId: this.installationId,
3994
- reason: "heartbeat_failed",
3995
- status: reason
3996
- });
3997
- }
3998
- }
3999
- } catch (error) {
4000
- this.connectionStatus = "offline";
4001
- this.verificationStatus = "error";
4002
- this.lifecycle.emit("sdk.verification_failed", {
4003
- projectId: this.options.projectId,
4004
- origin: window.location.origin,
4005
- environment: this.environment,
4006
- installationId: this.installationId,
4007
- reason: "heartbeat_failed",
4008
- category: error instanceof AuthenticationError ? "authorization" : "network"
4009
- });
4010
- if (previousConnection) {
4011
- this.lifecycle.emit("sdk.disconnected", {
4012
- projectId: this.options.projectId,
4013
- origin: window.location.origin,
4014
- environment: this.environment,
4015
- reason: "heartbeat_failed",
4016
- category: "network"
4017
- });
4018
- }
4019
- }
3998
+ await this.sendHeartbeat();
3999
+ const doc = this.host.host.ownerDocument;
4000
+ this.startHeartbeatScheduler(doc);
4020
4001
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4021
4002
  void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4022
4003
  avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
@@ -4141,6 +4122,16 @@ var AsiystRuntime = class {
4141
4122
  return;
4142
4123
  }
4143
4124
  this.destroyed = true;
4125
+ if (this.heartbeatTimer) {
4126
+ clearInterval(this.heartbeatTimer);
4127
+ this.heartbeatTimer = void 0;
4128
+ }
4129
+ const doc = this.host.host.ownerDocument;
4130
+ if (doc && this.visibilityListener) {
4131
+ doc.removeEventListener("visibilitychange", this.visibilityListener);
4132
+ this.visibilityListener = void 0;
4133
+ }
4134
+ this.isHeartbeatInFlight = false;
4144
4135
  if (this.pagehideListener) {
4145
4136
  win.removeEventListener("pagehide", this.pagehideListener);
4146
4137
  }
@@ -4160,6 +4151,135 @@ var AsiystRuntime = class {
4160
4151
  this.events.removeAll();
4161
4152
  await this.analytics.destroy();
4162
4153
  }
4154
+ startHeartbeatScheduler(doc) {
4155
+ if (this.heartbeatTimer) {
4156
+ clearInterval(this.heartbeatTimer);
4157
+ }
4158
+ this.heartbeatTimer = setInterval(() => {
4159
+ if (!this.destroyed) {
4160
+ void this.sendHeartbeat(true);
4161
+ }
4162
+ }, HEARTBEAT_INTERVAL_MS);
4163
+ if (doc && typeof doc.addEventListener === "function") {
4164
+ this.visibilityListener = () => {
4165
+ if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
4166
+ void this.sendHeartbeat(true);
4167
+ }
4168
+ };
4169
+ doc.addEventListener("visibilitychange", this.visibilityListener);
4170
+ }
4171
+ }
4172
+ async sendHeartbeat(_isPeriodic = false) {
4173
+ if (this.destroyed || this.isHeartbeatInFlight) {
4174
+ return false;
4175
+ }
4176
+ this.isHeartbeatInFlight = true;
4177
+ const previousConnection = this.connectionStatus === "connected";
4178
+ const origin = window.location.origin;
4179
+ const environment = this.environment;
4180
+ const installationId = this.installationId;
4181
+ try {
4182
+ if (!this.registrationSucceeded && installationId) {
4183
+ await this.registerInstallation();
4184
+ }
4185
+ const heartbeat = await this.cloud.heartbeat({
4186
+ origin,
4187
+ environment,
4188
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4189
+ });
4190
+ this.lastHeartbeatTime = Date.now();
4191
+ this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
4192
+ this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
4193
+ if (heartbeat.ok) {
4194
+ if (!previousConnection) {
4195
+ this.events.emit("asiyst:runtime:connected", {
4196
+ projectId: this.options.projectId,
4197
+ status: "connected",
4198
+ environment,
4199
+ origin
4200
+ });
4201
+ this.lifecycle.emit("sdk.connected", {
4202
+ projectId: this.options.projectId,
4203
+ origin,
4204
+ environment,
4205
+ installationId,
4206
+ sdkVersion: SDK_VERSION
4207
+ });
4208
+ }
4209
+ if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
4210
+ this.lifecycle.emit("sdk.verified", {
4211
+ projectId: this.options.projectId,
4212
+ origin,
4213
+ environment,
4214
+ installationId,
4215
+ sdkVersion: SDK_VERSION
4216
+ });
4217
+ }
4218
+ if (heartbeat.versionOutdated) {
4219
+ this.lifecycle.emit("sdk.version_outdated", {
4220
+ projectId: this.options.projectId,
4221
+ origin,
4222
+ environment,
4223
+ installationId,
4224
+ sdkVersion: SDK_VERSION
4225
+ });
4226
+ }
4227
+ return true;
4228
+ } else {
4229
+ const reason = heartbeat.verificationStatus ?? "unverified";
4230
+ this.lifecycle.emit("sdk.verification_failed", {
4231
+ projectId: this.options.projectId,
4232
+ origin,
4233
+ environment,
4234
+ status: reason,
4235
+ reason: "heartbeat_failed"
4236
+ });
4237
+ if (previousConnection) {
4238
+ this.events.emit("asiyst:runtime:disconnected", {
4239
+ projectId: this.options.projectId,
4240
+ reason: "heartbeat_failed"
4241
+ });
4242
+ this.lifecycle.emit("sdk.disconnected", {
4243
+ projectId: this.options.projectId,
4244
+ origin,
4245
+ environment,
4246
+ installationId,
4247
+ reason: "heartbeat_failed",
4248
+ status: reason
4249
+ });
4250
+ }
4251
+ return false;
4252
+ }
4253
+ } catch (error) {
4254
+ this.connectionStatus = "offline";
4255
+ this.verificationStatus = "error";
4256
+ this.lifecycle.emit("sdk.verification_failed", {
4257
+ projectId: this.options.projectId,
4258
+ origin,
4259
+ environment,
4260
+ installationId,
4261
+ reason: "heartbeat_failed",
4262
+ category: error instanceof AuthenticationError ? "authorization" : "network"
4263
+ });
4264
+ if (previousConnection) {
4265
+ this.events.emit("asiyst:runtime:disconnected", {
4266
+ projectId: this.options.projectId,
4267
+ reason: "heartbeat_failed"
4268
+ });
4269
+ this.lifecycle.emit("sdk.disconnected", {
4270
+ projectId: this.options.projectId,
4271
+ origin,
4272
+ environment,
4273
+ installationId,
4274
+ reason: "heartbeat_failed",
4275
+ category: "network"
4276
+ });
4277
+ }
4278
+ return false;
4279
+ } finally {
4280
+ this.isHeartbeatInFlight = false;
4281
+ }
4282
+ }
4163
4283
  async registerInstallation() {
4164
4284
  const origin = window.location.origin;
4165
4285
  const environment = this.environment;
@@ -4181,6 +4301,7 @@ var AsiystRuntime = class {
4181
4301
  environment,
4182
4302
  sdk_version: SDK_VERSION
4183
4303
  });
4304
+ this.registrationSucceeded = true;
4184
4305
  return;
4185
4306
  } catch (error) {
4186
4307
  lastError = error;
@@ -4280,6 +4401,9 @@ var Asiyst = {
4280
4401
  getVerificationStatus() {
4281
4402
  return requireRuntime().getVerificationStatus();
4282
4403
  },
4404
+ isRuntimeConnected() {
4405
+ return requireRuntime().getConnectionStatus() === "connected";
4406
+ },
4283
4407
  avatar: {
4284
4408
  show() {
4285
4409
  withIsolation(() => requireRuntime().avatarApi().show());