ui.shipaid.com 0.3.46 → 0.3.47

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/widget.es.js CHANGED
@@ -1960,6 +1960,23 @@ var __decorateClass = (decorators, target, key, kind) => {
1960
1960
  if (result) __defProp(target, key, result);
1961
1961
  return result;
1962
1962
  };
1963
+ const formatCartDataItems = (cart) => {
1964
+ const formattedCartWithItems = {
1965
+ items: cart.lines.edges.map(({ node: l2 }) => {
1966
+ return {
1967
+ id: l2.id,
1968
+ key: l2.id,
1969
+ variant_id: l2.merchandise.id,
1970
+ sku: l2.merchandise.sku,
1971
+ final_line_price: parseFloat(l2.cost.totalAmount.amount),
1972
+ quantity: l2.quantity
1973
+ };
1974
+ }),
1975
+ total_price: parseFloat(cart.cost.totalAmount.amount),
1976
+ item_count: cart.lines.edges.length
1977
+ };
1978
+ return formattedCartWithItems;
1979
+ };
1963
1980
  const runRequest = async (input, init) => {
1964
1981
  try {
1965
1982
  const response = await fetch(input, init);
@@ -2017,6 +2034,11 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2017
2034
  constructor() {
2018
2035
  var _a, _b, _c;
2019
2036
  super(...arguments);
2037
+ this.env = "prod";
2038
+ this.useCustomStoreFront = false;
2039
+ this.storeDomain = "";
2040
+ this.storeAccessToken = "";
2041
+ this.cartId = "";
2020
2042
  this.disablePolling = false;
2021
2043
  this.disableActions = false;
2022
2044
  this.pollingInterval = POLL_INTERVAL_DEFAULT;
@@ -2036,7 +2058,7 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2036
2058
  this.hasLoadedStrings = false;
2037
2059
  this.fetchInterceptorCleanup = () => {
2038
2060
  };
2039
- this.intervalId = 0;
2061
+ this.intervalId = null;
2040
2062
  this._state = {
2041
2063
  loading: false,
2042
2064
  success: null,
@@ -2064,6 +2086,61 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2064
2086
  localStorage.setItem(`${LOCAL_STORAGE_SHIPAID_POPUP_KEY}`, "true");
2065
2087
  }
2066
2088
  }
2089
+ get nhost() {
2090
+ const subdomain = this.env === "prod" ? "gjiyysyzjwuculcymsvb" : this.env === "staging" ? "xfnjpunvafvudwuzwjlm" : "local";
2091
+ const region = "us-east-1";
2092
+ const url = `https://${subdomain}.graphql.${region}.nhost.run/v1`;
2093
+ return {
2094
+ request: async (query, variables) => {
2095
+ try {
2096
+ const response = await fetch(url, {
2097
+ method: "post",
2098
+ body: JSON.stringify({
2099
+ query,
2100
+ variables
2101
+ })
2102
+ });
2103
+ const result = await response.json();
2104
+ return result;
2105
+ } catch (error) {
2106
+ console.log(`Nhost Error: ${error}`);
2107
+ }
2108
+ }
2109
+ };
2110
+ }
2111
+ /** Runs a GraphQL query and returns the data
2112
+ * @param query GraphQL query string
2113
+ * @param variables Variables for the query
2114
+ * @returns Query response data
2115
+ */
2116
+ async runStoreFrontQuery(query, variables) {
2117
+ try {
2118
+ const myHeaders = new Headers();
2119
+ myHeaders.append("Content-Type", "application/json");
2120
+ myHeaders.append("X-Shopify-Storefront-Access-Token", this.storeAccessToken);
2121
+ const raw = JSON.stringify({
2122
+ query,
2123
+ variables
2124
+ });
2125
+ const requestOptions = {
2126
+ method: "POST",
2127
+ headers: myHeaders,
2128
+ body: raw
2129
+ };
2130
+ const response = await fetch(`https://${this.storeDomain}/api/2021-07/graphql.json`, requestOptions);
2131
+ if (!response.ok) {
2132
+ throw new Error(`GraphQL request failed: ${response.statusText}`);
2133
+ }
2134
+ const json = await response.json();
2135
+ if (json.errors) {
2136
+ throw new Error(json.errors[0].message);
2137
+ }
2138
+ return json.data;
2139
+ } catch (error) {
2140
+ console.error("GraphQL query error:", error);
2141
+ throw new Error("Failed to execute GraphQL query");
2142
+ }
2143
+ }
2067
2144
  /** Getter to check if we should refresh the page or not */
2068
2145
  get shouldRefreshOnUpdate() {
2069
2146
  if (this.disablePolling) return false;
@@ -2171,25 +2248,36 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2171
2248
  /** Fetches store info from the ShipAid public API. */
2172
2249
  async _fetchShipAidData() {
2173
2250
  var _a, _b, _c, _d, _e;
2174
- const shop = ((_a = window.Shopify) == null ? void 0 : _a.shop) ?? ((_c = (_b = window.Shopify) == null ? void 0 : _b.Checkout) == null ? void 0 : _c.apiHost);
2251
+ let shop;
2252
+ if (this.storeDomain) {
2253
+ shop = this.storeDomain;
2254
+ } else {
2255
+ shop = ((_a = window.Shopify) == null ? void 0 : _a.shop) ?? ((_c = (_b = window.Shopify) == null ? void 0 : _b.Checkout) == null ? void 0 : _c.apiHost);
2256
+ }
2175
2257
  if (!shop) throw new Error("No shop found in Shopify object.");
2176
2258
  try {
2177
- const endpoint = new URL(window.location.href);
2178
- endpoint.pathname = this._apiEndpoint;
2179
- const payload = {
2180
- query: StoreQuery,
2181
- variables: { store: shop }
2182
- };
2183
- const response = await this._fetch.post(
2184
- endpoint.toString(),
2185
- payload
2186
- );
2187
- if (!response) throw new Error("Missing response for store query.");
2188
- if ((_d = response.errors) == null ? void 0 : _d.length) throw new Error(response.errors[0].message);
2189
- if (!((_e = response.data) == null ? void 0 : _e.store)) {
2259
+ let endpoint;
2260
+ let result;
2261
+ if (this.useCustomStoreFront) {
2262
+ result = await this.nhost.request(StoreQuery, { store: shop });
2263
+ } else {
2264
+ endpoint = new URL(window.location.href);
2265
+ endpoint.pathname = this._apiEndpoint;
2266
+ const payload = {
2267
+ query: StoreQuery,
2268
+ variables: { store: shop }
2269
+ };
2270
+ result = await this._fetch.post(
2271
+ endpoint.toString(),
2272
+ payload
2273
+ );
2274
+ }
2275
+ if (!result) throw new Error("Missing response for store query.");
2276
+ if ((_d = result.errors) == null ? void 0 : _d.length) throw new Error(result.errors[0].message);
2277
+ if (!((_e = result.data) == null ? void 0 : _e.store)) {
2190
2278
  throw new Error("Missing store from store query response.");
2191
2279
  }
2192
- return response.data.store;
2280
+ return result.data.store;
2193
2281
  } catch (error) {
2194
2282
  console.error(error);
2195
2283
  throw new Error(`Could not find a store for ${this._storeDomain}`);
@@ -2239,6 +2327,14 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2239
2327
  /** Fetch current cart from the Shopify ajax API */
2240
2328
  async _fetchCart() {
2241
2329
  try {
2330
+ if (this.useCustomStoreFront && this.cartId) {
2331
+ const result = await this.runStoreFrontQuery(
2332
+ "query getCart($cartId: ID!){ cart( id: $cartId ) { id createdAt updatedAt lines(first: 10) { edges { node { id quantity merchandise { ... on ProductVariant { id sku } } cost{ totalAmount{ amount currencyCode } } } } } cost { totalAmount { amount currencyCode } subtotalAmount { amount currencyCode } } } }",
2333
+ { cartId: this.cartId }
2334
+ );
2335
+ const cart2 = formatCartDataItems(result.cart);
2336
+ return cart2;
2337
+ }
2242
2338
  const cart = await this._fetch.get("/cart.js");
2243
2339
  return cart;
2244
2340
  } catch (err) {
@@ -2249,10 +2345,32 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2249
2345
  }
2250
2346
  /** Fetch current product from the Shopify ajax API */
2251
2347
  async _fetchProduct() {
2348
+ var _a, _b;
2252
2349
  try {
2253
- const { product } = await this._fetch.get(
2254
- `/products/${PRODUCT_HANDLE}.json`
2255
- );
2350
+ let product;
2351
+ if (this.useCustomStoreFront) {
2352
+ const result = await this.runStoreFrontQuery(
2353
+ "query searchProducts($query: String!, $first: Int) { search(query: $query, first: $first, types: PRODUCT) { edges { node { ... on Product { id title handle variants(first: 1) { edges { node { id title price { amount } } } } } } } } }",
2354
+ {
2355
+ query: "ShipAid Delivery Guarantee",
2356
+ first: 1
2357
+ }
2358
+ );
2359
+ if ((_b = (_a = result == null ? void 0 : result.search) == null ? void 0 : _a.edges) == null ? void 0 : _b.length) {
2360
+ const protectionProductItem = result.search.edges[0];
2361
+ product = {
2362
+ id: protectionProductItem.node.id,
2363
+ variants: protectionProductItem.node.variants.edges.map((v2) => ({
2364
+ id: v2.node.id,
2365
+ price: v2.node.price.amount
2366
+ }))
2367
+ };
2368
+ }
2369
+ } else {
2370
+ product = (await this._fetch.get(
2371
+ `/products/${PRODUCT_HANDLE}.json`
2372
+ )).product;
2373
+ }
2256
2374
  return product;
2257
2375
  } catch (err) {
2258
2376
  const error = err;
@@ -2270,6 +2388,77 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2270
2388
  if (!cart) cart = await this._fetchCart();
2271
2389
  this._cart = cart;
2272
2390
  }
2391
+ async addCartProtectionVariant() {
2392
+ var _a, _b, _c, _d;
2393
+ let cart;
2394
+ let sellingPlanId;
2395
+ if (this.supportSubscriptions) {
2396
+ const itemWithSubscription = (_b = (_a = this._cart) == null ? void 0 : _a.items) == null ? void 0 : _b.find((item) => {
2397
+ var _a2;
2398
+ return item.id !== ((_a2 = this._protectionVariant) == null ? void 0 : _a2.id) && !!(item == null ? void 0 : item.selling_plan_allocation);
2399
+ });
2400
+ if (itemWithSubscription) {
2401
+ const protectionSellingPlan = await this._fetchSellingPlanFromVariant(itemWithSubscription.selling_plan_allocation.selling_plan);
2402
+ sellingPlanId = protectionSellingPlan ? getIdFromShopifyGid(protectionSellingPlan.id) : null;
2403
+ }
2404
+ }
2405
+ if (this.useCustomStoreFront) {
2406
+ const cartItemAdded = await this.runStoreFrontQuery(
2407
+ "mutation AddItemToCart($cartId: ID!, $lines: [CartLineInput!]!) { cartLinesAdd(cartId: $cartId, lines: $lines) { cart { id lines(first: 10) { edges { node { id quantity merchandise { ... on ProductVariant { id sku } } cost{ totalAmount{ amount currencyCode } } } } } cost { totalAmount { amount currencyCode } subtotalAmount { amount currencyCode } } } } }",
2408
+ {
2409
+ cartId: this.cartId,
2410
+ lines: [{
2411
+ merchandiseId: String((_c = this._protectionVariant) == null ? void 0 : _c.id),
2412
+ quantity: 1,
2413
+ sellingPlanId
2414
+ }]
2415
+ }
2416
+ );
2417
+ cart = formatCartDataItems(cartItemAdded.cartLinesAdd.cart);
2418
+ } else {
2419
+ const payload = {
2420
+ quantity: 1,
2421
+ id: String((_d = this._protectionVariant) == null ? void 0 : _d.id),
2422
+ selling_plan: sellingPlanId
2423
+ };
2424
+ cart = await this._fetch.post(
2425
+ "/cart/add.js",
2426
+ payload
2427
+ );
2428
+ }
2429
+ return cart;
2430
+ }
2431
+ async updateCartProtectionVariant(qty, protectionCartItem = null, sellingPlanId = null) {
2432
+ var _a, _b;
2433
+ let cart;
2434
+ if (this.useCustomStoreFront) {
2435
+ const cartItemUpdated = await this.runStoreFrontQuery(
2436
+ "mutation RemoveItemToCart($cartId: ID!, $lines: [CartLineUpdateInput!]!) { cartLinesUpdate(cartId: $cartId, lines: $lines) { cart { id lines(first: 10) { edges { node { id quantity merchandise { ... on ProductVariant { id sku } } cost{ totalAmount{ amount currencyCode } } } } } cost { totalAmount { amount currencyCode } subtotalAmount { amount currencyCode } } } } }",
2437
+ {
2438
+ cartId: this.cartId,
2439
+ lines: [
2440
+ {
2441
+ id: String(protectionCartItem ? protectionCartItem.key : (_a = this._protectionCartItem) == null ? void 0 : _a.key),
2442
+ quantity: qty,
2443
+ sellingPlanId
2444
+ }
2445
+ ]
2446
+ }
2447
+ );
2448
+ cart = formatCartDataItems(cartItemUpdated.cartLinesUpdate.cart);
2449
+ } else {
2450
+ const payload = {
2451
+ quantity: qty,
2452
+ id: String(protectionCartItem ? protectionCartItem.key : (_b = this._protectionCartItem) == null ? void 0 : _b.key),
2453
+ selling_plan: sellingPlanId
2454
+ };
2455
+ cart = await this._fetch.post(
2456
+ "/cart/change.js",
2457
+ payload
2458
+ );
2459
+ }
2460
+ return cart;
2461
+ }
2273
2462
  /** Add ShipAid shipping protection. */
2274
2463
  async addProtection() {
2275
2464
  var _a, _b;
@@ -2280,26 +2469,8 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2280
2469
  throw new Error("No protection variant found.");
2281
2470
  }
2282
2471
  this._setState("loading");
2283
- const payload = {
2284
- quantity: 1,
2285
- id: this._protectionVariant.id
2286
- };
2287
- if (this.supportSubscriptions) {
2288
- const itemWithSubscription = this._cart.items.find((item) => {
2289
- var _a2;
2290
- return item.id !== ((_a2 = this._protectionVariant) == null ? void 0 : _a2.id) && !!(item == null ? void 0 : item.selling_plan_allocation);
2291
- });
2292
- if (itemWithSubscription) {
2293
- const protectionSellingPlan = await this._fetchSellingPlanFromVariant(itemWithSubscription.selling_plan_allocation.selling_plan);
2294
- const sellingPlanId = protectionSellingPlan ? getIdFromShopifyGid(protectionSellingPlan.id) : null;
2295
- payload.selling_plan = sellingPlanId;
2296
- }
2297
- }
2298
- const cartItem = await this._fetch.post(
2299
- "/cart/add.js",
2300
- payload
2301
- );
2302
- await this._handleRefresh(cartItem);
2472
+ const cart = await this.addCartProtectionVariant();
2473
+ await this._handleRefresh(cart);
2303
2474
  this._setState("success");
2304
2475
  } catch (err) {
2305
2476
  const error = err;
@@ -2317,14 +2488,7 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2317
2488
  throw new Error("Protection product not found.");
2318
2489
  }
2319
2490
  this._setState("loading");
2320
- const payload = {
2321
- quantity: 0,
2322
- id: this._protectionCartItem.key
2323
- };
2324
- const cart = await this._fetch.post(
2325
- "/cart/change.js",
2326
- payload
2327
- );
2491
+ const cart = await this.updateCartProtectionVariant(0, this._protectionCartItem);
2328
2492
  await this._handleRefresh(cart);
2329
2493
  this._cart = cart;
2330
2494
  this._setState("success");
@@ -2382,14 +2546,7 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2382
2546
  );
2383
2547
  });
2384
2548
  const protectionCartItem = (_e = this._cart) == null ? void 0 : _e.items[protectionCartItemIndex];
2385
- const removePayload = {
2386
- id: protectionCartItem.key,
2387
- quantity: 0
2388
- };
2389
- const cart = await this._fetch.post(
2390
- "/cart/change.js",
2391
- removePayload
2392
- );
2549
+ const cart = await this.updateCartProtectionVariant(0, protectionCartItem);
2393
2550
  return await this._handleRefresh(cart);
2394
2551
  }
2395
2552
  }
@@ -2579,14 +2736,7 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2579
2736
  if (!this._store) return;
2580
2737
  const protectionFee = await this.calculateProtectionTotal(this._cart);
2581
2738
  if (this._cart.item_count > 0 && !!protectionCartItem && (this._cart.total_price === (protectionCartItem == null ? void 0 : protectionCartItem.final_line_price) || !protectionFee)) {
2582
- const removePayload = {
2583
- id: protectionCartItem.key,
2584
- quantity: 0
2585
- };
2586
- const cart2 = await this._fetch.post(
2587
- "/cart/change.js",
2588
- removePayload
2589
- );
2739
+ const cart2 = await this.updateCartProtectionVariant(0, protectionCartItem);
2590
2740
  sessionStorage.removeItem(LOCAL_STORAGE_KEY);
2591
2741
  return await this._handleRefresh(cart2);
2592
2742
  }
@@ -2624,7 +2774,7 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2624
2774
  updateSubscriptionPayload = { id: protectionCartItem.key, quantity: 1, selling_plan: sellingPlanId };
2625
2775
  }
2626
2776
  if (updateSubscriptionPayload) {
2627
- const cart2 = await this._fetch.post("/cart/change.js", updateSubscriptionPayload);
2777
+ const cart2 = await this.updateCartProtectionVariant(updateSubscriptionPayload.quantity, protectionCartItem, updateSubscriptionPayload.selling_plan);
2628
2778
  await this._handleRefresh(cart2);
2629
2779
  }
2630
2780
  }
@@ -2635,14 +2785,7 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
2635
2785
  position: protectionCartItemIndex + 1
2636
2786
  };
2637
2787
  if (protectionCartItem.quantity === 1) return;
2638
- const updatePayload2 = {
2639
- id: protectionCartItem.key,
2640
- quantity: 1
2641
- };
2642
- const cart2 = await this._fetch.post(
2643
- "/cart/change.js",
2644
- updatePayload2
2645
- );
2788
+ const cart2 = await this.updateCartProtectionVariant(1, protectionCartItem);
2646
2789
  this._handleRefreshCart();
2647
2790
  return await this._handleRefresh(cart2);
2648
2791
  }
@@ -3043,6 +3186,21 @@ const _ShipAidWidget = class _ShipAidWidget extends s$1 {
3043
3186
  };
3044
3187
  _ShipAidWidget.styles = styles;
3045
3188
  let ShipAidWidget = _ShipAidWidget;
3189
+ __decorateClass([
3190
+ n$7({ type: String, attribute: true })
3191
+ ], ShipAidWidget.prototype, "env");
3192
+ __decorateClass([
3193
+ n$7({ type: Boolean, attribute: true })
3194
+ ], ShipAidWidget.prototype, "useCustomStoreFront");
3195
+ __decorateClass([
3196
+ n$7({ type: String, attribute: true })
3197
+ ], ShipAidWidget.prototype, "storeDomain");
3198
+ __decorateClass([
3199
+ n$7({ type: String, attribute: true })
3200
+ ], ShipAidWidget.prototype, "storeAccessToken");
3201
+ __decorateClass([
3202
+ n$7({ type: String, attribute: true })
3203
+ ], ShipAidWidget.prototype, "cartId");
3046
3204
  __decorateClass([
3047
3205
  n$7({ type: Boolean, attribute: true })
3048
3206
  ], ShipAidWidget.prototype, "disablePolling");