@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.cjs CHANGED
@@ -97,7 +97,7 @@ var ALL_ACTION_KINDS = [
97
97
  // src/core/constants.ts
98
98
  function resolveSdkVersion() {
99
99
  {
100
- return "0.1.21";
100
+ return "0.1.22";
101
101
  }
102
102
  }
103
103
  var SDK_VERSION = resolveSdkVersion();
@@ -115,6 +115,7 @@ var AVATAR_VIEWPORT_PADDING = 12;
115
115
  var AVATAR_TARGET_GAP = 16;
116
116
  var WEBSITE_MAP_TEXT_LIMIT = 80;
117
117
  var CONFIG_CACHE_TTL_MS = 1e3 * 60 * 10;
118
+ var HEARTBEAT_INTERVAL_MS = 45e3;
118
119
 
119
120
  // src/security/selectors.ts
120
121
  var DANGEROUS_SELECTOR = /javascript:|expression\(|@import|url\s*\(|behavior:|binding:|<script/i;
@@ -157,11 +158,12 @@ var ANCHORS = [
157
158
  "top-left"
158
159
  ];
159
160
  var PUBLIC_IDENTIFIER_PATTERN = /^(?=.{1,128}$)[A-Za-z0-9_][A-Za-z0-9_-]*$/;
161
+ 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;
160
162
  function isValidPublicIdentifier(value) {
161
163
  if (typeof value !== "string") return false;
162
164
  const trimmed = value.trim();
163
165
  if (!trimmed || trimmed.length > 128) return false;
164
- 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)) {
166
+ if (UUID_PATTERN.test(trimmed)) {
165
167
  return false;
166
168
  }
167
169
  return PUBLIC_IDENTIFIER_PATTERN.test(trimmed);
@@ -776,7 +778,7 @@ var CloudClient = class {
776
778
  throw new ConfigurationError(`Failed to resolve avatar configuration for project ${this.projectId}`);
777
779
  }
778
780
  async heartbeat(metadata) {
779
- const response = await this.runtimeRequest({
781
+ let response = await this.runtimeRequest({
780
782
  path: "/sdk/heartbeat",
781
783
  method: "POST",
782
784
  idempotent: true,
@@ -789,6 +791,21 @@ var CloudClient = class {
789
791
  timestamp: metadata.timestamp
790
792
  }
791
793
  }, "assistant:heartbeat");
794
+ if (response.status === 404) {
795
+ response = await this.runtimeRequest({
796
+ path: "/api/v1/sdk/heartbeat",
797
+ method: "POST",
798
+ idempotent: true,
799
+ body: {
800
+ project_id: this.projectId,
801
+ public_key: this.publicKey,
802
+ sdk_version: SDK_VERSION,
803
+ origin: metadata.origin,
804
+ environment: metadata.environment,
805
+ timestamp: metadata.timestamp
806
+ }
807
+ }, "assistant:heartbeat");
808
+ }
792
809
  const body = response.data && typeof response.data === "object" && !Array.isArray(response.data) ? response.data : void 0;
793
810
  const rawStatus = body?.status ?? body?.connectionStatus ?? body?.verificationStatus ?? (body?.verified === true ? "verified" : void 0);
794
811
  const verificationStatus = rawStatus === "connected" || rawStatus === "verified" || rawStatus === "inactive" || rawStatus === "not_detected" || rawStatus === "error" ? rawStatus : void 0;
@@ -801,13 +818,22 @@ var CloudClient = class {
801
818
  };
802
819
  }
803
820
  async registerInstallation(registration) {
804
- const response = await this.transport.request({
821
+ let response = await this.transport.request({
805
822
  path: "/sdk/installations/register",
806
823
  method: "POST",
807
824
  body: registration,
808
825
  idempotent: true,
809
826
  sessionId: this.sessionId
810
827
  });
828
+ if (response.status === 404) {
829
+ response = await this.transport.request({
830
+ path: "/api/v1/sdk/installations/register",
831
+ method: "POST",
832
+ body: registration,
833
+ idempotent: true,
834
+ sessionId: this.sessionId
835
+ });
836
+ }
811
837
  if (!response.ok) {
812
838
  throw new NetworkError(`SDK installation registration failed (${response.status}).`);
813
839
  }
@@ -3036,6 +3062,9 @@ function isLikelyJavaScriptUrl(value) {
3036
3062
  const lower = value.trim().toLowerCase();
3037
3063
  return lower.startsWith("javascript:") || lower.startsWith("data:") || lower.startsWith("vbscript:") || lower.includes("eval(") || lower.includes("new function") || lower.includes("document.cookie");
3038
3064
  }
3065
+ function isLocalHost(host) {
3066
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
3067
+ }
3039
3068
  function validateWebsiteDomain(config, currentUrl) {
3040
3069
  const allowedDomains = config.allowedDomains.map((domain) => normalizeHost(domain));
3041
3070
  if (allowedDomains.length === 0) {
@@ -3044,7 +3073,16 @@ function validateWebsiteDomain(config, currentUrl) {
3044
3073
  try {
3045
3074
  const parsed = new URL(currentUrl);
3046
3075
  const host = normalizeHost(parsed.host);
3047
- const allowed = allowedDomains.some((domain) => host === domain || host.endsWith(`.${domain}`));
3076
+ const hostIsLocal = isLocalHost(host);
3077
+ const allowed = allowedDomains.some((domain) => {
3078
+ if (host === domain || host.endsWith(`.${domain}`)) {
3079
+ return true;
3080
+ }
3081
+ if (hostIsLocal && isLocalHost(domain)) {
3082
+ return true;
3083
+ }
3084
+ return false;
3085
+ });
3048
3086
  if (!allowed) {
3049
3087
  return { allowed: false, reason: "DOMAIN_NOT_AUTHORIZED" };
3050
3088
  }
@@ -3696,23 +3734,36 @@ var RuntimeAuth = class {
3696
3734
  const timeout = setTimeout(() => controller.abort(), 1e4);
3697
3735
  let response;
3698
3736
  try {
3699
- response = await fetch(`${this.options.apiBaseUrl.replace(/\/$/, "")}/sdk/runtime/token`, {
3737
+ const baseUrl = this.options.apiBaseUrl.replace(/\/$/, "");
3738
+ const payload = JSON.stringify({
3739
+ projectId: this.options.projectId,
3740
+ publicKey: this.options.publicKey,
3741
+ installationId: this.options.installationId,
3742
+ origin: this.options.origin,
3743
+ environment: this.options.environment,
3744
+ sdkVersion: SDK_VERSION,
3745
+ capabilities: [...RUNTIME_CAPABILITIES]
3746
+ });
3747
+ response = await fetch(`${baseUrl}/sdk/runtime/token`, {
3700
3748
  method: "POST",
3701
3749
  headers: {
3702
3750
  Accept: "application/json",
3703
3751
  "Content-Type": "application/json"
3704
3752
  },
3705
- body: JSON.stringify({
3706
- projectId: this.options.projectId,
3707
- publicKey: this.options.publicKey,
3708
- installationId: this.options.installationId,
3709
- origin: this.options.origin,
3710
- environment: this.options.environment,
3711
- sdkVersion: SDK_VERSION,
3712
- capabilities: [...RUNTIME_CAPABILITIES]
3713
- }),
3753
+ body: payload,
3714
3754
  signal: controller.signal
3715
3755
  });
3756
+ if (response.status === 404) {
3757
+ response = await fetch(`${baseUrl}/api/v1/sdk/runtime/token`, {
3758
+ method: "POST",
3759
+ headers: {
3760
+ Accept: "application/json",
3761
+ "Content-Type": "application/json"
3762
+ },
3763
+ body: payload,
3764
+ signal: controller.signal
3765
+ });
3766
+ }
3716
3767
  } catch {
3717
3768
  throw new NetworkError("ASIYST runtime authentication is unavailable.");
3718
3769
  } finally {
@@ -3859,6 +3910,9 @@ var AsiystRuntime = class {
3859
3910
  this.connectionStatus = "disconnected";
3860
3911
  this.verificationStatus = "not_detected";
3861
3912
  this.rescanDebounced = debounce(() => this.rescan(), DOM_SCAN_DEBOUNCE_MS);
3913
+ this.isHeartbeatInFlight = false;
3914
+ this.lastHeartbeatTime = 0;
3915
+ this.registrationSucceeded = false;
3862
3916
  if (!doc.body) {
3863
3917
  throw new InitializationError("document.body is not available");
3864
3918
  }
@@ -3866,7 +3920,7 @@ var AsiystRuntime = class {
3866
3920
  this.installationId = loadOrCreateInstallationId(options.projectId);
3867
3921
  this.visitorSessionId = options.visitorSessionId || `vsess_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
3868
3922
  const isLocalOrigin = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i.test(win.location.hostname);
3869
- this.environment = options.apiBaseUrl || isLocalOrigin ? "development" : "production";
3923
+ this.environment = options.environment || (isLocalOrigin ? "development" : "production");
3870
3924
  const transport = new HttpTransport({
3871
3925
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
3872
3926
  projectId: options.projectId,
@@ -3963,82 +4017,9 @@ var AsiystRuntime = class {
3963
4017
  sdkVersion: SDK_VERSION
3964
4018
  });
3965
4019
  await this.registerInstallation();
3966
- const previousConnection = this.connectionStatus === "connected";
3967
- try {
3968
- const heartbeat = await this.cloud.heartbeat({
3969
- origin: window.location.origin,
3970
- environment: this.environment,
3971
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
3972
- });
3973
- this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
3974
- this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
3975
- if (heartbeat.ok) {
3976
- this.lifecycle.emit("sdk.connected", {
3977
- projectId: this.options.projectId,
3978
- origin: window.location.origin,
3979
- environment: this.environment,
3980
- installationId: this.installationId,
3981
- sdkVersion: SDK_VERSION
3982
- });
3983
- if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
3984
- this.lifecycle.emit("sdk.verified", {
3985
- projectId: this.options.projectId,
3986
- origin: window.location.origin,
3987
- environment: this.environment,
3988
- installationId: this.installationId,
3989
- sdkVersion: SDK_VERSION
3990
- });
3991
- }
3992
- if (heartbeat.versionOutdated) {
3993
- this.lifecycle.emit("sdk.version_outdated", {
3994
- projectId: this.options.projectId,
3995
- origin: window.location.origin,
3996
- environment: this.environment,
3997
- installationId: this.installationId,
3998
- sdkVersion: SDK_VERSION
3999
- });
4000
- }
4001
- } else {
4002
- const reason = heartbeat.verificationStatus ?? "unverified";
4003
- this.lifecycle.emit("sdk.verification_failed", {
4004
- projectId: this.options.projectId,
4005
- origin: window.location.origin,
4006
- environment: this.environment,
4007
- status: reason,
4008
- reason: "heartbeat_failed"
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
- installationId: this.installationId,
4016
- reason: "heartbeat_failed",
4017
- status: reason
4018
- });
4019
- }
4020
- }
4021
- } catch (error) {
4022
- this.connectionStatus = "offline";
4023
- this.verificationStatus = "error";
4024
- this.lifecycle.emit("sdk.verification_failed", {
4025
- projectId: this.options.projectId,
4026
- origin: window.location.origin,
4027
- environment: this.environment,
4028
- installationId: this.installationId,
4029
- reason: "heartbeat_failed",
4030
- category: error instanceof AuthenticationError ? "authorization" : "network"
4031
- });
4032
- if (previousConnection) {
4033
- this.lifecycle.emit("sdk.disconnected", {
4034
- projectId: this.options.projectId,
4035
- origin: window.location.origin,
4036
- environment: this.environment,
4037
- reason: "heartbeat_failed",
4038
- category: "network"
4039
- });
4040
- }
4041
- }
4020
+ await this.sendHeartbeat();
4021
+ const doc = this.host.host.ownerDocument;
4022
+ this.startHeartbeatScheduler(doc);
4042
4023
  this.events.emit("asiyst:ready", { projectId: this.options.projectId, configVersion: cfg.version });
4043
4024
  void this.cloud.sendTelemetryEvent("avatar_runtime_initialized", {
4044
4025
  avatarId: this.options.avatarId ?? cfg.avatarId ?? cfg.avatarName,
@@ -4163,6 +4144,16 @@ var AsiystRuntime = class {
4163
4144
  return;
4164
4145
  }
4165
4146
  this.destroyed = true;
4147
+ if (this.heartbeatTimer) {
4148
+ clearInterval(this.heartbeatTimer);
4149
+ this.heartbeatTimer = void 0;
4150
+ }
4151
+ const doc = this.host.host.ownerDocument;
4152
+ if (doc && this.visibilityListener) {
4153
+ doc.removeEventListener("visibilitychange", this.visibilityListener);
4154
+ this.visibilityListener = void 0;
4155
+ }
4156
+ this.isHeartbeatInFlight = false;
4166
4157
  if (this.pagehideListener) {
4167
4158
  win.removeEventListener("pagehide", this.pagehideListener);
4168
4159
  }
@@ -4182,6 +4173,135 @@ var AsiystRuntime = class {
4182
4173
  this.events.removeAll();
4183
4174
  await this.analytics.destroy();
4184
4175
  }
4176
+ startHeartbeatScheduler(doc) {
4177
+ if (this.heartbeatTimer) {
4178
+ clearInterval(this.heartbeatTimer);
4179
+ }
4180
+ this.heartbeatTimer = setInterval(() => {
4181
+ if (!this.destroyed) {
4182
+ void this.sendHeartbeat(true);
4183
+ }
4184
+ }, HEARTBEAT_INTERVAL_MS);
4185
+ if (doc && typeof doc.addEventListener === "function") {
4186
+ this.visibilityListener = () => {
4187
+ if (!this.destroyed && doc.visibilityState === "visible" && Date.now() - this.lastHeartbeatTime > 3e4) {
4188
+ void this.sendHeartbeat(true);
4189
+ }
4190
+ };
4191
+ doc.addEventListener("visibilitychange", this.visibilityListener);
4192
+ }
4193
+ }
4194
+ async sendHeartbeat(_isPeriodic = false) {
4195
+ if (this.destroyed || this.isHeartbeatInFlight) {
4196
+ return false;
4197
+ }
4198
+ this.isHeartbeatInFlight = true;
4199
+ const previousConnection = this.connectionStatus === "connected";
4200
+ const origin = window.location.origin;
4201
+ const environment = this.environment;
4202
+ const installationId = this.installationId;
4203
+ try {
4204
+ if (!this.registrationSucceeded && installationId) {
4205
+ await this.registerInstallation();
4206
+ }
4207
+ const heartbeat = await this.cloud.heartbeat({
4208
+ origin,
4209
+ environment,
4210
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4211
+ });
4212
+ this.lastHeartbeatTime = Date.now();
4213
+ this.connectionStatus = heartbeat.ok ? "connected" : "disconnected";
4214
+ this.verificationStatus = heartbeat.verificationStatus === "verified" ? "connected" : heartbeat.verificationStatus ?? (heartbeat.ok ? "connected" : "not_detected");
4215
+ if (heartbeat.ok) {
4216
+ if (!previousConnection) {
4217
+ this.events.emit("asiyst:runtime:connected", {
4218
+ projectId: this.options.projectId,
4219
+ status: "connected",
4220
+ environment,
4221
+ origin
4222
+ });
4223
+ this.lifecycle.emit("sdk.connected", {
4224
+ projectId: this.options.projectId,
4225
+ origin,
4226
+ environment,
4227
+ installationId,
4228
+ sdkVersion: SDK_VERSION
4229
+ });
4230
+ }
4231
+ if (heartbeat.verificationStatus === "connected" || heartbeat.verificationStatus === "verified") {
4232
+ this.lifecycle.emit("sdk.verified", {
4233
+ projectId: this.options.projectId,
4234
+ origin,
4235
+ environment,
4236
+ installationId,
4237
+ sdkVersion: SDK_VERSION
4238
+ });
4239
+ }
4240
+ if (heartbeat.versionOutdated) {
4241
+ this.lifecycle.emit("sdk.version_outdated", {
4242
+ projectId: this.options.projectId,
4243
+ origin,
4244
+ environment,
4245
+ installationId,
4246
+ sdkVersion: SDK_VERSION
4247
+ });
4248
+ }
4249
+ return true;
4250
+ } else {
4251
+ const reason = heartbeat.verificationStatus ?? "unverified";
4252
+ this.lifecycle.emit("sdk.verification_failed", {
4253
+ projectId: this.options.projectId,
4254
+ origin,
4255
+ environment,
4256
+ status: reason,
4257
+ reason: "heartbeat_failed"
4258
+ });
4259
+ if (previousConnection) {
4260
+ this.events.emit("asiyst:runtime:disconnected", {
4261
+ projectId: this.options.projectId,
4262
+ reason: "heartbeat_failed"
4263
+ });
4264
+ this.lifecycle.emit("sdk.disconnected", {
4265
+ projectId: this.options.projectId,
4266
+ origin,
4267
+ environment,
4268
+ installationId,
4269
+ reason: "heartbeat_failed",
4270
+ status: reason
4271
+ });
4272
+ }
4273
+ return false;
4274
+ }
4275
+ } catch (error) {
4276
+ this.connectionStatus = "offline";
4277
+ this.verificationStatus = "error";
4278
+ this.lifecycle.emit("sdk.verification_failed", {
4279
+ projectId: this.options.projectId,
4280
+ origin,
4281
+ environment,
4282
+ installationId,
4283
+ reason: "heartbeat_failed",
4284
+ category: error instanceof AuthenticationError ? "authorization" : "network"
4285
+ });
4286
+ if (previousConnection) {
4287
+ this.events.emit("asiyst:runtime:disconnected", {
4288
+ projectId: this.options.projectId,
4289
+ reason: "heartbeat_failed"
4290
+ });
4291
+ this.lifecycle.emit("sdk.disconnected", {
4292
+ projectId: this.options.projectId,
4293
+ origin,
4294
+ environment,
4295
+ installationId,
4296
+ reason: "heartbeat_failed",
4297
+ category: "network"
4298
+ });
4299
+ }
4300
+ return false;
4301
+ } finally {
4302
+ this.isHeartbeatInFlight = false;
4303
+ }
4304
+ }
4185
4305
  async registerInstallation() {
4186
4306
  const origin = window.location.origin;
4187
4307
  const environment = this.environment;
@@ -4203,6 +4323,7 @@ var AsiystRuntime = class {
4203
4323
  environment,
4204
4324
  sdk_version: SDK_VERSION
4205
4325
  });
4326
+ this.registrationSucceeded = true;
4206
4327
  return;
4207
4328
  } catch (error) {
4208
4329
  lastError = error;
@@ -4302,6 +4423,9 @@ var Asiyst = {
4302
4423
  getVerificationStatus() {
4303
4424
  return requireRuntime().getVerificationStatus();
4304
4425
  },
4426
+ isRuntimeConnected() {
4427
+ return requireRuntime().getConnectionStatus() === "connected";
4428
+ },
4305
4429
  avatar: {
4306
4430
  show() {
4307
4431
  withIsolation(() => requireRuntime().avatarApi().show());