@blotoutio/providers-evo-search-sdk 1.70.2 → 1.71.1

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/core.mjs CHANGED
@@ -815,6 +815,16 @@ const uiActions = new Set([
815
815
  'evoSearchProductAddedToCart',
816
816
  'evoSearchProductPurchased',
817
817
  'evoSearchSearchIssued',
818
+ // Relevance-telemetry pair (PR2 task 3): one impressions beacon per
819
+ // finalized query, one click beacon per result click. Server handling
820
+ // (Task 4) wired in routes/user.ts.
821
+ 'evoSearchImpressions',
822
+ 'evoSearchResultClick',
823
+ // One beacon per Ask answer the assistant could not produce (generation
824
+ // failure, budget exhaustion) — the client-side counterpart to the worker's
825
+ // own degrade counters, and the only signal for a failure the worker never
826
+ // sees (the request never reaching it).
827
+ 'evoSearchAskDegraded',
818
828
  ]);
819
829
  new Set([...uiActions]);
820
830
 
@@ -852,6 +862,172 @@ const logger = {
852
862
  },
853
863
  };
854
864
 
865
+ // Pure, DOM-free session-context logic: what the shopper's tab has seen this
866
+ // visit, kept small enough to ride along on every search request as a `ctx`
867
+ // query param and every finalized-query beacon. No PII — ids, capped query
868
+ // strings, and an enum page type only. Storage wiring (sessionStorage
869
+ // read/write, entry page detection from location.pathname) lives in
870
+ // utils.ts; this module only knows how to grow and shrink the shape
871
+ // immutably, and how to encode it for the wire.
872
+ // Single source of truth for the enum — utils.ts's sessionStorage parse
873
+ // validates membership against this (not just `typeof === 'string'`) before
874
+ // trusting a stored value, so a hostile/corrupted entry can't smuggle an
875
+ // arbitrary string into the wire payload.
876
+ const PAGE_TYPES = [
877
+ 'home',
878
+ 'plp',
879
+ 'pdp',
880
+ 'cart',
881
+ 'search',
882
+ 'other',
883
+ ];
884
+ const isPageType = (value) => typeof value === 'string' && PAGE_TYPES.includes(value);
885
+ const MAX_VIEWED = 20;
886
+ // A product id longer than this is not an id any catalog issues; it is a
887
+ // runaway string that would eat the whole byte budget on one entry. Mirrors
888
+ // the decoder's own per-id cap, which DROPS (never truncates) an oversized
889
+ // id — a truncated id silently becomes a different, wrong product.
890
+ const MAX_PRODUCT_ID_CHARS = 64;
891
+ // The platform's global-id form for a product. Hosts hand us whichever form
892
+ // their storefront layer has to hand; the catalog is keyed on the bare id, so
893
+ // normalize here rather than making every caller remember which one to pass.
894
+ const GLOBAL_ID_PREFIX = 'gid://shopify/Product/';
895
+ /**
896
+ * Coerces a caller-supplied product id into the id space the catalog uses, or
897
+ * null when it cannot be one. Accepts a number (storefront globals expose the
898
+ * id numerically) or a string, tolerates the platform's global-id form, and
899
+ * rejects empty/oversized values rather than putting an id on the wire that
900
+ * can never resolve.
901
+ */
902
+ const normalizeProductId = (value) => {
903
+ const raw = typeof value === 'number' && Number.isFinite(value)
904
+ ? String(value)
905
+ : typeof value === 'string'
906
+ ? value.trim()
907
+ : '';
908
+ const id = raw.startsWith(GLOBAL_ID_PREFIX)
909
+ ? raw.slice(GLOBAL_ID_PREFIX.length)
910
+ : raw;
911
+ if (!id || id.length > MAX_PRODUCT_ID_CHARS) {
912
+ return null;
913
+ }
914
+ return id;
915
+ };
916
+ // Hard cap enforced by serializeContext, measured in ENCODED UTF-8 BYTES —
917
+ // `.length` counts UTF-16 code units, which undercounts CJK/emoji text by up
918
+ // to 3x. Kept in sync with the `ctx` query param budget documented in the
919
+ // PR2 brief (base64url grows this ~4/3, so ~2.7KB encoded — comfortably
920
+ // inside URL limits).
921
+ const MAX_SERIALIZED_BYTES = 2048;
922
+ const pushViewed = (ctx, id) => ({
923
+ ...ctx,
924
+ viewed: [id, ...ctx.viewed.filter((viewedId) => viewedId !== id)].slice(0, MAX_VIEWED),
925
+ });
926
+ // Drops entries from the tail (pushViewed/pushQuery keep newest-first) until
927
+ // the ENCODED byte length fits the hard cap, in order of how much each byte
928
+ // is worth: the browse list first (its tail is the least recent thing the
929
+ // shopper looked at, and it is the longest list), then the cart, then the
930
+ // queries — fewest entries and the most intent per byte, so they yield last
931
+ // but are not exempt: five 200-char CJK queries alone encode to ~3KB, so a
932
+ // character-bounded list can still blow a byte budget.
933
+ const serializeContext = (ctx) => {
934
+ let working = {
935
+ ...ctx,
936
+ viewed: [...ctx.viewed],
937
+ cart: [...ctx.cart],
938
+ queries: [...ctx.queries],
939
+ };
940
+ let serialized = JSON.stringify(working);
941
+ while (textEncoder.encode(serialized).length > MAX_SERIALIZED_BYTES &&
942
+ (working.viewed.length > 0 ||
943
+ working.cart.length > 0 ||
944
+ working.queries.length > 0)) {
945
+ working =
946
+ working.viewed.length > 0
947
+ ? { ...working, viewed: working.viewed.slice(0, -1) }
948
+ : working.cart.length > 0
949
+ ? { ...working, cart: working.cart.slice(0, -1) }
950
+ : { ...working, queries: working.queries.slice(0, -1) };
951
+ serialized = JSON.stringify(working);
952
+ }
953
+ return serialized;
954
+ };
955
+ // Detected once per session from the entry URL — home/plp/pdp/cart by path
956
+ // shape, everything else is 'other'. Pure so it's testable alongside the
957
+ // rest of this module; utils.ts calls it exactly once, on first read.
958
+ const detectEntryPage = (pathname) => {
959
+ if (pathname === '/') {
960
+ return 'home';
961
+ }
962
+ if (pathname.startsWith('/products/')) {
963
+ return 'pdp';
964
+ }
965
+ if (pathname.startsWith('/collections/')) {
966
+ return 'plp';
967
+ }
968
+ if (pathname.startsWith('/cart')) {
969
+ return 'cart';
970
+ }
971
+ return 'other';
972
+ };
973
+ // Native TextEncoder + btoa, same as the CDN sibling's utils/user-auth.ts —
974
+ // jsdom's missing TextEncoder is a test-environment gap, polyfilled in
975
+ // jest.setup.ts rather than worked around in shipped code.
976
+ const textEncoder = new TextEncoder();
977
+ const toBase64Url = (bytes) => {
978
+ let bin = '';
979
+ for (let i = 0; i < bytes.length; i++) {
980
+ bin += String.fromCharCode(bytes[i]);
981
+ }
982
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
983
+ };
984
+ // Wire form for the `ctx` search query param: base64url(serializeContext(ctx)),
985
+ // no padding. Returns null when there's nothing worth the extra URL bytes —
986
+ // a context with no viewed products, cart lines or past queries yet (e.g. the very
987
+ // first search of a fresh tab) — so a brand-new session doesn't pay for a
988
+ // param carrying only the entryPage enum.
989
+ const encodeContextParam = (ctx) => {
990
+ if (ctx.viewed.length === 0 &&
991
+ ctx.cart.length === 0 &&
992
+ ctx.queries.length === 0) {
993
+ return null;
994
+ }
995
+ return toBase64Url(textEncoder.encode(serializeContext(ctx)));
996
+ };
997
+
998
+ // `crypto.randomUUID` is secure-context-only: on an `http://` storefront it is
999
+ // undefined and calling it throws a TypeError. Called bare, that threw from
1000
+ // inside the autocomplete and image-search render paths — after results were
1001
+ // already assigned — so the catch cleared them and the shopper saw an error
1002
+ // state for a working search. `crypto.getRandomValues` has no such
1003
+ // restriction, so it carries the fallback; Math.random is the last resort for
1004
+ // an environment with no crypto at all. The output stays RFC4122-v4 shaped
1005
+ // either way, because the worker's beacon validators reject anything else.
1006
+ const randomBytes16 = () => {
1007
+ const bytes = new Uint8Array(16);
1008
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
1009
+ crypto.getRandomValues(bytes);
1010
+ return bytes;
1011
+ }
1012
+ for (let i = 0; i < bytes.length; i++) {
1013
+ bytes[i] = Math.floor(Math.random() * 256);
1014
+ }
1015
+ return bytes;
1016
+ };
1017
+ const mintId = () => {
1018
+ var _a, _b;
1019
+ if (typeof crypto !== 'undefined' &&
1020
+ typeof crypto.randomUUID === 'function') {
1021
+ return crypto.randomUUID();
1022
+ }
1023
+ const bytes = randomBytes16();
1024
+ // Version 4, variant 10xx — the two bits the shape check would otherwise
1025
+ // read as a malformed id.
1026
+ bytes[6] = (((_a = bytes[6]) !== null && _a !== void 0 ? _a : 0) & 0x0f) | 0x40;
1027
+ bytes[8] = (((_b = bytes[8]) !== null && _b !== void 0 ? _b : 0) & 0x3f) | 0x80;
1028
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
1029
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1030
+ };
855
1031
  // Intentionally duplicated from @blotoutio/providers/evo-search/config to keep the hooks bundle lean — importing from the config barrel pulls the shared/universal geo data into dist/hooks.mjs (~4KB gzipped). Drift between the two values is caught by utils.test.ts.
856
1032
  const previewKeyName = 'previewEvoSearch';
857
1033
  const hasPreviewKey = () => {
@@ -876,6 +1052,101 @@ const hasDisableKey = () => {
876
1052
  return false;
877
1053
  }
878
1054
  };
1055
+ // Cross-widget, cross-search shopper context (recently viewed products,
1056
+ // finalized queries, entry page) that rides along on every search
1057
+ // request as a `ctx` query param and every finalized-query beacon, so
1058
+ // ranking/telemetry can see the visit's shape without the worker
1059
+ // maintaining its own session. A query param, not a header, so /search
1060
+ // stays a CORS-simple request (no preflight on the per-keystroke hot path).
1061
+ // sessionStorage-scoped like the rest of this file's keys: it dies with the
1062
+ // tab and never needs a retention policy. No PII — see session-context.ts.
1063
+ const sessionContextKeyName = 'evoSearchSessionContext';
1064
+ const emptySessionContext = () => ({
1065
+ viewed: [],
1066
+ cart: [],
1067
+ queries: [],
1068
+ entryPage: detectEntryPage(typeof window !== 'undefined' ? window.location.pathname : ''),
1069
+ });
1070
+ const getSessionContext = () => {
1071
+ try {
1072
+ const raw = sessionStorage.getItem(sessionContextKeyName);
1073
+ if (raw) {
1074
+ const parsed = JSON.parse(raw);
1075
+ // Element types are checked, not just array-ness: a corrupted stored
1076
+ // value (e.g. viewed: [123]) must not flow onto the wire as non-string
1077
+ // data. Fall through to a fresh context instead, same as the
1078
+ // entryPage enum check below.
1079
+ const isStringArray = (value) => Array.isArray(value) && value.every((v) => typeof v === 'string');
1080
+ // Absent, not invalid: a tab that started on an older SDK has a stored
1081
+ // context with no `cart` key at all. Reading that as a shape failure
1082
+ // would throw away its viewed/queries history on every upgrade, so a
1083
+ // missing list reads as an empty one; a wrong-typed one still falls
1084
+ // through to a fresh context like any other corrupted array.
1085
+ const storedCart = parsed.cart === undefined ? [] : parsed.cart;
1086
+ if (isStringArray(parsed.viewed) &&
1087
+ isStringArray(parsed.queries) &&
1088
+ isStringArray(storedCart)) {
1089
+ return {
1090
+ viewed: parsed.viewed,
1091
+ cart: storedCart,
1092
+ queries: parsed.queries,
1093
+ // A hostile/corrupted stored value (or a future enum member from a
1094
+ // newer SDK version) falls back to 'other' rather than discarding
1095
+ // otherwise-good viewed/queries data, and rather than passing
1096
+ // an unvalidated string through to the wire.
1097
+ entryPage: isPageType(parsed.entryPage) ? parsed.entryPage : 'other',
1098
+ };
1099
+ }
1100
+ }
1101
+ }
1102
+ catch {
1103
+ // Storage unavailable or corrupt; fall through to a fresh context.
1104
+ }
1105
+ // First read this session: detect entryPage once and persist immediately
1106
+ // so a later navigation within the same tab doesn't re-detect it from a
1107
+ // different path.
1108
+ const fresh = emptySessionContext();
1109
+ setSessionContext(fresh);
1110
+ return fresh;
1111
+ };
1112
+ /** @internal */
1113
+ const setSessionContext = (ctx) => {
1114
+ try {
1115
+ sessionStorage.setItem(sessionContextKeyName, serializeContext(ctx));
1116
+ }
1117
+ catch {
1118
+ // Storage unavailable; the context is best-effort telemetry, not
1119
+ // functionality — swallow rather than fail whatever caller triggered it.
1120
+ }
1121
+ };
1122
+ // base64url-encoded form for the `ctx` search query param — null when
1123
+ // there's nothing worth adding to the URL yet (see encodeContextParam).
1124
+ // api.ts stays decoupled from session-context's internals. Memoized because
1125
+ // search() calls this on every debounced keystroke: the cache is keyed on
1126
+ // the raw stored string, so a hit costs one getItem + compare instead of the
1127
+ // parse/serialize/encode chain, and any writer (not just setSessionContext)
1128
+ // invalidates it naturally.
1129
+ let cachedContextRaw = null;
1130
+ let cachedContextParam = null;
1131
+ const getSessionContextParam = () => {
1132
+ let raw = null;
1133
+ try {
1134
+ raw = sessionStorage.getItem(sessionContextKeyName);
1135
+ }
1136
+ catch {
1137
+ // Storage unavailable — nothing stable to memoize against.
1138
+ return encodeContextParam(getSessionContext());
1139
+ }
1140
+ if (raw !== null && raw === cachedContextRaw) {
1141
+ return cachedContextParam;
1142
+ }
1143
+ const ctx = getSessionContext();
1144
+ cachedContextParam = encodeContextParam(ctx);
1145
+ // A null raw means getSessionContext just persisted a fresh context — key
1146
+ // the cache on what it wrote so the next call hits.
1147
+ cachedContextRaw = raw !== null && raw !== void 0 ? raw : serializeContext(ctx);
1148
+ return cachedContextParam;
1149
+ };
879
1150
 
880
1151
  var _a;
881
1152
  const registryKey = Symbol.for('evo-search');
@@ -912,6 +1183,260 @@ const notifyReady = () => {
912
1183
  notifySubscribers(registry.subscribers, 'notifyReady');
913
1184
  };
914
1185
 
1186
+ /**
1187
+ * Storefront-local helpers, deliberately separate from the worker-scoped API
1188
+ * client: `api.ts` injects identity params and headers that must never reach
1189
+ * the merchant's own origin, and its `credentials: omit` policy is the
1190
+ * opposite of what storefront requests (which ride the cart cookie) need.
1191
+ */
1192
+ /**
1193
+ * The storefront's root path. Shopify publishes it (locale prefix included,
1194
+ * e.g. `/en-ca/`) on `window.Shopify.routes.root`; default to `/`.
1195
+ */
1196
+ const storefrontRoot = () => {
1197
+ var _a, _b;
1198
+ if (typeof window === 'undefined') {
1199
+ return '/';
1200
+ }
1201
+ const root = (_b = (_a = window.Shopify) === null || _a === void 0 ? void 0 : _a.routes) === null || _b === void 0 ? void 0 : _b.root;
1202
+ return typeof root === 'string' && root.startsWith('/') && root.endsWith('/')
1203
+ ? root
1204
+ : '/';
1205
+ };
1206
+
1207
+ // Storefront-side producers for the shopper session context. `session-context.ts`
1208
+ // knows how to grow the shape and `utils.ts` how to persist it; this module is
1209
+ // the only place that decides, from the page itself, WHAT to put in it.
1210
+ //
1211
+ // Why it exists: the widget's product-click handler is the only other producer,
1212
+ // so a shopper who browses the storefront normally — landing on product pages
1213
+ // from a collection, an ad, or a link — contributes nothing to ranking until
1214
+ // they happen to click a result inside search. Capturing the product page the
1215
+ // shopper is standing on closes that gap.
1216
+ //
1217
+ // Constraints this module works under, all deliberate:
1218
+ // - No network calls. This runs on the merchant's storefront; every id comes
1219
+ // from something already in the page (a global the platform published, or
1220
+ // the page's own structured data) or from a host that hands it to us.
1221
+ // - No PII, no page text. Ids only — never titles, prices or descriptions.
1222
+ // - Never throws. Every source is optional and best-effort: a page that
1223
+ // exposes none of them simply contributes nothing.
1224
+ // - No consent gate of its own. The context is anonymous, client-held and
1225
+ // dies with the tab; the provider is loaded under the pixel's own consent
1226
+ // decision, so a suppressed init means no capture at all, and the
1227
+ // transport (the `ctx` search param) stays gated on the merchant opt-in
1228
+ // that api.ts checks.
1229
+ const shopifyMeta = () => {
1230
+ var _a, _b;
1231
+ const w = window;
1232
+ // Two spellings of the same platform-published object: themes render the
1233
+ // analytics one, and some render a bare `meta` as well. Neither is catalog
1234
+ // data — they are the platform's page-scoped conventions.
1235
+ return (_b = (_a = w.ShopifyAnalytics) === null || _a === void 0 ? void 0 : _a.meta) !== null && _b !== void 0 ? _b : w.meta;
1236
+ };
1237
+ /**
1238
+ * True when the page the shopper is on is a product page, by the two signals
1239
+ * a storefront publishes without us asking: the platform's own page-type
1240
+ * marker, and the product path shape under the storefront root (which carries
1241
+ * the locale prefix on localized stores, so `/fr/products/…` is recognized).
1242
+ */
1243
+ const onProductPage = () => {
1244
+ var _a, _b;
1245
+ if (((_b = (_a = shopifyMeta()) === null || _a === void 0 ? void 0 : _a.page) === null || _b === void 0 ? void 0 : _b.pageType) === 'product') {
1246
+ return true;
1247
+ }
1248
+ return window.location.pathname.startsWith(`${storefrontRoot()}products/`);
1249
+ };
1250
+ // Structured data is the last resort and the only source read out of the DOM,
1251
+ // so it is bounded on every axis: how many blocks are parsed, how big a block
1252
+ // may be, and how deep the search for a Product node goes.
1253
+ const MAX_LD_BLOCKS = 5;
1254
+ // A structured-data block far larger than this is a page-wide graph, not one
1255
+ // product's node; parsing it would cost more than the signal is worth.
1256
+ const MAX_LD_CHARS = 100000;
1257
+ const productIdFromLdNode = (node) => {
1258
+ if (!node || typeof node !== 'object') {
1259
+ return null;
1260
+ }
1261
+ if (Array.isArray(node)) {
1262
+ for (const entry of node) {
1263
+ const found = productIdFromLdNode(entry);
1264
+ if (found) {
1265
+ return found;
1266
+ }
1267
+ }
1268
+ return null;
1269
+ }
1270
+ const record = node;
1271
+ const graph = record['@graph'];
1272
+ if (Array.isArray(graph)) {
1273
+ return productIdFromLdNode(graph);
1274
+ }
1275
+ const type = record['@type'];
1276
+ const isProduct = Array.isArray(type)
1277
+ ? type.includes('Product')
1278
+ : type === 'Product';
1279
+ if (!isProduct) {
1280
+ return null;
1281
+ }
1282
+ const id = normalizeProductId(record['productID']);
1283
+ // Only an all-digits id is accepted here, and `sku` is never read: the
1284
+ // catalog is keyed on the platform's own numeric product id, whereas a
1285
+ // merchant SKU (or a handle) is a different id space entirely. An id from
1286
+ // the wrong space can never resolve server-side — it would silently occupy
1287
+ // one of the few recently-viewed slots and contribute nothing. A host whose
1288
+ // structured data carries something else should call `trackProductView`.
1289
+ return id && /^\d+$/.test(id) ? id : null;
1290
+ };
1291
+ const productIdFromStructuredData = () => {
1292
+ const blocks = document.querySelectorAll('script[type="application/ld+json"]');
1293
+ const limit = Math.min(blocks.length, MAX_LD_BLOCKS);
1294
+ for (let i = 0; i < limit; i++) {
1295
+ const text = blocks[i].textContent;
1296
+ if (!text || text.length > MAX_LD_CHARS) {
1297
+ continue;
1298
+ }
1299
+ try {
1300
+ const found = productIdFromLdNode(JSON.parse(text));
1301
+ if (found) {
1302
+ return found;
1303
+ }
1304
+ }
1305
+ catch {
1306
+ // A malformed block is one merchant app's problem, not ours; try the
1307
+ // next one.
1308
+ }
1309
+ }
1310
+ return null;
1311
+ };
1312
+ /**
1313
+ * The id of the product this page is about, or null when the page isn't a
1314
+ * product page (or doesn't say which product it is). Sources are tried
1315
+ * cheapest first and each one is optional.
1316
+ */
1317
+ const currentProductId = () => {
1318
+ var _a, _b;
1319
+ try {
1320
+ // The platform global is authoritative and free: it is only populated on
1321
+ // a product page, and it carries the id in the catalog's own id space.
1322
+ const fromGlobal = normalizeProductId((_b = (_a = shopifyMeta()) === null || _a === void 0 ? void 0 : _a.product) === null || _b === void 0 ? void 0 : _b.id);
1323
+ if (fromGlobal) {
1324
+ return fromGlobal;
1325
+ }
1326
+ if (!onProductPage()) {
1327
+ return null;
1328
+ }
1329
+ return productIdFromStructuredData();
1330
+ }
1331
+ catch {
1332
+ return null;
1333
+ }
1334
+ };
1335
+ const rememberView = (id) => {
1336
+ const ctx = getSessionContext();
1337
+ // Once per page load: a re-entrant call (a second capture attempt, a
1338
+ // re-init) must not churn storage for a product that is already the most
1339
+ // recent view. A LATER load of the same product is a different matter — by
1340
+ // then something else is at the head, so it pushes again and moves back to
1341
+ // the front, which is how recency is expressed. There is no repeat counter:
1342
+ // `viewed` is a deduplicated, newest-first list and the server tallies each
1343
+ // id once.
1344
+ if (ctx.viewed[0] === id) {
1345
+ return;
1346
+ }
1347
+ setSessionContext(pushViewed(ctx, id));
1348
+ };
1349
+ /**
1350
+ * Records the product page the shopper is currently on, if this is one.
1351
+ * Returns whether anything was recorded (the retry below is its only caller
1352
+ * that cares).
1353
+ */
1354
+ const captureProductView = () => {
1355
+ try {
1356
+ const id = currentProductId();
1357
+ if (!id) {
1358
+ return false;
1359
+ }
1360
+ rememberView(id);
1361
+ return true;
1362
+ }
1363
+ catch {
1364
+ // Storage or DOM unavailable — the context is best-effort ranking input,
1365
+ // never functionality.
1366
+ return false;
1367
+ }
1368
+ };
1369
+ /**
1370
+ * Called once from the SDK bootstrap. The platform's page globals are written
1371
+ * by the theme's own head markup, so a loader that runs ahead of them would
1372
+ * see nothing at init; when the document is still parsing and nothing was
1373
+ * found, try again once the DOM is complete.
1374
+ */
1375
+ const startProductViewCapture = () => {
1376
+ try {
1377
+ if (captureProductView()) {
1378
+ return;
1379
+ }
1380
+ if (document.readyState === 'loading') {
1381
+ document.addEventListener('DOMContentLoaded', () => {
1382
+ captureProductView();
1383
+ }, { once: true });
1384
+ }
1385
+ }
1386
+ catch {
1387
+ // See captureProductView.
1388
+ }
1389
+ };
1390
+
1391
+ const createSessionContextGate = (uiPreferences, fetchConfig,
1392
+ // Whether this shopper has accumulated anything worth sending yet. Spending
1393
+ // a request to ask permission to send nothing is the one case where the
1394
+ // probe is pure waste, and it is also the common one — a session that has
1395
+ // just started has an empty context.
1396
+ hasContext) => {
1397
+ let serverEnabled = false;
1398
+ // One probe per API instance, latched BEFORE the request is issued so a
1399
+ // slow or failing config fetch can never turn the per-keystroke search path
1400
+ // into a retry storm. A probe that fails leaves the gate off, which is the
1401
+ // safe answer: the context is best-effort ranking input, never correctness.
1402
+ let probed = false;
1403
+ const prime = () => {
1404
+ // An explicit merchant preference already decides the question in both
1405
+ // directions, so there is nothing to ask the server about.
1406
+ if (probed || (uiPreferences === null || uiPreferences === void 0 ? void 0 : uiPreferences.sessionContext) !== undefined) {
1407
+ return;
1408
+ }
1409
+ // Deliberately does NOT latch `probed`: a session with nothing to say yet
1410
+ // will have something to say later, and that later call is the one worth
1411
+ // spending the probe on.
1412
+ if (!hasContext()) {
1413
+ return;
1414
+ }
1415
+ probed = true;
1416
+ // Deferred to a microtask so the request that triggered the prime is
1417
+ // already on the wire: the probe must never compete with, delay, or
1418
+ // reorder the search it rides behind.
1419
+ void Promise.resolve().then(() => fetchConfig().catch(() => {
1420
+ // Swallowed deliberately — the gate simply stays off. The caller that
1421
+ // triggered this never learns of it, and never retries.
1422
+ }));
1423
+ };
1424
+ return {
1425
+ shouldSend: () => {
1426
+ var _a;
1427
+ prime();
1428
+ // The merchant preference is an explicit override in both directions;
1429
+ // absent — the normal state — defers to the server's last answer.
1430
+ return (_a = uiPreferences === null || uiPreferences === void 0 ? void 0 : uiPreferences.sessionContext) !== null && _a !== void 0 ? _a : serverEnabled;
1431
+ },
1432
+ prime,
1433
+ resolveFrom: (sessionContextEnabled) => {
1434
+ probed = true;
1435
+ serverEnabled = sessionContextEnabled === true;
1436
+ },
1437
+ };
1438
+ };
1439
+
915
1440
  // Resilience wrapper for /search requests. A transient network failure or a
916
1441
  // hung request must not wedge the UI: add a per-attempt timeout (a hang becomes
917
1442
  // a rejection), retry transient failures with backoff, and never retry a
@@ -1148,6 +1673,13 @@ const downscaleImage = async (source) => {
1148
1673
  // Ask can't reuse withSearchResilience: a half-consumed stream isn't retryable.
1149
1674
  // Idle timeout resets per chunk; both reject with TimeoutError so submitAsk
1150
1675
  // routes them to the search fallback rather than treating them as cancellation.
1676
+ // Ceiling for an assembled GET URL, past which the optional session-context
1677
+ // param is dropped (see getJSON). Chosen above the encoder's own worst case —
1678
+ // session-context.ts caps its payload at 2KB, which base64url-grows to ~2.7KB
1679
+ // — so a legitimately full context is never dropped on its own, and several
1680
+ // times under the request-line ceiling of the edge that terminates these
1681
+ // requests. It is a safety bound, not a tuning knob.
1682
+ const MAX_REQUEST_URL_CHARS = 4096;
1151
1683
  const QUICK_ADD_VALIDATE_TIMEOUT_MS = 7000;
1152
1684
  const ASK_REQUEST_TIMEOUT_MS = 7000;
1153
1685
  const ASK_SSE_IDLE_TIMEOUT_MS = 10000;
@@ -1161,6 +1693,16 @@ const KEEP_WARM_INTERVAL_MS = 60000;
1161
1693
  // Stand-in caller signal for `search()` calls that don't pass one. Module-level
1162
1694
  // and never aborted, so it carries no state between calls.
1163
1695
  const NEVER_ABORTED = new AbortController().signal;
1696
+ // Tells /search this client resolves the response's product and collection
1697
+ // lanes against the top-level arrays itself, so the lanes need only carry ids.
1698
+ // Without it the server repeats every lane entry in full, which roughly doubles
1699
+ // the body for entries the client already has. Sent on both search legs so
1700
+ // neither pays for the duplication.
1701
+ //
1702
+ // Opt-in from the client, not a server-side switch: the client is published
1703
+ // separately from the worker, so a storefront can be running any earlier
1704
+ // version of it. One that never sends this keeps receiving whole entries.
1705
+ const LANE_REFERENCES = { lanes: 'ids' };
1164
1706
  // Always defer to what the storefront itself is rendering — same source
1165
1707
  // shop-gpt reads from. Two widgets on the same page would otherwise drift:
1166
1708
  // shop-gpt picks Shopify, evo-search would pick its own override and show
@@ -1291,6 +1833,16 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
1291
1833
  if (!credentialed) {
1292
1834
  setIdentityParams(url);
1293
1835
  }
1836
+ // Measured only here, where the URL is finally assembled: the results-page
1837
+ // leg carries facets, filter selections, a continuation cursor and identity
1838
+ // on top of the query, so its length is not knowable at the call site. A
1839
+ // session context is a ranking hint, so an over-long URL drops the hint
1840
+ // rather than the request — a slightly less personalized answer beats a
1841
+ // refused one.
1842
+ if (url.href.length > MAX_REQUEST_URL_CHARS &&
1843
+ url.searchParams.has('ctx')) {
1844
+ url.searchParams.delete('ctx');
1845
+ }
1294
1846
  const response = await fetchImpl(url, {
1295
1847
  method: 'GET',
1296
1848
  ...(credentialed ? { headers: getHeaders() } : {}),
@@ -1310,9 +1862,21 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
1310
1862
  logger.info('EvoSearch API: Fetching trending searches');
1311
1863
  return getJSON('/trending', 'Trending', undefined, signal);
1312
1864
  };
1313
- const config = (signal) => {
1865
+ // Held in the gate rather than read off `uiPreferences` at each send site:
1866
+ // that object is captured by value when this API instance is built, and the
1867
+ // widget replaces its own copy after fetching config, so an overlay there
1868
+ // would never reach this closure. The gate starts closed, so a search that
1869
+ // races ahead of the first answer sends nothing — session context is
1870
+ // best-effort ranking input, never a correctness input. `config` is
1871
+ // referenced lazily (only once the probe fires, long after this line runs).
1872
+ const sessionContextGate = createSessionContextGate(uiPreferences, () => config(), () => getSessionContextParam() !== null);
1873
+ const config = async (signal) => {
1314
1874
  logger.info('EvoSearch API: Fetching ask config');
1315
- return getJSON('/config', 'Config', undefined, signal);
1875
+ const data = await getJSON('/config', 'Config', undefined, signal);
1876
+ // A worker deployed before this gate omits the field; an absent answer
1877
+ // must read as off rather than as an opt-in.
1878
+ sessionContextGate.resolveFrom(data.sessionContextEnabled);
1879
+ return data;
1316
1880
  };
1317
1881
  const searchPageDesign = (signal, previewToken) => {
1318
1882
  logger.info(`EvoSearch API: Fetching ${previewToken ? 'preview' : 'published'} search page design`);
@@ -1382,11 +1946,38 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
1382
1946
  };
1383
1947
  const deleteRecent = (value) => sendMutation('/user/recents', 'DeleteRecent', 'DELETE', { value });
1384
1948
  const clearRecents = () => sendMutation('/user/recents', 'ClearRecents', 'DELETE');
1949
+ // The single decision point for whether a request carries the shopper's
1950
+ // session context, shared by both search legs so the autocomplete and
1951
+ // results-page requests cannot drift apart on when it is sent — the results
1952
+ // page is where a shopper spends the most time, so a leg without it is a
1953
+ // silently unpersonalized surface.
1954
+ //
1955
+ // Best-effort shopper context (recently viewed, past queries, entry page)
1956
+ // for server-side ranking, capped well under 2KB by session-context.ts.
1957
+ // Carried as a query param rather than a header so /search stays a
1958
+ // CORS-simple request — no OPTIONS preflight on the per-keystroke hot path.
1959
+ // Omitted while there's nothing to say yet. Gated on the server, which is
1960
+ // the only side that knows whether a `ctx` consumer is live: sending browsing
1961
+ // history nobody reads is pure cost and pure exposure. The merchant
1962
+ // preference is an explicit override in both directions — set, it wins;
1963
+ // absent (the normal state), the server decides.
1964
+ const withSessionContext = (params) => {
1965
+ if (!sessionContextGate.shouldSend()) {
1966
+ return params;
1967
+ }
1968
+ const ctxParam = getSessionContextParam();
1969
+ return ctxParam ? { ...params, ctx: ctxParam } : params;
1970
+ };
1385
1971
  // Resilience lives here, not at each call site, so no consumer can opt out —
1386
1972
  // the headless channel previously had no deadline and no retry.
1387
1973
  const search = async (query, limit = 24, signal) => {
1388
1974
  logger.info(`EvoSearch API: Search request - query length: ${query.length}, limit: ${limit}`);
1389
- const data = await withSearchResilience((attemptSignal) => getJSON('/search', 'Search', { q: query, limit: String(limit) }, attemptSignal),
1975
+ const searchParams = withSessionContext({
1976
+ q: query,
1977
+ limit: String(limit),
1978
+ ...LANE_REFERENCES,
1979
+ });
1980
+ const data = await withSearchResilience((attemptSignal) => getJSON('/search', 'Search', searchParams, attemptSignal),
1390
1981
  // Shared stand-in is safe: the wrapper removes its abort listener per attempt.
1391
1982
  signal !== null && signal !== void 0 ? signal : NEVER_ABORTED);
1392
1983
  logger.info(`EvoSearch API: Search success - ${data.llmSuggestions.length} suggestions, ${data.products.length} products`);
@@ -1400,6 +1991,7 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
1400
1991
  const params = {
1401
1992
  q: query,
1402
1993
  facets: '1',
1994
+ ...LANE_REFERENCES,
1403
1995
  };
1404
1996
  if (options.limit != null) {
1405
1997
  params['limit'] = String(options.limit);
@@ -1433,7 +2025,12 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
1433
2025
  if ((filters === null || filters === void 0 ? void 0 : filters.priceMax) != null) {
1434
2026
  params['priceMax'] = String(filters.priceMax);
1435
2027
  }
1436
- return withSearchResilience((attemptSignal) => getJSON('/search', 'SearchResults', params, attemptSignal), (_f = options.signal) !== null && _f !== void 0 ? _f : NEVER_ABORTED);
2028
+ return withSearchResilience((attemptSignal) => getJSON('/search', 'SearchResults',
2029
+ // Applied per attempt, and to every page: a continuation (cursor) or
2030
+ // a numbered page (offset) is the same result set the shopper is
2031
+ // still reading, so dropping the context there would re-rank the
2032
+ // next page against a different profile than the first.
2033
+ withSessionContext(params), attemptSignal), (_f = options.signal) !== null && _f !== void 0 ? _f : NEVER_ABORTED);
1437
2034
  };
1438
2035
  // Same deadline as `validateQuickAdd`, and for the same reason: the only
1439
2036
  // caller passes no signal, so without one a stalled request never settles —
@@ -1690,7 +2287,7 @@ const createEvoSearchAPI = ({ fetch: fetchImpl = window.fetch, baseURL, userId,
1690
2287
  .catch(logger.error);
1691
2288
  // Also send to analytics via sendTag
1692
2289
  sendTag({
1693
- eventId: crypto.randomUUID(),
2290
+ eventId: mintId(),
1694
2291
  eventName: action,
1695
2292
  data: {
1696
2293
  ...actionData,
@@ -1758,6 +2355,17 @@ const parseSseFrame = (frame) => {
1758
2355
  }
1759
2356
  };
1760
2357
 
2358
+ const FORCED_KEY = 'evsUiVersion';
2359
+ // ?evs=reset must also drop the QA force so a shopper returns to the configured version.
2360
+ const clearForcedUiVersion = () => {
2361
+ try {
2362
+ sessionStorage.removeItem(FORCED_KEY);
2363
+ }
2364
+ catch {
2365
+ /* no-op: storage unavailable */
2366
+ }
2367
+ };
2368
+
1761
2369
  const error = (message) => console.error(message);
1762
2370
  // Headless hosts render their own UI, so nothing else pings /warm for them.
1763
2371
  let disposeKeepWarm;
@@ -1830,6 +2438,7 @@ const init = (params) => {
1830
2438
  try {
1831
2439
  sessionStorage.removeItem(previewKeyName);
1832
2440
  sessionStorage.removeItem(disableKeyName);
2441
+ clearForcedUiVersion();
1833
2442
  logger.info('EvoSearch SDK: Reset to configured state via ?evs=reset URL param');
1834
2443
  }
1835
2444
  catch {
@@ -1849,6 +2458,13 @@ const init = (params) => {
1849
2458
  if (hasPreview) {
1850
2459
  logger.info('EvoSearch SDK: Preview mode enabled via sessionStorage');
1851
2460
  }
2461
+ // Before the UI/headless fork: a headless host returns early below, and
2462
+ // its shoppers browse product pages exactly like everyone else's. Not
2463
+ // gated on the session-context opt-in — that flag gates the TRANSPORT
2464
+ // (api.ts decides whether the context leaves the browser), and gating
2465
+ // capture too would leave a merchant who turns it on with an empty
2466
+ // history until the shopper navigates again.
2467
+ startProductViewCapture();
1852
2468
  const evoSearchAPI = createEvoSearchAPI({
1853
2469
  baseURL: params.baseUrl,
1854
2470
  userId: params.userId,
@@ -1860,7 +2476,7 @@ const init = (params) => {
1860
2476
  const uiImplementation = window[registryKey].ui;
1861
2477
  const headless = !uiImplementation;
1862
2478
  params.sendTag({
1863
- eventId: crypto.randomUUID(),
2479
+ eventId: mintId(),
1864
2480
  eventName: 'evoSearchInitialized',
1865
2481
  data: { mode, hasPreview, headless },
1866
2482
  providers: { evoSearch: true },
@@ -1892,7 +2508,7 @@ const init = (params) => {
1892
2508
  visualSearchEnabled,
1893
2509
  });
1894
2510
  params.sendTag({
1895
- eventId: crypto.randomUUID(),
2511
+ eventId: mintId(),
1896
2512
  eventName: 'evoSearchLoaded',
1897
2513
  data: {},
1898
2514
  providers: { evoSearch: true },
@@ -1912,7 +2528,7 @@ const init = (params) => {
1912
2528
  const tag = ({ data }) => {
1913
2529
  try {
1914
2530
  return {
1915
- sdkVersion: "1.70.2" || '',
2531
+ sdkVersion: "1.71.1" || '',
1916
2532
  searchQuery: data['searchQuery'],
1917
2533
  searchResults: data['searchResults'],
1918
2534
  timestamp: Date.now(),
@@ -1921,7 +2537,7 @@ const tag = ({ data }) => {
1921
2537
  catch (err) {
1922
2538
  console.error(`EvoSearch SDK: Tagging failed - ${err}`);
1923
2539
  return {
1924
- sdkVersion: "1.70.2" ,
2540
+ sdkVersion: "1.71.1" ,
1925
2541
  timestamp: Date.now(),
1926
2542
  };
1927
2543
  }