@depict-ai/dpc 1.0.43 → 1.0.45

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/ES10/index.cjs CHANGED
@@ -17,7 +17,7 @@ function $parcel$interopDefault(a) {
17
17
  $parcel$export(module.exports, "DPC", () => $89ae37e3a26189b4$export$820526014323765f);
18
18
  $parcel$export(module.exports, "version", () => $fcc8287091fb489d$export$83d89fbfd8236492);
19
19
  /*! Depict PerformanceClient */
20
- const $fcc8287091fb489d$export$83d89fbfd8236492 = "1.0.43";
20
+ const $fcc8287091fb489d$export$83d89fbfd8236492 = "1.0.45";
21
21
  let $405164bc961cc106$export$8ae64f3d447c14f7;
22
22
  (function (ProductCardType) {
23
23
  ProductCardType[ProductCardType["Recommendation"] = 0] = "Recommendation";
package/ES10/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const version = "1.0.43";
1
+ export const version = "1.0.45";
2
2
  enum ProductCardType {
3
3
  Recommendation = 0,
4
4
  SnakeRecommendation = 1,
package/ES10/index.js CHANGED
@@ -6,7 +6,7 @@ import $4uUHR$babelruntimehelpersclassPrivateFieldSet from "@babel/runtime/helpe
6
6
  /*! Depict PerformanceClient */
7
7
  import { register_es_version } from "../multi_import_deduplicator.mjs";
8
8
  register_es_version("performance-client", "ES10");
9
- const $3242b911de3d57ad$export$83d89fbfd8236492 = "1.0.43";
9
+ const $3242b911de3d57ad$export$83d89fbfd8236492 = "1.0.45";
10
10
  let $983195e3c4979825$export$8ae64f3d447c14f7;
11
11
  (function (ProductCardType) {
12
12
  ProductCardType[ProductCardType["Recommendation"] = 0] = "Recommendation";
package/dist/index.cjs CHANGED
@@ -17,7 +17,7 @@ function $parcel$interopDefault(a) {
17
17
  $parcel$export(module.exports, "DPC", () => $89ae37e3a26189b4$export$820526014323765f);
18
18
  $parcel$export(module.exports, "version", () => $fcc8287091fb489d$export$83d89fbfd8236492);
19
19
  /*! Depict PerformanceClient */
20
- const $fcc8287091fb489d$export$83d89fbfd8236492 = "1.0.43";
20
+ const $fcc8287091fb489d$export$83d89fbfd8236492 = "1.0.45";
21
21
  let $405164bc961cc106$export$8ae64f3d447c14f7;
22
22
  (function (ProductCardType) {
23
23
  ProductCardType[ProductCardType["Recommendation"] = 0] = "Recommendation";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const version = "1.0.43";
1
+ export const version = "1.0.45";
2
2
  enum ProductCardType {
3
3
  Recommendation = 0,
4
4
  SnakeRecommendation = 1,
@@ -0,0 +1 @@
1
+ {"mappings":";ACEA;;GAEG;AACH,0BAA0B;IACxB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC9C,UAAU,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IAC7D,KAAK,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH;IACE,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IAClC,GAAG,EAAE,WAAW,CAAC;IACjB,GAAG,EAAE,GAAiB,CAAC;CACxB;AAED,QAAQ,MAAM,CAAC;IACb,UAAU,MAAM;QACd;;WAEG;QACH,GAAG,EAAE,WAAW,CAAC;QACjB,MAAM,EAAE,YAAY,CAAC;KACtB;CACF;AEbD;IACE;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AACD;;IACE,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,UAAQ;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qEAAqE;IACrE,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,4DAA4D;IAC5D,cAAc,CAAC,EAAE,MAAM,CAAC;gBAEZ,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO;IA+B/C;;OAEG;IACH,uBAAuB,CAAC,IAAI,EAAE,WAAW;IAiBzC,gBAAgB,uBAA8B;IAC9C;;OAEG;IACH,cAAc,CAAC,OAAO,EAAE,WAAW;IAQnC;;OAEG;IACH,oBAAoB,CAAC,MAAM,EAAE,WAAW;IAsBxC;;OAEG;IACH,kBAAkB,CAAC,IAAI,KAAA;IAGvB;;OAEG;IACH,iCAAiC,CAAC,EAAE,iBAAiB,EAAE,EAAE;QAAE,iBAAiB,EAAE,MAAM,CAAA;KAAE;IAGtF;;OAEG;IACH,4BAA4B,CAAC,EAAE,iBAAiB,EAAE,EAAE;QAAE,iBAAiB,EAAE,MAAM,CAAA;KAAE;IAGjF;;OAEG;IACH,iBAAiB,CAAC,IAAI,EAAE;QAAE,cAAc,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,gBAAgB,EAAE,CAAA;KAAE;IAkBlG;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM;IAGxB;;OAEG;IACH,YAAY,CAAC,UAAU,EAAE,MAAM;IAS/B;;;;OAIG;IACH,SAAS,CAAC,OAAO,EAAE,MAAM;IAIzB;;OAEG;IACH,sBAAsB;IAStB;;OAEG;IACH,mBAAmB;CAOpB;ACrND,OAAO,MAAM,iBAAiB,CAAC","sources":["packages/performance-client/selectors.ts","packages/performance-client/types.ts","packages/performance-client/setup_dpq.ts","packages/performance-client/PerformanceClient.ts","packages/performance-client/version.ts","packages/performance-client/index_npm.ts"],"sourcesContent":["export const a2c_selector = \".depict-add-to-cart\";\nexport const recommendation_card_selector = \"[data-recommendation_id],[data-recommendation-id]\";\n","import type { PerformanceClient } from \"./PerformanceClient\";\n\n/**\n * The Depict Queue function used to register events to be sent to depict.\n */\nexport type DepictQueue = {\n (eventName: string, ...args: unknown[]): void;\n send_event?: (eventName: string, ...args: unknown[]) => void;\n queue: [string, unknown][];\n};\n\n/**\n * Depict Object containing everything depict-related on the page.\n */\nexport interface DepictObject {\n eventHistory: [string, unknown][];\n dpq: DepictQueue;\n dpc: PerformanceClient;\n}\n\ndeclare global {\n interface Window {\n /**\n * Lifted DPQ function for ease-of-use\n */\n dpq: DepictQueue;\n depict: DepictObject;\n }\n}\n","import { PerformanceClient } from \"./PerformanceClient\";\nimport { DepictObject } from \"./types\";\n\n/**\n * Creates an event queue (depict queue)\n */\nfunction create_dpq() {\n const fn: any = function () {\n const args = arguments;\n if (fn.send_event) {\n fn.send_event.apply(this, args);\n } else {\n fn.queue.push(args);\n }\n };\n fn.queue = [];\n return fn;\n}\n\nconst string_guard = (eventName: string, eventData: any) => {\n if (typeof eventData !== \"string\") {\n throw new Error(`${eventName} event requires a string as an argument`);\n }\n};\n\n/**\n * Handle events from dpq with the global dpc instance.\n */\nconst event_handler = (eventName: string, eventData: any) => {\n const dpc = window.depict.dpc;\n if (eventName === \"purchase\") {\n if (typeof eventData !== \"object\" || eventData === null) {\n throw new Error(\"purchase event requires an object as an argument\");\n } else if (!Array.isArray(eventData.products)) {\n throw new Error(\"purchase event requires a products array\");\n } else if (!eventData.currency || typeof eventData.currency !== \"string\") {\n throw new Error(\"purchase event requires a currency string\");\n } else if (!eventData.transaction_id || typeof eventData.transaction_id !== \"string\") {\n throw new Error(\"purchase event requires a transaction_id string\");\n }\n dpc.sendPurchaseEvent(eventData);\n } else if (eventName === \"setMarket\") {\n string_guard(eventName, eventData);\n dpc.setMarket(eventData);\n } else if (eventName === \"setProductId\") {\n string_guard(eventName, eventData);\n dpc.setProductId(eventData);\n } else if (eventName === \"setUserId\") {\n string_guard(eventName, eventData);\n dpc.setUserId(eventData);\n }\n};\n\n/**\n * Hooks up Depict Queue (dpq) to Depict Performance Client (dpc).\n * Creates dpq if it doesn't exist.\n */\nexport const setup_dpq = (dpc: PerformanceClient) => {\n const dpq = (window.dpq ||= create_dpq());\n const depict = (window.depict ||= {} as DepictObject);\n depict.dpq = dpq; // refrencing dpq into the depict object\n depict.eventHistory = dpq.queue; // making this more visible in the depict object\n depict.dpc = dpc;\n\n // Hook up the depict queue to the PerformanceClient\n if (!dpq.send_event) {\n dpq.send_event = (eventName: string, eventData: unknown) => {\n dpq.queue.push([eventName, eventData]); // push to queue as usual to keep history\n event_handler(eventName, eventData); // hand-over to the PerformanceClient\n };\n // Handle any events queued before this code ran.\n dpq.queue.forEach(([eventName, eventData]) => {\n event_handler(eventName, eventData);\n });\n }\n};\n","import {\n depict_body,\n depict_click,\n derror,\n dlog,\n foolproof_send_beacon,\n get_tracking_event_context_data,\n impression_track_element,\n observer,\n send_depict_unfiltered,\n} from \"@depict-ai/utilishared\";\nimport { PurchasedProduct, TrackV2Request } from \"@depict-ai/types/api/TrackV2Request\";\nimport { a2c_selector, recommendation_card_selector } from \"./selectors\";\nimport { setup_dpq } from \"./setup_dpq\";\n\nexport interface Options {\n /**\n * The initial market. Should be specified if the market is known at the point of intializing DPC.\n */\n market?: string;\n /**\n * If we should observe for recommendations on creation. If false, you must call `trackRecommendationCard` manually.\n */\n auto_observe?: boolean;\n}\nexport class PerformanceClient {\n merchant: string;\n auto_observe = true;\n market?: string;\n\n /** Latest product_id found in the DOM. Used in a2c & pageview events on PDPs. */\n latest_product_id?: string;\n /** The value of location.pathname when latest_product_id was set */\n latest_product_id_path?: string;\n /** Latest user_id found in the DOM. Used for all events. */\n latest_user_id?: string;\n\n constructor(merchant: string, options?: Options) {\n // Make sure we do not construct dpc more than once.\n if (window.depict.dpc instanceof PerformanceClient) {\n dlog(\"DPC already initialized. Returning existing instance.\");\n return window.depict.dpc;\n }\n setup_dpq(this);\n this.merchant = merchant;\n this.#parseOptions(options);\n if (this.auto_observe) {\n this.observeRecommendations();\n this.observePDPA2CButton();\n }\n }\n\n #parseOptions(options?: Options) {\n if (options !== undefined) {\n if (options.auto_observe !== undefined) {\n this.auto_observe = options.auto_observe;\n }\n if (options.market !== undefined) {\n this.market = options.market;\n }\n }\n }\n\n #getContextData() {\n const data = { market: this.market, tenant: this.merchant, user_id: this.latest_user_id };\n return { ...get_tracking_event_context_data(), data };\n }\n\n /**\n * Adds click and impression tracking to a recommendation card\n */\n trackRecommendationCard(card: HTMLElement) {\n const recommendation_id = card.dataset.recommendation_id;\n if (!recommendation_id) {\n derror(\"No recommendation_id found on card. Can't add tracking.\", card);\n return;\n }\n if (this.checkIfTracked(card)) return;\n card.addEventListener(\"click\", () => this.sendRecommendationClickEvent({ recommendation_id }));\n impression_track_element({\n element: card,\n data: { recommendation_id, ...this.#getContextData() },\n });\n\n // If the card has an optional a2c button, we track that as well.\n const a2c_button = card.querySelector<HTMLElement>(a2c_selector);\n if (a2c_button) this.trackAddToCartButton(a2c_button);\n }\n tracked_elements = new WeakSet<HTMLElement>();\n /**\n * Make sure the tracking is not set up twice on the same element.\n */\n checkIfTracked(element: HTMLElement) {\n if (this.tracked_elements.has(element)) {\n dlog(\"Already tracked\", element);\n return true;\n }\n this.tracked_elements.add(element);\n return false;\n }\n /**\n * Adds tracking to an Add to cart button.\n */\n trackAddToCartButton(button: HTMLElement) {\n if (this.checkIfTracked(button)) return;\n button.addEventListener(\"click\", () => {\n // If the button is nested in a recommendation, include the recommendation id.\n const recommendation_id = button.closest<HTMLElement>(recommendation_card_selector)?.dataset.recommendation_id;\n // If there exists a product_id on the page, we can send it with the event. This is for PDPs only.\n const product_id = this.#getProductId();\n this.sendAddToCartEvent({\n product_id,\n recommendation_id,\n });\n });\n }\n /**\n * Sends a tracking event to depict\n */\n #sendTrackingEvent(payload: depict_body) {\n // Todo. check consent. For some events, delay until consent decision, with possible timeout.\n // For others, decide immediately based on current consent. (We shouldn't track a long history of events from before the user consented)\n // If no consent, don't send at all, or send anonymous? I think the latter is valid, since no ID in cookie or localStorage.\n send_depict_unfiltered([{ ...payload, ...this.#getContextData() }], true);\n }\n /**\n * Sends an Add to Cart Event to depict\n */\n sendAddToCartEvent(data) {\n this.#sendTrackingEvent({ type: \"add_to_cart\", ...data });\n }\n /**\n * Sends an impression event to Depict\n */\n sendRecommendationImpressionEvent({ recommendation_id }: { recommendation_id: string }) {\n this.#sendTrackingEvent({ type: \"element_visible\", recommendation_id });\n }\n /**\n * Sends a recommendation click event to Depict\n */\n sendRecommendationClickEvent({ recommendation_id }: { recommendation_id: string }) {\n depict_click({ recommendation_id, ...this.#getContextData() });\n }\n /**\n * Sends a Purchase Event to Depict\n */\n sendPurchaseEvent(data: { transaction_id: string; currency: string; products: PurchasedProduct[] }) {\n if (!this.market) {\n throw Error(\"Market not set\");\n }\n\n const request: TrackV2Request = {\n events: [\n {\n event_type: \"purchase\",\n ...data,\n },\n ],\n tenant: this.merchant,\n market: this.market,\n };\n\n foolproof_send_beacon(process.env.BASE_URL + \"/v2/create-events\", request);\n }\n /**\n * Update the market used for tracking events\n */\n setMarket(market: string) {\n this.market = market;\n }\n /**\n * Update the product_id used for add-to-cart and pageview events on PDPs.\n */\n setProductId(product_id: string) {\n dlog(\"Setting product id\", product_id);\n this.latest_product_id = product_id;\n this.latest_product_id_path = location.pathname;\n }\n #getProductId() {\n if (this.latest_product_id_path !== location.pathname) return undefined;\n return this.latest_product_id;\n }\n /**\n * Set the user_id for logged in users.\n *\n * https://docs.depict.ai/docs/performance-client#informing-depict-of-logged-in-users\n */\n setUserId(user_id: string) {\n dlog(\"Setting user id\", user_id);\n this.latest_user_id = user_id;\n }\n /**\n * Observe the dom for recommendations to track\n */\n observeRecommendations() {\n dlog(\"Starting to observe recommendations with selector\", recommendation_card_selector);\n observer.onexists(recommendation_card_selector, ({ element }) => {\n // I think we'll have to search for \"parent\"/\"container\" elements first, which should contain the surface/rectype name.\n // Then it's easier to dedup cards and get their index as well.\n dlog(\"found recommendation\", element);\n this.trackRecommendationCard(element);\n });\n }\n /**\n * Observe the dom for add to cart buttons. Used on product detail pages.\n */\n observePDPA2CButton() {\n const handler = ({ element }) => {\n dlog(\"Found pdp add-to-cart button\", element);\n this.trackAddToCartButton(element);\n };\n observer.onexists(a2c_selector, handler);\n }\n}\n","export const version = \"0.0.3\";\n","/*! Depict PerformanceClient */\nimport { dlog } from \"@depict-ai/utilishared\";\n\nexport { PerformanceClient as DPC } from \"./PerformanceClient\";\n\nexport type { DepictQueue, DepictObject } from \"./types\";\n\nimport { version } from \"./version\";\nexport { version };\n\ndlog(\"@depict-ai/dpc version\", version);\n"],"names":[],"version":3,"file":"index.d.ts.map"}
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import $4uUHR$babelruntimehelpersclassPrivateFieldSet from "@babel/runtime/helpe
6
6
  /*! Depict PerformanceClient */
7
7
  import { register_es_version } from "../multi_import_deduplicator.mjs";
8
8
  register_es_version("performance-client", "ES10");
9
- const $3242b911de3d57ad$export$83d89fbfd8236492 = "1.0.43";
9
+ const $3242b911de3d57ad$export$83d89fbfd8236492 = "1.0.45";
10
10
  let $983195e3c4979825$export$8ae64f3d447c14f7;
11
11
  (function (ProductCardType) {
12
12
  ProductCardType[ProductCardType["Recommendation"] = 0] = "Recommendation";
package/dist/main.js ADDED
@@ -0,0 +1,4 @@
1
+ var e=require("@depict-ai/utilishared");function t(e,t,r,n){Object.defineProperty(e,t,{get:r,set:n,enumerable:!0,configurable:!0})}t(module.exports,"DPC",(()=>_)),t(module.exports,"version",(()=>g));
2
+ /*! Depict PerformanceClient */
3
+ const r=".depict-add-to-cart",n="[data-recommendation_id],[data-recommendation-id]";const i=(e,t)=>{if("string"!=typeof t)throw new Error(`${e} event requires a string as an argument`)},o=(e,t)=>{const r=window.depict.dpc;if("purchase"===e){if("object"!=typeof t||null===t)throw new Error("purchase event requires an object as an argument");if(!Array.isArray(t.products))throw new Error("purchase event requires a products array");if(!t.currency||"string"!=typeof t.currency)throw new Error("purchase event requires a currency string");if(!t.transaction_id||"string"!=typeof t.transaction_id)throw new Error("purchase event requires a transaction_id string");r.sendPurchaseEvent(t)}else"setMarket"===e?(i(e,t),r.setMarket(t)):"setProductId"===e?(i(e,t),r.setProductId(t)):"setUserId"===e&&(i(e,t),r.setUserId(t))},s=e=>{const t=window.dpq||=function(){const e=function(){const t=arguments;e.send_event?e.send_event.apply(this,t):e.queue.push(t)};return e.queue=[],e}(),r=window.depict||={};r.dpq=t,r.eventHistory=t.queue,r.dpc=e,t.send_event||(t.send_event=(e,r)=>{t.queue.push([e,r]),o(e,r)},t.queue.forEach((([e,t])=>{o(e,t)})))};function d(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var a=0;function c(e){return"__private_"+a+++"_"+e}var u=c("parseOptions"),h=c("getContextData"),m=c("sendTrackingEvent"),p=c("getProductId");class _{constructor(t,r){if(Object.defineProperty(this,p,{value:k}),Object.defineProperty(this,m,{value:f}),Object.defineProperty(this,h,{value:v}),Object.defineProperty(this,u,{value:l}),this.merchant=void 0,this.auto_observe=!0,this.market=void 0,this.latest_product_id=void 0,this.latest_product_id_path=void 0,this.latest_user_id=void 0,this.tracked_elements=new WeakSet,window.depict.dpc instanceof _)return(0,e.dlog)("DPC already initialized. Returning existing instance."),window.depict.dpc;s(this),this.merchant=t,d(this,u)[u](r),this.auto_observe&&(this.observeRecommendations(),this.observePDPA2CButton())}trackRecommendationCard(t){const n=t.dataset.recommendation_id;if(!n)return void(0,e.derror)("No recommendation_id found on card. Can't add tracking.",t);if(this.checkIfTracked(t))return;t.addEventListener("click",(()=>this.sendRecommendationClickEvent({recommendation_id:n}))),(0,e.impression_track_element)({element:t,data:{recommendation_id:n,...d(this,h)[h]()}});const i=t.querySelector(r);i&&this.trackAddToCartButton(i)}checkIfTracked(t){return this.tracked_elements.has(t)?((0,e.dlog)("Already tracked",t),!0):(this.tracked_elements.add(t),!1)}trackAddToCartButton(e){this.checkIfTracked(e)||e.addEventListener("click",(()=>{const t=e.closest(n)?.dataset.recommendation_id,r=d(this,p)[p]();this.sendAddToCartEvent({product_id:r,recommendation_id:t})}))}sendAddToCartEvent(e){d(this,m)[m]({type:"add_to_cart",...e})}sendRecommendationImpressionEvent({recommendation_id:e}){d(this,m)[m]({type:"element_visible",recommendation_id:e})}sendRecommendationClickEvent({recommendation_id:t}){(0,e.depict_click)({recommendation_id:t,...d(this,h)[h]()})}sendPurchaseEvent(t){if(!this.market)throw Error("Market not set");const r={events:[{event_type:"purchase",...t}],tenant:this.merchant,market:this.market};(0,e.foolproof_send_beacon)("https://api.depict.ai/v2/create-events",r)}setMarket(e){this.market=e}setProductId(t){(0,e.dlog)("Setting product id",t),this.latest_product_id=t,this.latest_product_id_path=location.pathname}setUserId(t){(0,e.dlog)("Setting user id",t),this.latest_user_id=t}observeRecommendations(){(0,e.dlog)("Starting to observe recommendations with selector",n),e.observer.onexists(n,(({element:t})=>{(0,e.dlog)("found recommendation",t),this.trackRecommendationCard(t)}))}observePDPA2CButton(){e.observer.onexists(r,(({element:t})=>{(0,e.dlog)("Found pdp add-to-cart button",t),this.trackAddToCartButton(t)}))}}function l(e){void 0!==e&&(void 0!==e.auto_observe&&(this.auto_observe=e.auto_observe),void 0!==e.market&&(this.market=e.market))}function v(){const t={market:this.market,tenant:this.merchant,user_id:this.latest_user_id};return{...(0,e.get_tracking_event_context_data)(),data:t}}function f(t){(0,e.send_depict_unfiltered)([{...t,...d(this,h)[h]()}],!0)}function k(){if(this.latest_product_id_path===location.pathname)return this.latest_product_id}const g="0.0.3";(0,e.dlog)("@depict-ai/dpc version",g);
4
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"mappings":";;AAAO,MAAMA,EAAe,sBACfC,EAA+B,oDCkB5C,MAAMC,EAAe,CAACC,EAAmBC,KACvC,GAAyB,iBAAdA,EACT,MAAM,IAAIC,MAAO,GAAEF,2CAAkD,EAOnEG,EAAgB,CAACH,EAAmBC,KACxC,MAAMG,EAAMC,OAAOC,OAAOF,IAC1B,GAAkB,aAAdJ,EAA0B,CAC5B,GAAyB,iBAAdC,GAAwC,OAAdA,EACnC,MAAM,IAAIC,MAAM,oDACX,IAAKK,MAAMC,QAAQP,E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AKyB,yBAA2BqC,SAASC,SAC7C,OAAO/D,KAAKwB,iBACd,CCrLK,MAAM+C,EAAU,SCUvB1C,UAAK,yBAA0B0C","sources":["packages/performance-client/selectors.ts","packages/performance-client/setup_dpq.ts","packages/performance-client/PerformanceClient.ts","packages/performance-client/version.ts","packages/performance-client/index_npm.ts"],"sourcesContent":["export const a2c_selector = \".depict-add-to-cart\";\nexport const recommendation_card_selector = \"[data-recommendation_id],[data-recommendation-id]\";\n","import { PerformanceClient } from \"./PerformanceClient\";\nimport { DepictObject } from \"./types\";\n\n/**\n * Creates an event queue (depict queue)\n */\nfunction create_dpq() {\n const fn: any = function () {\n const args = arguments;\n if (fn.send_event) {\n fn.send_event.apply(this, args);\n } else {\n fn.queue.push(args);\n }\n };\n fn.queue = [];\n return fn;\n}\n\nconst string_guard = (eventName: string, eventData: any) => {\n if (typeof eventData !== \"string\") {\n throw new Error(`${eventName} event requires a string as an argument`);\n }\n};\n\n/**\n * Handle events from dpq with the global dpc instance.\n */\nconst event_handler = (eventName: string, eventData: any) => {\n const dpc = window.depict.dpc;\n if (eventName === \"purchase\") {\n if (typeof eventData !== \"object\" || eventData === null) {\n throw new Error(\"purchase event requires an object as an argument\");\n } else if (!Array.isArray(eventData.products)) {\n throw new Error(\"purchase event requires a products array\");\n } else if (!eventData.currency || typeof eventData.currency !== \"string\") {\n throw new Error(\"purchase event requires a currency string\");\n } else if (!eventData.transaction_id || typeof eventData.transaction_id !== \"string\") {\n throw new Error(\"purchase event requires a transaction_id string\");\n }\n dpc.sendPurchaseEvent(eventData);\n } else if (eventName === \"setMarket\") {\n string_guard(eventName, eventData);\n dpc.setMarket(eventData);\n } else if (eventName === \"setProductId\") {\n string_guard(eventName, eventData);\n dpc.setProductId(eventData);\n } else if (eventName === \"setUserId\") {\n string_guard(eventName, eventData);\n dpc.setUserId(eventData);\n }\n};\n\n/**\n * Hooks up Depict Queue (dpq) to Depict Performance Client (dpc).\n * Creates dpq if it doesn't exist.\n */\nexport const setup_dpq = (dpc: PerformanceClient) => {\n const dpq = (window.dpq ||= create_dpq());\n const depict = (window.depict ||= {} as DepictObject);\n depict.dpq = dpq; // refrencing dpq into the depict object\n depict.eventHistory = dpq.queue; // making this more visible in the depict object\n depict.dpc = dpc;\n\n // Hook up the depict queue to the PerformanceClient\n if (!dpq.send_event) {\n dpq.send_event = (eventName: string, eventData: unknown) => {\n dpq.queue.push([eventName, eventData]); // push to queue as usual to keep history\n event_handler(eventName, eventData); // hand-over to the PerformanceClient\n };\n // Handle any events queued before this code ran.\n dpq.queue.forEach(([eventName, eventData]) => {\n event_handler(eventName, eventData);\n });\n }\n};\n","import {\n depict_body,\n depict_click,\n derror,\n dlog,\n foolproof_send_beacon,\n get_tracking_event_context_data,\n impression_track_element,\n observer,\n send_depict_unfiltered,\n} from \"@depict-ai/utilishared\";\nimport { PurchasedProduct, TrackV2Request } from \"@depict-ai/types/api/TrackV2Request\";\nimport { a2c_selector, recommendation_card_selector } from \"./selectors\";\nimport { setup_dpq } from \"./setup_dpq\";\n\nexport interface Options {\n /**\n * The initial market. Should be specified if the market is known at the point of intializing DPC.\n */\n market?: string;\n /**\n * If we should observe for recommendations on creation. If false, you must call `trackRecommendationCard` manually.\n */\n auto_observe?: boolean;\n}\nexport class PerformanceClient {\n merchant: string;\n auto_observe = true;\n market?: string;\n\n /** Latest product_id found in the DOM. Used in a2c & pageview events on PDPs. */\n latest_product_id?: string;\n /** The value of location.pathname when latest_product_id was set */\n latest_product_id_path?: string;\n /** Latest user_id found in the DOM. Used for all events. */\n latest_user_id?: string;\n\n constructor(merchant: string, options?: Options) {\n // Make sure we do not construct dpc more than once.\n if (window.depict.dpc instanceof PerformanceClient) {\n dlog(\"DPC already initialized. Returning existing instance.\");\n return window.depict.dpc;\n }\n setup_dpq(this);\n this.merchant = merchant;\n this.#parseOptions(options);\n if (this.auto_observe) {\n this.observeRecommendations();\n this.observePDPA2CButton();\n }\n }\n\n #parseOptions(options?: Options) {\n if (options !== undefined) {\n if (options.auto_observe !== undefined) {\n this.auto_observe = options.auto_observe;\n }\n if (options.market !== undefined) {\n this.market = options.market;\n }\n }\n }\n\n #getContextData() {\n const data = { market: this.market, tenant: this.merchant, user_id: this.latest_user_id };\n return { ...get_tracking_event_context_data(), data };\n }\n\n /**\n * Adds click and impression tracking to a recommendation card\n */\n trackRecommendationCard(card: HTMLElement) {\n const recommendation_id = card.dataset.recommendation_id;\n if (!recommendation_id) {\n derror(\"No recommendation_id found on card. Can't add tracking.\", card);\n return;\n }\n if (this.checkIfTracked(card)) return;\n card.addEventListener(\"click\", () => this.sendRecommendationClickEvent({ recommendation_id }));\n impression_track_element({\n element: card,\n data: { recommendation_id, ...this.#getContextData() },\n });\n\n // If the card has an optional a2c button, we track that as well.\n const a2c_button = card.querySelector<HTMLElement>(a2c_selector);\n if (a2c_button) this.trackAddToCartButton(a2c_button);\n }\n tracked_elements = new WeakSet<HTMLElement>();\n /**\n * Make sure the tracking is not set up twice on the same element.\n */\n checkIfTracked(element: HTMLElement) {\n if (this.tracked_elements.has(element)) {\n dlog(\"Already tracked\", element);\n return true;\n }\n this.tracked_elements.add(element);\n return false;\n }\n /**\n * Adds tracking to an Add to cart button.\n */\n trackAddToCartButton(button: HTMLElement) {\n if (this.checkIfTracked(button)) return;\n button.addEventListener(\"click\", () => {\n // If the button is nested in a recommendation, include the recommendation id.\n const recommendation_id = button.closest<HTMLElement>(recommendation_card_selector)?.dataset.recommendation_id;\n // If there exists a product_id on the page, we can send it with the event. This is for PDPs only.\n const product_id = this.#getProductId();\n this.sendAddToCartEvent({\n product_id,\n recommendation_id,\n });\n });\n }\n /**\n * Sends a tracking event to depict\n */\n #sendTrackingEvent(payload: depict_body) {\n // Todo. check consent. For some events, delay until consent decision, with possible timeout.\n // For others, decide immediately based on current consent. (We shouldn't track a long history of events from before the user consented)\n // If no consent, don't send at all, or send anonymous? I think the latter is valid, since no ID in cookie or localStorage.\n send_depict_unfiltered([{ ...payload, ...this.#getContextData() }], true);\n }\n /**\n * Sends an Add to Cart Event to depict\n */\n sendAddToCartEvent(data) {\n this.#sendTrackingEvent({ type: \"add_to_cart\", ...data });\n }\n /**\n * Sends an impression event to Depict\n */\n sendRecommendationImpressionEvent({ recommendation_id }: { recommendation_id: string }) {\n this.#sendTrackingEvent({ type: \"element_visible\", recommendation_id });\n }\n /**\n * Sends a recommendation click event to Depict\n */\n sendRecommendationClickEvent({ recommendation_id }: { recommendation_id: string }) {\n depict_click({ recommendation_id, ...this.#getContextData() });\n }\n /**\n * Sends a Purchase Event to Depict\n */\n sendPurchaseEvent(data: { transaction_id: string; currency: string; products: PurchasedProduct[] }) {\n if (!this.market) {\n throw Error(\"Market not set\");\n }\n\n const request: TrackV2Request = {\n events: [\n {\n event_type: \"purchase\",\n ...data,\n },\n ],\n tenant: this.merchant,\n market: this.market,\n };\n\n foolproof_send_beacon(process.env.BASE_URL + \"/v2/create-events\", request);\n }\n /**\n * Update the market used for tracking events\n */\n setMarket(market: string) {\n this.market = market;\n }\n /**\n * Update the product_id used for add-to-cart and pageview events on PDPs.\n */\n setProductId(product_id: string) {\n dlog(\"Setting product id\", product_id);\n this.latest_product_id = product_id;\n this.latest_product_id_path = location.pathname;\n }\n #getProductId() {\n if (this.latest_product_id_path !== location.pathname) return undefined;\n return this.latest_product_id;\n }\n /**\n * Set the user_id for logged in users.\n *\n * https://docs.depict.ai/docs/performance-client#informing-depict-of-logged-in-users\n */\n setUserId(user_id: string) {\n dlog(\"Setting user id\", user_id);\n this.latest_user_id = user_id;\n }\n /**\n * Observe the dom for recommendations to track\n */\n observeRecommendations() {\n dlog(\"Starting to observe recommendations with selector\", recommendation_card_selector);\n observer.onexists(recommendation_card_selector, ({ element }) => {\n // I think we'll have to search for \"parent\"/\"container\" elements first, which should contain the surface/rectype name.\n // Then it's easier to dedup cards and get their index as well.\n dlog(\"found recommendation\", element);\n this.trackRecommendationCard(element);\n });\n }\n /**\n * Observe the dom for add to cart buttons. Used on product detail pages.\n */\n observePDPA2CButton() {\n const handler = ({ element }) => {\n dlog(\"Found pdp add-to-cart button\", element);\n this.trackAddToCartButton(element);\n };\n observer.onexists(a2c_selector, handler);\n }\n}\n","export const version = \"0.0.3\";\n","/*! Depict PerformanceClient */\nimport { dlog } from \"@depict-ai/utilishared\";\n\nexport { PerformanceClient as DPC } from \"./PerformanceClient\";\n\nexport type { DepictQueue, DepictObject } from \"./types\";\n\nimport { version } from \"./version\";\nexport { version };\n\ndlog(\"@depict-ai/dpc version\", version);\n"],"names":["a2c_selector","recommendation_card_selector","string_guard","eventName","eventData","Error","event_handler","dpc","window","depict","Array","isArray","products","currency","transaction_id","sendPurchaseEvent","setMarket","setProductId","setUserId","setup_dpq","dpq","fn","args","arguments","send_event","apply","this","queue","push","create_dpq","eventHistory","forEach","$5b1b25903ea9d665$var$_parseOptions","$5b1b25903ea9d665$var$_classPrivateFieldLooseKey","$5b1b25903ea9d665$var$_getContextData","$5b1b25903ea9d665$var$_sendTrackingEvent","$5b1b25903ea9d665$var$_getProductId","PerformanceClient","constructor","merchant","options","Object","defineProperty","value","$5b1b25903ea9d665$var$_getProductId2","$5b1b25903ea9d665$var$_sendTrackingEvent2","$5b1b25903ea9d665$var$_getContextData2","$5b1b25903ea9d665$var$_parseOptions2","auto_observe","market","latest_product_id","latest_product_id_path","latest_user_id","tracked_elements","WeakSet","dlog","$5b1b25903ea9d665$var$_classPrivateFieldLooseBase","observeRecommendations","observePDPA2CButton","trackRecommendationCard","card","recommendation_id","dataset","derror","checkIfTracked","addEventListener","sendRecommendationClickEvent","impression_track_element","element","data","a2c_button","querySelector","trackAddToCartButton","has","add","button","closest","product_id","sendAddToCartEvent","type","sendRecommendationImpressionEvent","depict_click","request","events","event_type","tenant","foolproof_send_beacon","process","location","pathname","user_id","observer","onexists","undefined","get_tracking_event_context_data","payload","send_depict_unfiltered","version"],"version":3,"file":"main.js.map"}
package/dist/module.js ADDED
@@ -0,0 +1,3 @@
1
+ import{dlog as t,derror as e,impression_track_element as r,depict_click as n,foolproof_send_beacon as i,observer as s,get_tracking_event_context_data as o,send_depict_unfiltered as a}from"@depict-ai/utilishared";
2
+ /*! Depict PerformanceClient */const d=".depict-add-to-cart",c="[data-recommendation_id],[data-recommendation-id]";const u=(t,e)=>{if("string"!=typeof e)throw new Error(`${t} event requires a string as an argument`)},h=(t,e)=>{const r=window.depict.dpc;if("purchase"===t){if("object"!=typeof e||null===e)throw new Error("purchase event requires an object as an argument");if(!Array.isArray(e.products))throw new Error("purchase event requires a products array");if(!e.currency||"string"!=typeof e.currency)throw new Error("purchase event requires a currency string");if(!e.transaction_id||"string"!=typeof e.transaction_id)throw new Error("purchase event requires a transaction_id string");r.sendPurchaseEvent(e)}else"setMarket"===t?(u(t,e),r.setMarket(e)):"setProductId"===t?(u(t,e),r.setProductId(e)):"setUserId"===t&&(u(t,e),r.setUserId(e))},m=t=>{const e=window.dpq||=function(){const t=function(){const e=arguments;t.send_event?t.send_event.apply(this,e):t.queue.push(e)};return t.queue=[],t}(),r=window.depict||={};r.dpq=e,r.eventHistory=e.queue,r.dpc=t,e.send_event||(e.send_event=(t,r)=>{e.queue.push([t,r]),h(t,r)},e.queue.forEach((([t,e])=>{h(t,e)})))};function p(t,e){if(!Object.prototype.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var _=0;function v(t){return"__private_"+_+++"_"+t}var l=v("parseOptions"),f=v("getContextData"),k=v("sendTrackingEvent"),w=v("getProductId");class y{constructor(e,r){if(Object.defineProperty(this,w,{value:P}),Object.defineProperty(this,k,{value:E}),Object.defineProperty(this,f,{value:g}),Object.defineProperty(this,l,{value:b}),this.merchant=void 0,this.auto_observe=!0,this.market=void 0,this.latest_product_id=void 0,this.latest_product_id_path=void 0,this.latest_user_id=void 0,this.tracked_elements=new WeakSet,window.depict.dpc instanceof y)return t("DPC already initialized. Returning existing instance."),window.depict.dpc;m(this),this.merchant=e,p(this,l)[l](r),this.auto_observe&&(this.observeRecommendations(),this.observePDPA2CButton())}trackRecommendationCard(t){const n=t.dataset.recommendation_id;if(!n)return void e("No recommendation_id found on card. Can't add tracking.",t);if(this.checkIfTracked(t))return;t.addEventListener("click",(()=>this.sendRecommendationClickEvent({recommendation_id:n}))),r({element:t,data:{recommendation_id:n,...p(this,f)[f]()}});const i=t.querySelector(d);i&&this.trackAddToCartButton(i)}checkIfTracked(e){return this.tracked_elements.has(e)?(t("Already tracked",e),!0):(this.tracked_elements.add(e),!1)}trackAddToCartButton(t){this.checkIfTracked(t)||t.addEventListener("click",(()=>{const e=t.closest(c)?.dataset.recommendation_id,r=p(this,w)[w]();this.sendAddToCartEvent({product_id:r,recommendation_id:e})}))}sendAddToCartEvent(t){p(this,k)[k]({type:"add_to_cart",...t})}sendRecommendationImpressionEvent({recommendation_id:t}){p(this,k)[k]({type:"element_visible",recommendation_id:t})}sendRecommendationClickEvent({recommendation_id:t}){n({recommendation_id:t,...p(this,f)[f]()})}sendPurchaseEvent(t){if(!this.market)throw Error("Market not set");const e={events:[{event_type:"purchase",...t}],tenant:this.merchant,market:this.market};i("https://api.depict.ai/v2/create-events",e)}setMarket(t){this.market=t}setProductId(e){t("Setting product id",e),this.latest_product_id=e,this.latest_product_id_path=location.pathname}setUserId(e){t("Setting user id",e),this.latest_user_id=e}observeRecommendations(){t("Starting to observe recommendations with selector",c),s.onexists(c,(({element:e})=>{t("found recommendation",e),this.trackRecommendationCard(e)}))}observePDPA2CButton(){s.onexists(d,(({element:e})=>{t("Found pdp add-to-cart button",e),this.trackAddToCartButton(e)}))}}function b(t){void 0!==t&&(void 0!==t.auto_observe&&(this.auto_observe=t.auto_observe),void 0!==t.market&&(this.market=t.market))}function g(){const t={market:this.market,tenant:this.merchant,user_id:this.latest_user_id};return{...o(),data:t}}function E(t){a([{...t,...p(this,f)[f]()}],!0)}function P(){if(this.latest_product_id_path===location.pathname)return this.latest_product_id}const C="0.0.3";t("@depict-ai/dpc version",C);export{y as DPC,C as version};
3
+ //# sourceMappingURL=module.js.map
@@ -0,0 +1 @@
1
+ {"mappings":";+B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AQS,SACVvB,KAAKuB,OAAST,EAAQS,QAG5B,CAAC,SAAAH,IAGC,MAAMuB,EAAO,CAAEpB,OAAQvB,KAAKuB,OAAQoC,OAAQ3D,KAAKa,SAAUmD,QAAShE,KAAK0B,gBACzE,MAAO,IAAK0C,I,KAAmCzB,EACjD,CAAC,SAAAxB,EAqDkBkD,GAIjBC,EAAuB,CAAC,IAAKD,KAASvC,EAAG9B,KAAHQ,WAA8B,EACtE,CAAC,SAAAU,IAuDC,GAAIlB,KAAKyB,yBAA2BqC,SAASC,SAC7C,OAAO/D,KAAKwB,iBACd,CCrLK,MAAM+C,EAAU,QCUvB1C,EAAK,yBAA0B0C,U","sources":["packages/performance-client/selectors.ts","packages/performance-client/setup_dpq.ts","packages/performance-client/PerformanceClient.ts","packages/performance-client/version.ts","packages/performance-client/index_npm.ts"],"sourcesContent":["export const a2c_selector = \".depict-add-to-cart\";\nexport const recommendation_card_selector = \"[data-recommendation_id],[data-recommendation-id]\";\n","import { PerformanceClient } from \"./PerformanceClient\";\nimport { DepictObject } from \"./types\";\n\n/**\n * Creates an event queue (depict queue)\n */\nfunction create_dpq() {\n const fn: any = function () {\n const args = arguments;\n if (fn.send_event) {\n fn.send_event.apply(this, args);\n } else {\n fn.queue.push(args);\n }\n };\n fn.queue = [];\n return fn;\n}\n\nconst string_guard = (eventName: string, eventData: any) => {\n if (typeof eventData !== \"string\") {\n throw new Error(`${eventName} event requires a string as an argument`);\n }\n};\n\n/**\n * Handle events from dpq with the global dpc instance.\n */\nconst event_handler = (eventName: string, eventData: any) => {\n const dpc = window.depict.dpc;\n if (eventName === \"purchase\") {\n if (typeof eventData !== \"object\" || eventData === null) {\n throw new Error(\"purchase event requires an object as an argument\");\n } else if (!Array.isArray(eventData.products)) {\n throw new Error(\"purchase event requires a products array\");\n } else if (!eventData.currency || typeof eventData.currency !== \"string\") {\n throw new Error(\"purchase event requires a currency string\");\n } else if (!eventData.transaction_id || typeof eventData.transaction_id !== \"string\") {\n throw new Error(\"purchase event requires a transaction_id string\");\n }\n dpc.sendPurchaseEvent(eventData);\n } else if (eventName === \"setMarket\") {\n string_guard(eventName, eventData);\n dpc.setMarket(eventData);\n } else if (eventName === \"setProductId\") {\n string_guard(eventName, eventData);\n dpc.setProductId(eventData);\n } else if (eventName === \"setUserId\") {\n string_guard(eventName, eventData);\n dpc.setUserId(eventData);\n }\n};\n\n/**\n * Hooks up Depict Queue (dpq) to Depict Performance Client (dpc).\n * Creates dpq if it doesn't exist.\n */\nexport const setup_dpq = (dpc: PerformanceClient) => {\n const dpq = (window.dpq ||= create_dpq());\n const depict = (window.depict ||= {} as DepictObject);\n depict.dpq = dpq; // refrencing dpq into the depict object\n depict.eventHistory = dpq.queue; // making this more visible in the depict object\n depict.dpc = dpc;\n\n // Hook up the depict queue to the PerformanceClient\n if (!dpq.send_event) {\n dpq.send_event = (eventName: string, eventData: unknown) => {\n dpq.queue.push([eventName, eventData]); // push to queue as usual to keep history\n event_handler(eventName, eventData); // hand-over to the PerformanceClient\n };\n // Handle any events queued before this code ran.\n dpq.queue.forEach(([eventName, eventData]) => {\n event_handler(eventName, eventData);\n });\n }\n};\n","import {\n depict_body,\n depict_click,\n derror,\n dlog,\n foolproof_send_beacon,\n get_tracking_event_context_data,\n impression_track_element,\n observer,\n send_depict_unfiltered,\n} from \"@depict-ai/utilishared\";\nimport { PurchasedProduct, TrackV2Request } from \"@depict-ai/types/api/TrackV2Request\";\nimport { a2c_selector, recommendation_card_selector } from \"./selectors\";\nimport { setup_dpq } from \"./setup_dpq\";\n\nexport interface Options {\n /**\n * The initial market. Should be specified if the market is known at the point of intializing DPC.\n */\n market?: string;\n /**\n * If we should observe for recommendations on creation. If false, you must call `trackRecommendationCard` manually.\n */\n auto_observe?: boolean;\n}\nexport class PerformanceClient {\n merchant: string;\n auto_observe = true;\n market?: string;\n\n /** Latest product_id found in the DOM. Used in a2c & pageview events on PDPs. */\n latest_product_id?: string;\n /** The value of location.pathname when latest_product_id was set */\n latest_product_id_path?: string;\n /** Latest user_id found in the DOM. Used for all events. */\n latest_user_id?: string;\n\n constructor(merchant: string, options?: Options) {\n // Make sure we do not construct dpc more than once.\n if (window.depict.dpc instanceof PerformanceClient) {\n dlog(\"DPC already initialized. Returning existing instance.\");\n return window.depict.dpc;\n }\n setup_dpq(this);\n this.merchant = merchant;\n this.#parseOptions(options);\n if (this.auto_observe) {\n this.observeRecommendations();\n this.observePDPA2CButton();\n }\n }\n\n #parseOptions(options?: Options) {\n if (options !== undefined) {\n if (options.auto_observe !== undefined) {\n this.auto_observe = options.auto_observe;\n }\n if (options.market !== undefined) {\n this.market = options.market;\n }\n }\n }\n\n #getContextData() {\n const data = { market: this.market, tenant: this.merchant, user_id: this.latest_user_id };\n return { ...get_tracking_event_context_data(), data };\n }\n\n /**\n * Adds click and impression tracking to a recommendation card\n */\n trackRecommendationCard(card: HTMLElement) {\n const recommendation_id = card.dataset.recommendation_id;\n if (!recommendation_id) {\n derror(\"No recommendation_id found on card. Can't add tracking.\", card);\n return;\n }\n if (this.checkIfTracked(card)) return;\n card.addEventListener(\"click\", () => this.sendRecommendationClickEvent({ recommendation_id }));\n impression_track_element({\n element: card,\n data: { recommendation_id, ...this.#getContextData() },\n });\n\n // If the card has an optional a2c button, we track that as well.\n const a2c_button = card.querySelector<HTMLElement>(a2c_selector);\n if (a2c_button) this.trackAddToCartButton(a2c_button);\n }\n tracked_elements = new WeakSet<HTMLElement>();\n /**\n * Make sure the tracking is not set up twice on the same element.\n */\n checkIfTracked(element: HTMLElement) {\n if (this.tracked_elements.has(element)) {\n dlog(\"Already tracked\", element);\n return true;\n }\n this.tracked_elements.add(element);\n return false;\n }\n /**\n * Adds tracking to an Add to cart button.\n */\n trackAddToCartButton(button: HTMLElement) {\n if (this.checkIfTracked(button)) return;\n button.addEventListener(\"click\", () => {\n // If the button is nested in a recommendation, include the recommendation id.\n const recommendation_id = button.closest<HTMLElement>(recommendation_card_selector)?.dataset.recommendation_id;\n // If there exists a product_id on the page, we can send it with the event. This is for PDPs only.\n const product_id = this.#getProductId();\n this.sendAddToCartEvent({\n product_id,\n recommendation_id,\n });\n });\n }\n /**\n * Sends a tracking event to depict\n */\n #sendTrackingEvent(payload: depict_body) {\n // Todo. check consent. For some events, delay until consent decision, with possible timeout.\n // For others, decide immediately based on current consent. (We shouldn't track a long history of events from before the user consented)\n // If no consent, don't send at all, or send anonymous? I think the latter is valid, since no ID in cookie or localStorage.\n send_depict_unfiltered([{ ...payload, ...this.#getContextData() }], true);\n }\n /**\n * Sends an Add to Cart Event to depict\n */\n sendAddToCartEvent(data) {\n this.#sendTrackingEvent({ type: \"add_to_cart\", ...data });\n }\n /**\n * Sends an impression event to Depict\n */\n sendRecommendationImpressionEvent({ recommendation_id }: { recommendation_id: string }) {\n this.#sendTrackingEvent({ type: \"element_visible\", recommendation_id });\n }\n /**\n * Sends a recommendation click event to Depict\n */\n sendRecommendationClickEvent({ recommendation_id }: { recommendation_id: string }) {\n depict_click({ recommendation_id, ...this.#getContextData() });\n }\n /**\n * Sends a Purchase Event to Depict\n */\n sendPurchaseEvent(data: { transaction_id: string; currency: string; products: PurchasedProduct[] }) {\n if (!this.market) {\n throw Error(\"Market not set\");\n }\n\n const request: TrackV2Request = {\n events: [\n {\n event_type: \"purchase\",\n ...data,\n },\n ],\n tenant: this.merchant,\n market: this.market,\n };\n\n foolproof_send_beacon(process.env.BASE_URL + \"/v2/create-events\", request);\n }\n /**\n * Update the market used for tracking events\n */\n setMarket(market: string) {\n this.market = market;\n }\n /**\n * Update the product_id used for add-to-cart and pageview events on PDPs.\n */\n setProductId(product_id: string) {\n dlog(\"Setting product id\", product_id);\n this.latest_product_id = product_id;\n this.latest_product_id_path = location.pathname;\n }\n #getProductId() {\n if (this.latest_product_id_path !== location.pathname) return undefined;\n return this.latest_product_id;\n }\n /**\n * Set the user_id for logged in users.\n *\n * https://docs.depict.ai/docs/performance-client#informing-depict-of-logged-in-users\n */\n setUserId(user_id: string) {\n dlog(\"Setting user id\", user_id);\n this.latest_user_id = user_id;\n }\n /**\n * Observe the dom for recommendations to track\n */\n observeRecommendations() {\n dlog(\"Starting to observe recommendations with selector\", recommendation_card_selector);\n observer.onexists(recommendation_card_selector, ({ element }) => {\n // I think we'll have to search for \"parent\"/\"container\" elements first, which should contain the surface/rectype name.\n // Then it's easier to dedup cards and get their index as well.\n dlog(\"found recommendation\", element);\n this.trackRecommendationCard(element);\n });\n }\n /**\n * Observe the dom for add to cart buttons. Used on product detail pages.\n */\n observePDPA2CButton() {\n const handler = ({ element }) => {\n dlog(\"Found pdp add-to-cart button\", element);\n this.trackAddToCartButton(element);\n };\n observer.onexists(a2c_selector, handler);\n }\n}\n","export const version = \"0.0.3\";\n","/*! Depict PerformanceClient */\nimport { dlog } from \"@depict-ai/utilishared\";\n\nexport { PerformanceClient as DPC } from \"./PerformanceClient\";\n\nexport type { DepictQueue, DepictObject } from \"./types\";\n\nimport { version } from \"./version\";\nexport { version };\n\ndlog(\"@depict-ai/dpc version\", version);\n"],"names":["a2c_selector","recommendation_card_selector","string_guard","eventName","eventData","Error","event_handler","dpc","window","depict","Array","isArray","products","currency","transaction_id","sendPurchaseEvent","setMarket","setProductId","setUserId","setup_dpq","dpq","fn","args","arguments","send_event","apply","this","queue","push","create_dpq","eventHistory","forEach","$20a7a3e3dcebf2c1$var$_parseOptions","$20a7a3e3dcebf2c1$var$_classPrivateFieldLooseKey","$20a7a3e3dcebf2c1$var$_getContextData","$20a7a3e3dcebf2c1$var$_sendTrackingEvent","$20a7a3e3dcebf2c1$var$_getProductId","PerformanceClient","constructor","merchant","options","Object","defineProperty","value","$20a7a3e3dcebf2c1$var$_getProductId2","$20a7a3e3dcebf2c1$var$_sendTrackingEvent2","$20a7a3e3dcebf2c1$var$_getContextData2","$20a7a3e3dcebf2c1$var$_parseOptions2","auto_observe","market","latest_product_id","latest_product_id_path","latest_user_id","tracked_elements","WeakSet","dlog","$20a7a3e3dcebf2c1$var$_classPrivateFieldLooseBase","observeRecommendations","observePDPA2CButton","trackRecommendationCard","card","recommendation_id","dataset","derror","checkIfTracked","addEventListener","sendRecommendationClickEvent","impression_track_element","element","data","a2c_button","querySelector","trackAddToCartButton","has","add","button","closest","product_id","sendAddToCartEvent","type","sendRecommendationImpressionEvent","depict_click","request","events","event_type","tenant","foolproof_send_beacon","process","location","pathname","user_id","observer","onexists","undefined","get_tracking_event_context_data","payload","send_depict_unfiltered","version"],"version":3,"file":"module.js.map"}
package/latest/index.cjs CHANGED
@@ -11,7 +11,7 @@ function $parcel$export(e, n, v, s) {
11
11
  $parcel$export(module.exports, "DPC", () => $15e3eebad2263636$export$820526014323765f);
12
12
  $parcel$export(module.exports, "version", () => $9c6b4a5c4c4f318d$export$83d89fbfd8236492);
13
13
  /*! Depict PerformanceClient */
14
- const $9c6b4a5c4c4f318d$export$83d89fbfd8236492 = "1.0.43";
14
+ const $9c6b4a5c4c4f318d$export$83d89fbfd8236492 = "1.0.45";
15
15
  let $02e69dba644a2ef8$export$8ae64f3d447c14f7;
16
16
  (function (ProductCardType) {
17
17
  ProductCardType[ProductCardType["Recommendation"] = 0] = "Recommendation";
package/latest/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const version = "1.0.43";
1
+ export const version = "1.0.45";
2
2
  enum ProductCardType {
3
3
  Recommendation = 0,
4
4
  SnakeRecommendation = 1,
package/latest/index.js CHANGED
@@ -3,7 +3,7 @@ import { add_to_version_info as $lbGMC$add_to_version_info, dlog as $lbGMC$dlog,
3
3
  /*! Depict PerformanceClient */
4
4
  import { register_es_version } from "../multi_import_deduplicator.mjs";
5
5
  register_es_version("performance-client", "latest");
6
- const $3b068891cefe570d$export$83d89fbfd8236492 = "1.0.43";
6
+ const $3b068891cefe570d$export$83d89fbfd8236492 = "1.0.45";
7
7
  let $ba8dc1a552d27224$export$8ae64f3d447c14f7;
8
8
  (function (ProductCardType) {
9
9
  ProductCardType[ProductCardType["Recommendation"] = 0] = "Recommendation";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@depict-ai/dpc",
3
- "version": "1.0.43",
3
+ "version": "1.0.45",
4
4
  "packageManager": "yarn@3.2.2",
5
5
  "source": "./src/index.ts",
6
6
  "types": "ES10/index.d.ts",
@@ -92,8 +92,8 @@
92
92
  "@babel/plugin-transform-typescript": "^7.22.9",
93
93
  "@babel/runtime": "latest",
94
94
  "@babel/runtime-corejs3": "^7.22.6",
95
- "@depict-ai/types": "^1.0.39",
96
- "@depict-ai/utilishared": "^1.0.49"
95
+ "@depict-ai/types": "^4.0.0",
96
+ "@depict-ai/utilishared": "^1.0.51"
97
97
  },
98
98
  "main": "ES10/index.cjs",
99
99
  "module": "ES10/index.js"