@sharadtech/infralytiqs-sdk 1.0.2 → 1.0.3

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.
Files changed (65) hide show
  1. package/buildScripts/Jenkinsfile.deploy +241 -125
  2. package/clients/publicis/arc/README.md +212 -0
  3. package/clients/publicis/arc/package-lock.json +808 -0
  4. package/clients/publicis/arc/package.json +23 -0
  5. package/clients/publicis/arc/rollup.config.mjs +28 -0
  6. package/clients/publicis/arc/src/index.js +2900 -0
  7. package/clients/publicis/atl/README.md +203 -0
  8. package/clients/publicis/atl/package-lock.json +808 -0
  9. package/clients/publicis/atl/package.json +23 -0
  10. package/clients/publicis/atl/rollup.config.mjs +28 -0
  11. package/clients/publicis/atl/src/index.js +2902 -0
  12. package/clients/publicis/colab/README.md +213 -0
  13. package/clients/publicis/colab/package-lock.json +808 -0
  14. package/clients/publicis/colab/package.json +23 -0
  15. package/clients/publicis/colab/rollup.config.mjs +28 -0
  16. package/clients/publicis/colab/src/index.js +2901 -0
  17. package/clients/publicis/fnacdarty/README.md +210 -0
  18. package/clients/publicis/fnacdarty/package-lock.json +808 -0
  19. package/clients/publicis/fnacdarty/package.json +23 -0
  20. package/clients/publicis/fnacdarty/rollup.config.mjs +28 -0
  21. package/clients/publicis/fnacdarty/src/index.js +2900 -0
  22. package/clients/publicis/garnier/README.md +206 -0
  23. package/clients/publicis/garnier/package-lock.json +808 -0
  24. package/clients/publicis/garnier/package.json +23 -0
  25. package/clients/publicis/garnier/rollup.config.mjs +28 -0
  26. package/clients/publicis/garnier/src/index.js +2894 -0
  27. package/clients/publicis/pmigtr/README.md +212 -0
  28. package/clients/publicis/pmigtr/package-lock.json +808 -0
  29. package/clients/publicis/pmigtr/package.json +23 -0
  30. package/clients/publicis/pmigtr/rollup.config.mjs +28 -0
  31. package/clients/publicis/pmigtr/src/index.js +2903 -0
  32. package/clients/publicis/ps/package-lock.json +2 -2
  33. package/clients/publicis/ps/package.json +1 -1
  34. package/clients/publicis/px/README.md +209 -0
  35. package/clients/publicis/px/package-lock.json +808 -0
  36. package/clients/publicis/px/package.json +23 -0
  37. package/clients/publicis/px/rollup.config.mjs +28 -0
  38. package/clients/publicis/px/src/index.js +2899 -0
  39. package/clients/publicis/pxp/README.md +212 -0
  40. package/clients/publicis/pxp/package-lock.json +808 -0
  41. package/clients/publicis/pxp/package.json +23 -0
  42. package/clients/publicis/pxp/rollup.config.mjs +28 -0
  43. package/clients/publicis/pxp/src/index.js +2900 -0
  44. package/clients/publicis/razorfish/README.md +210 -0
  45. package/clients/publicis/razorfish/package-lock.json +808 -0
  46. package/clients/publicis/razorfish/package.json +23 -0
  47. package/clients/publicis/razorfish/rollup.config.mjs +28 -0
  48. package/clients/publicis/razorfish/src/index.js +2900 -0
  49. package/clients/publicis/stellantis/README.md +208 -0
  50. package/clients/publicis/stellantis/package-lock.json +808 -0
  51. package/clients/publicis/stellantis/package.json +23 -0
  52. package/clients/publicis/stellantis/rollup.config.mjs +28 -0
  53. package/clients/publicis/stellantis/src/index.js +2895 -0
  54. package/clients/publicis/visa/README.md +208 -0
  55. package/clients/publicis/visa/package-lock.json +808 -0
  56. package/clients/publicis/visa/package.json +23 -0
  57. package/clients/publicis/visa/rollup.config.mjs +28 -0
  58. package/clients/publicis/visa/src/index.js +2894 -0
  59. package/dist/infralytiqs.js +243 -71
  60. package/dist/infralytiqs.min.js +2 -2
  61. package/package.json +1 -1
  62. package/src/envConfig.ts +1 -1
  63. package/src/remoteConfig.ts +164 -0
  64. package/src/tracker.ts +30 -0
  65. package/src/types.ts +10 -2
@@ -0,0 +1,2894 @@
1
+ /**
2
+ * Infralytiqs client-specific bootstrap — Visa
3
+ * (visa-sit.productioncloud.io, ...)
4
+ *
5
+ * This is the "visa" sibling of the "publicis/ps" bootstrap. Both target
6
+ * the same Adobe DAM Asset Share Commons platform (groupe-dam tenant), so
7
+ * the event taxonomy, selectors, and DOM heuristics are identical; only
8
+ * the host domain, the client-override global namespace (IL_VISA_*), and
9
+ * the internal de-dupe flag prefixes (__ilVisa*) differ. The per-tenant
10
+ * server/tenant/site/db values are still read from window.IL_* injected
11
+ * server-side by the AEM Sightly `Infralytiqs.html` fragment (visa runs
12
+ * on site_id = SIT), so this file hard-codes none of them. Visa uses the
13
+ * same URL shape as ps (login at `/login.html`, asset explorer at
14
+ * `/asset-explorer.html`, details at `/details/<type>.html/<assetPath>`),
15
+ * so no path-prefix handling is required.
16
+ *
17
+ * Pipeline:
18
+ * 1. The host page embeds the Infralytiqs SDK from the CDN:
19
+ * <script src="https://assets.infralytiqs.com/cdn/infralytiqs.min.js"></script>
20
+ * 2. The host page injects per-tenant configuration as `window.IL_*` globals
21
+ * (server-side rendered via the Sightly `Infralytiqs.html` fragment).
22
+ * 3. This bootstrap loads after the SDK + config and:
23
+ * a. Reads window.IL_* and Infralytiqs.init() with browser-side enrichment.
24
+ * b. Resolves the logged-in AEM user via /libs/granite/security/currentuser.json
25
+ * and calls Infralytiqs.identify() so subsequent events carry user_id.
26
+ * c. Tracks two families of events:
27
+ *
28
+ * ──────────────────────────────────────────────────────────────
29
+ * LOGIN PAGE (auth_state = anonymous)
30
+ * ──────────────────────────────────────────────────────────────
31
+ * login_page_view — anonymous landing on the login page
32
+ * login_attempt — Sign-in button submit (captures typed username,
33
+ * NEVER the password)
34
+ * sso_click — "Login with Lion Login" SSO button click
35
+ * terms_click — "Terms and Conditions" link click
36
+ *
37
+ * ──────────────────────────────────────────────────────────────
38
+ * ASSET SHARE COMMONS (auth_state = authenticated)
39
+ * (search_context = "asc" — URL-driven, pushState SPA)
40
+ * ──────────────────────────────────────────────────────────────
41
+ * search_executed — fired on every page whose URL carries `?fulltext=…`.
42
+ * Captures search term, semantic / fuzzy toggles,
43
+ * active filters (group, human label, property,
44
+ * operation, values) cross-referenced against the
45
+ * right-rail predicate sections so reports can
46
+ * render `ASSET TYPE = Image` instead of
47
+ * `jcr:content/metadata/ps:assettype = Image`,
48
+ * order-by, sort direction, layout (card | list),
49
+ * offset / limit, plus the search-statistics widget
50
+ * (`search_time_ms`, `result_total`, `result_pages`)
51
+ * once ASC finishes rendering the result count and
52
+ * response time in the right rail. The bootstrap
53
+ * briefly observes the statistics block before
54
+ * firing so the timing reflects the search the
55
+ * user actually just executed (not a stale value
56
+ * left over from the previous in-page navigation).
57
+ *
58
+ * asset_preview — fired on every page whose URL matches
59
+ * /details/<type>.html/<assetPath>. Captures the
60
+ * /content/dam/... path, the asset-share asset type
61
+ * (image / video / document / 3d / …), file name
62
+ * and extension.
63
+ *
64
+ * asset_download — fired when the browser POSTs to the ASC download
65
+ * endpoint (network interception, NOT button click,
66
+ * so it captures bulk-download from card menus,
67
+ * detail-page button, and the dropdown rendition
68
+ * picker uniformly).
69
+ * Captures asset_path + rendition_name from the
70
+ * form-encoded POST body.
71
+ *
72
+ * asset_add_to_cart — fired on click of any element matched by the
73
+ * `addToCart` selector list, the `[data-il-cart-add]`
74
+ * opt-in attribute, or visible text /add to cart/i.
75
+ * Captures the asset_path from data-attrs on the
76
+ * button or its nearest card ancestor.
77
+ *
78
+ * asset_share — fired on click of any element matched by the
79
+ * `shareButton` selector list or visible text
80
+ * /share/i. Placeholder until the share workflow
81
+ * is finalized.
82
+ *
83
+ * ──────────────────────────────────────────────────────────────
84
+ * ASSET EXPLORER (search_context = "asset_explorer")
85
+ * /asset-explorer.html#/content/dam/... (React SPA, hash routing)
86
+ * ──────────────────────────────────────────────────────────────
87
+ * search_executed — fired when the user runs a search inside the
88
+ * explorer. Listens to every plausible trigger
89
+ * (Enter on the input, native form submit,
90
+ * Search Options modal close, right-rail filter
91
+ * click, debounced typing) and carries the
92
+ * original `search_trigger` on each event so we
93
+ * can prune redundant hooks once production
94
+ * tells us which path actually fires. Captures
95
+ * search_term, semantic_search, fuzzy_search
96
+ * (read from the toggles in the open Search
97
+ * Options modal — see readAssetExplorerToggleState
98
+ * for the four heuristics tried), `folder_path`
99
+ * (the `#/content/dam/...` hash), and the stats
100
+ * widget (`search_time_ms`, `result_total`,
101
+ * `result_displayed`, `result_pages` when shown)
102
+ * once it settles. Subtype is `asset_search` —
103
+ * same as ASC — so a single ClickHouse query can
104
+ * report cross-context search volume.
105
+ *
106
+ * folder_navigation — fired whenever the hash route changes (user
107
+ * clicked into another DAM folder). Carries
108
+ * `folder_path` + the standard browser-side
109
+ * enrichment dimensions. Subtype is `asset_browse`.
110
+ *
111
+ * asset_preview — reuses the ASC details-page detector when the
112
+ * explorer hands off to a /details/<type>.html URL,
113
+ * plus the body-level click delegation so a
114
+ * right-side preview panel that exposes a
115
+ * `data-asset-path` attribute is also captured.
116
+ *
117
+ * asset_download — same network-interception path as ASC, since the
118
+ * download endpoint is shared at the AEM backend
119
+ * layer.
120
+ *
121
+ * asset_add_to_cart, asset_share — same click delegation as ASC.
122
+ *
123
+ * Selector strategy
124
+ * -----------------
125
+ * The DOM may evolve, so every selector is overridable via window globals
126
+ * (set BEFORE this bootstrap runs):
127
+ *
128
+ * window.IL_VISA_SELECTORS = {
129
+ * // Login page
130
+ * loginForm: '#loginForm',
131
+ * signInButton: 'button[type="submit"]',
132
+ * userField: 'input[name="username"]',
133
+ * ssoButton: '[data-il-sso-lion]',
134
+ * termsLink: 'a[href*="terms"]',
135
+ * // ASC
136
+ * searchInput: 'input[name="fulltext"]',
137
+ * filterRail: '#rail',
138
+ * addToCart: '[data-il-cart-add]',
139
+ * shareButton: '[data-il-share]'
140
+ * };
141
+ *
142
+ * If none are provided we fall back to a robust default set that matches
143
+ * by id, name, role, data-attribute, and visible text — so the bootstrap
144
+ * is essentially zero-config for the common ASC layout.
145
+ *
146
+ * The host page can also override how the logged-in user is resolved:
147
+ *
148
+ * window.IL_VISA_USER_RESOLVER = function () {
149
+ * return 'qa-ps-asc-global'; // sync
150
+ * // or: return Promise.resolve('qa-ps-asc-global');
151
+ * };
152
+ */
153
+ (function () {
154
+ 'use strict';
155
+
156
+ if (window.__ilVisaBootstrapped) {
157
+ return;
158
+ }
159
+ window.__ilVisaBootstrapped = true;
160
+
161
+ // ─── 1. Read host-page configuration ──────────────────────
162
+ var SERVER_URL = window.IL_SERVER_URL;
163
+ var TENANT_ID = window.IL_TENANT_ID;
164
+ var SITE_ID = window.IL_SITE_ID;
165
+ var DB_NAME = window.IL_DB_NAME;
166
+
167
+ if (!SERVER_URL || !TENANT_ID || !SITE_ID) {
168
+ return;
169
+ }
170
+
171
+ var USER_OVERRIDES = (window.IL_VISA_SELECTORS && typeof window.IL_VISA_SELECTORS === 'object')
172
+ ? window.IL_VISA_SELECTORS
173
+ : {};
174
+
175
+ // ─── 2. Default selectors ────────────────────────────────
176
+ // Each is a comma-separated list of CSS selectors tried in order. The first
177
+ // element that matches the page wins. Text-based fallback below handles
178
+ // pages whose controls don't carry stable IDs.
179
+ var SELECTORS = {
180
+ // ── Login page ─────────────────────────────────────────
181
+ loginForm: USER_OVERRIDES.loginForm
182
+ || 'form#loginForm, form[name="loginForm"], form[action*="login"], form[action*="signin"]',
183
+ signInButton: USER_OVERRIDES.signInButton
184
+ || '#signInButton, #signin, #signInBtn, #loginButton, button[name="signin"], button[data-action="signin"], button[type="submit"]',
185
+ userField: USER_OVERRIDES.userField
186
+ || '#username, #userId, #email, input[name="username"], input[name="userId"], input[name="email"], input[type="email"]',
187
+ ssoButton: USER_OVERRIDES.ssoButton
188
+ || '#lionLogin, [data-il-sso-lion], [data-sso="lion-login"], button[name="lion-login"], a[href*="lion-login"], a[href*="lionlogin"]',
189
+ termsLink: USER_OVERRIDES.termsLink
190
+ || 'a[data-il-terms], a#termsLink, a[href*="terms-and-conditions"], a[href*="terms_and_conditions"], a[href*="/terms"], a[href*="terms.html"]',
191
+
192
+ // ── Asset Share Commons ───────────────────────────────
193
+ // The search input on visa-sit.productioncloud.io has `name="fulltext"` and the
194
+ // `data-search-input` attribute set by the ASC search-bar component
195
+ // (id includes a per-render numeric suffix, so we don't depend on it).
196
+ searchInput: USER_OVERRIDES.searchInput
197
+ || 'input[name="fulltext"], [data-search-input], input.cmp-fulltext, input[type="search"][data-cmp-hook-search-input]',
198
+ // The ASC right-rail container that holds the filter/predicate panel.
199
+ // On visa-sit.productioncloud.io this is `#rail` inside the asset-share-commons
200
+ // root; we keep a comma-separated fallback list so the bootstrap also
201
+ // covers older / themed deployments that use a `.sidebar` wrapper.
202
+ filterRail: USER_OVERRIDES.filterRail
203
+ || '#rail, .search-rail, [data-cmp-is="search-rail"], #asset-share-commons .ui.wide.sidebar.right, .ui.wide.sidebar.right',
204
+ // Search-statistics widget (right-rail, "X assets / 54 ms / Y pages").
205
+ // On visa-sit.productioncloud.io this is `.cmp.cmp-search-statistics` containing
206
+ // a Semantic-UI `.ui.mini.three.statistics` block with three `.statistic`
207
+ // tiles. We keep alternative selectors for themed / re-skinned variants.
208
+ searchStatistics: USER_OVERRIDES.searchStatistics
209
+ || '.cmp.cmp-search-statistics, [class*="cmp-search-statistics"], [data-cmp-is="search-statistics"], .search-statistics, .cmp-searchstatistics',
210
+ // Asset-level Add-to-Cart button (per-tile / per-card / details
211
+ // page). The Asset Share Commons convention puts the asset path on
212
+ // `data-asset-share-asset` and the button-id on `data-asset-share-id`.
213
+ // We prioritise the data attributes so the button can be detected
214
+ // even when rendered as an icon-only variant with no visible label.
215
+ addToCart: USER_OVERRIDES.addToCart
216
+ || '[data-asset-share-id="add-to-cart"], [data-asset-share-id="addToCart"], [data-il-cart-add], [data-cmp-cart-action="add"], [data-asset-cart-action="add"], button.cart-add, a.cart-add, button[data-action="cart-add"]',
217
+ // Asset-level Share button. Distinct from the cart-level share
218
+ // (`data-asset-share-id="share-all"`) which the click delegation
219
+ // checks BEFORE this so they never overlap.
220
+ shareButton: USER_OVERRIDES.shareButton
221
+ || '[data-asset-share-id="share-asset"], [data-asset-share-id="share"], [data-il-share], [data-cmp-share-action], button.share, a.share, button[data-action="share"]',
222
+ // ── Cart & downloads (ASC modal flow, used on the asset-explorer too) ──
223
+ // Top-bar cart icon — opens the cart modal. The Asset Share
224
+ // Commons template renders this as a Semantic UI `<i class="big
225
+ // cart icon">` inside an `<a class="item">` link. We keep a
226
+ // data-attribute path in front for installations that follow
227
+ // newer ASC conventions.
228
+ cartOpenButton: USER_OVERRIDES.cartOpenButton
229
+ || '[data-asset-share-id="cart"], [data-asset-share-id="open-cart"], a[data-il-cart-open], a.item > i.cart.icon, a.item > i.big.cart.icon, .cmp-structure-user-menu i.cart.icon, .cmp-structure-user-menu i.big.cart.icon',
230
+ // Cart-modal "Share Cart" button — applies to the WHOLE cart.
231
+ // The DOM uses `data-asset-share-id="share-all"`.
232
+ cartShareButton: USER_OVERRIDES.cartShareButton
233
+ || '[data-asset-share-id="share-all"], [data-asset-share-id="shareCart"]',
234
+ // Cart-modal "Download Cart" button — initiates the cart-download
235
+ // flow (a second confirmation modal opens afterwards, then the
236
+ // actual binaries are produced and listed in the downloads modal).
237
+ cartDownloadButton: USER_OVERRIDES.cartDownloadButton
238
+ || '[data-asset-share-id="download-all"], [data-asset-share-id="downloadCart"]',
239
+ // Cart modal itself — used to scrape the cart contents at the
240
+ // moment Share Cart / Download Cart is clicked.
241
+ cartModal: USER_OVERRIDES.cartModal
242
+ || 'form.cmp-modal-cart, .cmp-modal-cart, [class*="cmp-modal-cart"]',
243
+ // Top-bar downloads icon — opens the downloads-list modal.
244
+ downloadsOpenButton: USER_OVERRIDES.downloadsOpenButton
245
+ || '[data-asset-share-id="downloads"], [data-asset-share-id="open-downloads"], a[data-il-downloads-open], a.item > i.download.icon, a.item > i.big.download.icon, .cmp-structure-user-menu i.download.icon, .cmp-structure-user-menu i.big.download.icon',
246
+ // Per-artifact download link inside the downloads modal. Anchors
247
+ // pointing at the AEM download-binaries endpoint with a
248
+ // `downloadId` query string. We deliberately accept ANY scheme /
249
+ // host the href might carry — the path is the stable identifier.
250
+ downloadBinaryLink: USER_OVERRIDES.downloadBinaryLink
251
+ || 'a[href*="downloadbinaries.json"], a[href*="downloadbinaries"][href*="downloadId="]',
252
+ // Per-download "remove from downloads" button. Carries the
253
+ // download UUID on `data-asset-share-download-id`.
254
+ downloadRemoveButton: USER_OVERRIDES.downloadRemoveButton
255
+ || '[data-asset-share-id="remove-from-downloads"], [data-asset-share-id="removeFromDownloads"]',
256
+ // ── Cart-Share modal (cmp-modal-share) ─────────────────
257
+ // The "Share Cart" button opens a SECOND modal that collects the
258
+ // recipient e-mails, the "Share Publicly" flag, and the optional
259
+ // start/expiry dates. The class anchor `cmp-modal-share` is
260
+ // stable across themes and the variant suffix
261
+ // `__wrapper--initial` covers the "fresh" state; we accept all
262
+ // wrapper variants because some themes also produce
263
+ // `__wrapper--success` / `__wrapper--error` after submission.
264
+ shareModal: USER_OVERRIDES.shareModal
265
+ || 'form.cmp-modal-share, form[class*="cmp-modal-share"], [class*="cmp-modal-share__wrapper"]',
266
+ // Comma-delimited e-mail recipients. The DOM uses
267
+ // <input type="email" multiple name="email">; the type+name
268
+ // pairing is the most stable anchor.
269
+ shareEmailInput: USER_OVERRIDES.shareEmailInput
270
+ || 'form.cmp-modal-share input[name="email"], form[class*="cmp-modal-share"] input[name="email"], [class*="cmp-modal-share"] input[type="email"][name="email"]',
271
+ // "Share Publicly" checkbox. ASC renders this without a data
272
+ // attribute, so we use the Semantic UI wrapper + child input
273
+ // pattern. The reader (below) also accepts a label-text match
274
+ // so a future template tweak that renames the wrapper won't
275
+ // silently dark-launch.
276
+ sharePublicCheckbox: USER_OVERRIDES.sharePublicCheckbox
277
+ || 'form.cmp-modal-share .ui.checkbox input[type="checkbox"], form[class*="cmp-modal-share"] .ui.checkbox input[type="checkbox"]',
278
+ // External-share date range. Only required when the public
279
+ // checkbox is ticked; the inputs use plain HTML id anchors that
280
+ // the ASC template controls.
281
+ shareStartDateInput: USER_OVERRIDES.shareStartDateInput
282
+ || 'form.cmp-modal-share #startDate, form[class*="cmp-modal-share"] #startDate, form.cmp-modal-share input[name="startDate"], form[class*="cmp-modal-share"] input[name="startDate"]',
283
+ shareExpiryDateInput: USER_OVERRIDES.shareExpiryDateInput
284
+ || 'form.cmp-modal-share #expiryDate, form[class*="cmp-modal-share"] #expiryDate, form.cmp-modal-share input[name="expiryDate"], form[class*="cmp-modal-share"] input[name="expiryDate"]',
285
+
286
+ // ── Asset Explorer (React) ─────────────────────────────
287
+ // /asset-explorer.html is a React SPA whose CSS Modules generate class
288
+ // names with a build-hash suffix that changes on every deploy
289
+ // (`_input_x72oj_15` → `_input_a1b2c_42` on the next build). Every
290
+ // selector below uses [class*="_<stable-prefix>_"] so it survives the
291
+ // hash refresh; we anchor on the human-stable prefix from the source
292
+ // CSS Module file name (`*.module.css`) which is reused across deploys.
293
+ assetExplorerRoot: USER_OVERRIDES.assetExplorerRoot
294
+ || '[class*="_directoryExplorer_"], .directory-explorer',
295
+ assetExplorerForm: USER_OVERRIDES.assetExplorerForm
296
+ || '[class*="_directoryExplorer_"] form, [class*="_form_"]',
297
+ assetExplorerSearchInput: USER_OVERRIDES.assetExplorerSearchInput
298
+ || '[class*="_directoryExplorer_"] input[type="text"], [class*="_inputWrapper_"] input, [class*="_input_"][type="text"]',
299
+ // Each row in the open Search Options modal. We identify "Semantic
300
+ // Search" vs "Fuzzy Search" by visible text, not by row index, in case
301
+ // the modal grows additional rows in a future release.
302
+ assetExplorerSearchOptionRow: USER_OVERRIDES.assetExplorerSearchOptionRow
303
+ || '[class*="_searchOptionRow_"], [class*="_searchOption_Row_"]',
304
+ // The right-side filter rail. Contains both the facet sections and
305
+ // the search-statistics tiles (`N DISPLAYED / N TOTAL / N MILLISECONDS`)
306
+ // at the bottom on visa-sit.productioncloud.io.
307
+ assetExplorerFilterRail: USER_OVERRIDES.assetExplorerFilterRail
308
+ || '[class*="_filterWrapper_"], [class*="_wrapper_tqpgs"], [class*="_filtersPanel_"]',
309
+ // Stats container. Live builds use `_statContainer_<hash>` (note the
310
+ // CamelCase — `_stat_` with a trailing underscore would not match) so
311
+ // we look for that prefix first, then progressively widen to other
312
+ // common React naming patterns. The reader pairs `_value_` children
313
+ // with `_label_` siblings inside whichever container matches, and
314
+ // falls back to a regex parse over the filter rail's text content
315
+ // when no structured tiles can be located.
316
+ assetExplorerSearchStatistics: USER_OVERRIDES.assetExplorerSearchStatistics
317
+ || '[class*="_statContainer_"], [class*="_statsContainer_"], [class*="_statisticsContainer_"], [class*="_statistics_"], [class*="_searchStats_"], [class*="_resultStats_"], [class*="_filterWrapper_"]',
318
+ // Filter sections inside the rail. Each section has a heading
319
+ // ("ASSET TYPE", "MARKETING FUNCTION / INDUSTRY", ...) plus its
320
+ // selectable options. We anchor on `_filterSection_`, `_facet_`,
321
+ // `_filterGroup_` and similar React naming conventions, and fall
322
+ // through to `<section>` / `<fieldset>` for un-prefixed builds.
323
+ assetExplorerFilterSection: USER_OVERRIDES.assetExplorerFilterSection
324
+ || '[class*="_filterSection_"], [class*="_filterGroup_"], [class*="_facet_"], [class*="_category_"], [class*="_section_"], section, fieldset',
325
+ // Left-side folder tree inside the explorer's content panel.
326
+ // `_directoryTree_<hash>` wraps the entire tree, `_directoryTreeContent_`
327
+ // is the scrollable inner container. Inner items also carry the
328
+ // `_directoryTree_<another-hash>` prefix from a nested CSS Module so
329
+ // the selector is intentionally permissive.
330
+ assetExplorerFolderTree: USER_OVERRIDES.assetExplorerFolderTree
331
+ || '[class*="_directoryTreeContent_"], [class*="_directoryTreeWrapper_"], [class*="_directoryTree_"]'
332
+ };
333
+
334
+ // Visible-text regexes used as a last-resort fallback when none of the CSS
335
+ // selectors above match. Intentionally case-insensitive and tolerant of
336
+ // surrounding whitespace / punctuation.
337
+ var TEXT_PATTERNS = {
338
+ signIn: /\b(sign[- ]?in|log[- ]?in|login)\b/i,
339
+ lionSso: /\blion\s*login\b/i,
340
+ terms: /\bterms?\s*(?:&|and)\s*conditions?\b/i,
341
+ cart: /\badd\s*to\s*(?:cart|collection)\b/i,
342
+ share: /\bshare\b/i,
343
+ semantic: /\bsemantic\s*search\b/i,
344
+ fuzzy: /\bfuzzy\s*search\b/i,
345
+ // "What are you looking for?" placeholder anchors the search input on
346
+ // /asset-explorer.html when the CSS-Module prefix has not yet been
347
+ // covered by the [class*="_input_"] selectors (themed builds, etc.).
348
+ aeSearchPlaceholder: /\b(looking for|search assets?|find assets?)\b/i
349
+ };
350
+
351
+ // ASC network endpoints — matched against the request URL. Patterns are
352
+ // intentionally tolerant so they survive moves in the AEM content tree
353
+ // (the `/content/<tenant>/<region>/.../actions/...` prefix varies but the
354
+ // suffix `/actions/download/.../download.download-asset-renditions.zip`
355
+ // is the ASC convention).
356
+ var ENDPOINTS = {
357
+ // POST /content/.../actions/download/.../download.download-asset-renditions.zip
358
+ // body: timezone=…&path=<assetPath>&renditionName=<name>&:cq_csrf_token=…
359
+ download: /\/actions\/download(?:\/[^?\s]*)?\/download\.download-asset-renditions\.zip(?:[?#]|$)/,
360
+ // Best-effort cart/share — used to OPPORTUNISTICALLY capture network calls
361
+ // if the click hook missed them. Not authoritative.
362
+ addToCart: /\/(?:cart|asset-collection|asset-collections)(?:\/[^?\s]*)?\.(?:add|json|html)(?:[?#]|$)|\/bin\/asset-share-commons\/cart/i,
363
+ share: /\/(?:share|email-asset|send)(?:\/[^?\s]*)?\.(?:send|json|html)(?:[?#]|$)/i
364
+ };
365
+
366
+ // Granite endpoint that returns { authorizableId, id, ... } for the
367
+ // currently logged-in AEM user. Public; requires the session cookie.
368
+ var CURRENT_USER_ENDPOINT = '/libs/granite/security/currentuser.json';
369
+
370
+ // localStorage cache key for the resolved user. Bypasses the Granite
371
+ // fetch on subsequent page loads so user_id is attached to events
372
+ // synchronously (avoids the "first event after navigation lacks user_id"
373
+ // race during a roundtrip to /libs/granite/...).
374
+ var CACHE_KEY_USER = 'IL_VISA_USER_ID';
375
+
376
+ // ─── 3. SDK access + safe wrappers ───────────────────────
377
+ function getApi() {
378
+ var raw = window.Infralytiqs;
379
+ if (!raw) return null;
380
+ return raw && raw.default && typeof raw.default.init === 'function' ? raw.default : raw;
381
+ }
382
+
383
+ function track(eventType, dims, metrics, subtype) {
384
+ var api = getApi();
385
+ if (!api) return;
386
+ try {
387
+ api.track(eventType, dims || {}, metrics || {}, subtype);
388
+ } catch (e) {
389
+ console.error('[IL-VISA] track failed', eventType, e);
390
+ }
391
+ }
392
+
393
+ function identify(userId) {
394
+ var api = getApi();
395
+ if (!api) return;
396
+ try { api.identify(userId); } catch (e) { /* noop */ }
397
+ }
398
+
399
+ function flush() {
400
+ var api = getApi();
401
+ if (!api) return Promise.resolve();
402
+ try { return api.flush(); } catch (e) { return Promise.resolve(); }
403
+ }
404
+
405
+ // ─── 4. Browser-side enrichment ──────────────────────────
406
+ // Each event picks up these as `custom_dimensions` so reports can break
407
+ // traffic down by browser, screen, timezone, etc. without per-event work.
408
+ function detectBrowser() {
409
+ var ua = (navigator && navigator.userAgent) || '';
410
+ var rules = [
411
+ { name: 'Edge', re: /\bEdg(?:e|A|iOS)?\/([\d\.]+)/i },
412
+ { name: 'Opera', re: /\bOPR\/([\d\.]+)/i },
413
+ { name: 'Samsung', re: /\bSamsungBrowser\/([\d\.]+)/i },
414
+ { name: 'Firefox', re: /\bFirefox\/([\d\.]+)/i },
415
+ { name: 'Chrome', re: /\bChrom(?:e|ium)\/([\d\.]+)/i },
416
+ { name: 'Safari', re: /\bVersion\/([\d\.]+).*Safari\b/i },
417
+ { name: 'IE', re: /\bMSIE\s([\d\.]+)|\bTrident\/.*\brv:([\d\.]+)/i }
418
+ ];
419
+ for (var i = 0; i < rules.length; i++) {
420
+ var m = ua.match(rules[i].re);
421
+ if (m) {
422
+ return { name: rules[i].name, version: (m[1] || m[2] || '').split('.')[0] };
423
+ }
424
+ }
425
+ return { name: 'Other', version: '' };
426
+ }
427
+
428
+ function safeStr(v) {
429
+ return (v === undefined || v === null) ? '' : String(v);
430
+ }
431
+
432
+ function getViewportSize() {
433
+ try {
434
+ var w = window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || 0;
435
+ var h = window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || 0;
436
+ return w && h ? (w + 'x' + h) : '';
437
+ } catch (e) { return ''; }
438
+ }
439
+
440
+ function getScreenResolution() {
441
+ try {
442
+ var s = window.screen || {};
443
+ var w = s.width || 0;
444
+ var h = s.height || 0;
445
+ return w && h ? (w + 'x' + h) : '';
446
+ } catch (e) { return ''; }
447
+ }
448
+
449
+ function getIanaTimezone() {
450
+ try {
451
+ if (typeof Intl !== 'undefined' && Intl.DateTimeFormat) {
452
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || '';
453
+ }
454
+ } catch (e) { /* noop */ }
455
+ return '';
456
+ }
457
+
458
+ function getColorScheme() {
459
+ try {
460
+ if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) return 'dark';
461
+ if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) return 'light';
462
+ } catch (e) { /* noop */ }
463
+ return '';
464
+ }
465
+
466
+ function buildEnrichmentDims() {
467
+ var browser = detectBrowser();
468
+ var dims = {
469
+ client_app: 'publicis-ps',
470
+ client_origin: location.origin,
471
+ client_tenant: TENANT_ID,
472
+ client_site: SITE_ID,
473
+ browser_name: browser.name,
474
+ browser_version: browser.version,
475
+ viewport_size: getViewportSize(),
476
+ screen_resolution: getScreenResolution(),
477
+ timezone_iana: getIanaTimezone(),
478
+ language_full: safeStr(navigator && navigator.language),
479
+ color_scheme: getColorScheme()
480
+ };
481
+ var clean = {};
482
+ for (var k in dims) {
483
+ if (dims.hasOwnProperty(k) && dims[k] !== '' && dims[k] !== undefined) {
484
+ clean[k] = dims[k];
485
+ }
486
+ }
487
+ return clean;
488
+ }
489
+
490
+ // ─── 5. SDK initialization ───────────────────────────────
491
+ function initSdk() {
492
+ var api = getApi();
493
+ if (!api) return false;
494
+ try {
495
+ api.init({
496
+ serverUrl: SERVER_URL,
497
+ tenantId: TENANT_ID,
498
+ siteId: SITE_ID,
499
+ dbName: DB_NAME,
500
+ debug: !!window.IL_DEBUG,
501
+ captureLocation: window.IL_CAPTURE_LOCATION === true,
502
+ globalDimensions: buildEnrichmentDims()
503
+ });
504
+ } catch (e) {
505
+ console.error('[IL-VISA] init failed', e);
506
+ return false;
507
+ }
508
+ return true;
509
+ }
510
+
511
+ // ─── 6. DOM + URL helpers ────────────────────────────────
512
+ function $(selectorList) {
513
+ if (!selectorList) return null;
514
+ try {
515
+ return document.querySelector(selectorList);
516
+ } catch (e) {
517
+ return null;
518
+ }
519
+ }
520
+
521
+ function visibleText(el) {
522
+ if (!el) return '';
523
+ var t = el.textContent || el.value || el.getAttribute('aria-label') || '';
524
+ return t.replace(/\s+/g, ' ').trim();
525
+ }
526
+
527
+ function closestMatchByText(root, tag, pattern) {
528
+ var nodes = root.querySelectorAll(tag);
529
+ for (var i = 0; i < nodes.length; i++) {
530
+ if (pattern.test(visibleText(nodes[i]))) {
531
+ return nodes[i];
532
+ }
533
+ }
534
+ return null;
535
+ }
536
+
537
+ /**
538
+ * Login-page heuristic: explicit URL hint, or DOM signals (password input
539
+ * inside a form). Anything that matches counts — false positives are
540
+ * harmless (just adds a `login_page` subtype to the page-view).
541
+ */
542
+ function isLoginPage() {
543
+ var href = (location.pathname + location.search + location.hash).toLowerCase();
544
+ if (/(^|\/)login(\.|\/|$|\?)/.test(href)) return true;
545
+ if (/signin/.test(href)) return true;
546
+ if (document.querySelector('input[type="password"]')) return true;
547
+ return false;
548
+ }
549
+
550
+ /**
551
+ * Parses `location.search` into a flat key→value (or key→string[]) map,
552
+ * URL-decoding both keys and values and tolerating duplicate keys.
553
+ */
554
+ function parseQuery() {
555
+ var out = {};
556
+ var qs = (location.search || '').replace(/^\?/, '');
557
+ if (!qs) return out;
558
+ var parts = qs.split('&');
559
+ for (var i = 0; i < parts.length; i++) {
560
+ if (!parts[i]) continue;
561
+ var eqIdx = parts[i].indexOf('=');
562
+ var k = eqIdx >= 0 ? parts[i].slice(0, eqIdx) : parts[i];
563
+ var v = eqIdx >= 0 ? parts[i].slice(eqIdx + 1) : '';
564
+ try { k = decodeURIComponent(k.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
565
+ try { v = decodeURIComponent(v.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
566
+ if (out[k] === undefined) out[k] = v;
567
+ else if (Array.isArray(out[k])) out[k].push(v);
568
+ else out[k] = [out[k], v];
569
+ }
570
+ return out;
571
+ }
572
+
573
+ /**
574
+ * Parses a form-encoded body (POST request) into a flat map. Accepts a
575
+ * raw string, a FormData, or a URLSearchParams. Returns {} on any error.
576
+ */
577
+ function parseFormBody(body) {
578
+ var out = {};
579
+ if (!body) return out;
580
+ try {
581
+ if (typeof FormData !== 'undefined' && body instanceof FormData) {
582
+ body.forEach(function (v, k) { if (!(k in out)) out[k] = String(v); });
583
+ return out;
584
+ }
585
+ if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
586
+ body.forEach(function (v, k) { if (!(k in out)) out[k] = String(v); });
587
+ return out;
588
+ }
589
+ } catch (e) { /* fall through to string parse */ }
590
+
591
+ var s = typeof body === 'string' ? body : '';
592
+ if (!s) return out;
593
+ var parts = s.split('&');
594
+ for (var i = 0; i < parts.length; i++) {
595
+ var p = parts[i];
596
+ if (!p) continue;
597
+ var eqIdx = p.indexOf('=');
598
+ var k = eqIdx >= 0 ? p.slice(0, eqIdx) : p;
599
+ var v = eqIdx >= 0 ? p.slice(eqIdx + 1) : '';
600
+ try { k = decodeURIComponent(k.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
601
+ try { v = decodeURIComponent(v.replace(/\+/g, ' ')); } catch (e) { /* keep raw */ }
602
+ if (!(k in out)) out[k] = v;
603
+ }
604
+ return out;
605
+ }
606
+
607
+ /**
608
+ * ASC encodes search-rail filters into the URL using indexed groups, e.g.:
609
+ * 0_group.propertyvalues.property = jcr:content/metadata/ps:assettype
610
+ * 0_group.propertyvalues.operation = equals
611
+ * 0_group.propertyvalues.0_values = Image
612
+ * 1_group.propertyvalues.property = ...
613
+ *
614
+ * This helper walks the parsed query string, buckets params by their
615
+ * `<idx>_group.` prefix, and returns a normalized array of
616
+ * { group, property, operation, values: [...] }
617
+ * suitable for JSON-serializing into a single dimension.
618
+ */
619
+ function extractFilters(q) {
620
+ var groups = {};
621
+ for (var k in q) {
622
+ if (!q.hasOwnProperty(k)) continue;
623
+ var m = k.match(/^(\d+)_group\.(.+)$/);
624
+ if (!m) continue;
625
+ var idx = m[1];
626
+ var rest = m[2];
627
+ if (!groups[idx]) groups[idx] = {};
628
+ groups[idx][rest] = q[k];
629
+ }
630
+ var list = [];
631
+ var keys = Object.keys(groups).sort(function (a, b) { return parseInt(a, 10) - parseInt(b, 10); });
632
+ for (var i = 0; i < keys.length; i++) {
633
+ var g = groups[keys[i]];
634
+ var prop = g['propertyvalues.property'] || g['property.property'] || '';
635
+ var op = g['propertyvalues.operation'] || g['property.operation'] || 'equals';
636
+ var values = [];
637
+ for (var p in g) {
638
+ if (!g.hasOwnProperty(p)) continue;
639
+ // `propertyvalues.0_values`, `propertyvalues.1_values`, ...
640
+ // or `property.0_value`, or singular `value` / `values`.
641
+ if (/^propertyvalues\.\d+_values$|^property\.\d+_value$|^propertyvalues\.values?$|^property\.values?$/.test(p)) {
642
+ var raw = g[p];
643
+ if (Array.isArray(raw)) {
644
+ for (var j = 0; j < raw.length; j++) values.push(raw[j]);
645
+ } else {
646
+ values.push(raw);
647
+ }
648
+ }
649
+ }
650
+ if (prop || values.length) {
651
+ list.push({ group: keys[i], property: prop, operation: op, values: values });
652
+ }
653
+ }
654
+ return list;
655
+ }
656
+
657
+ /**
658
+ * Locates the ASC right-rail filter container.
659
+ *
660
+ * The visible filter sections (ASSET TYPE, MARKETING FUNCTION / INDUSTRY,
661
+ * APPLICATION & USE, ORIGIN, ASSET USAGE RIGHTS, LANGUAGE / REGION, YEAR,
662
+ * LAST MODIFIED, CREATED, …) live inside this container along with the
663
+ * hidden inputs that ASC's predicate components use to encode the
664
+ * `<idx>_group.propertyvalues.property` URL params.
665
+ */
666
+ function findFilterRail() {
667
+ return $(SELECTORS.filterRail);
668
+ }
669
+
670
+ function cleanText(s) {
671
+ return (s == null ? '' : String(s)).replace(/\s+/g, ' ').trim();
672
+ }
673
+
674
+ /**
675
+ * Builds a property → human-readable label map by scanning the rail for
676
+ * predicate blocks. Each ASC predicate (`cmp-predicate`) carries a hidden
677
+ * `…propertyvalues.property` input and a visible heading. We walk up from
678
+ * the hidden input until we find the predicate block, then take its
679
+ * heading text as the label.
680
+ *
681
+ * Returns e.g.
682
+ * { 'jcr:content/metadata/ps:assettype': 'ASSET TYPE',
683
+ * 'jcr:content/metadata/cq:tags': 'MARKETING FUNCTION / INDUSTRY',
684
+ * ... }
685
+ */
686
+ function buildPropertyLabelMap(rail) {
687
+ var map = {};
688
+ if (!rail || !rail.querySelectorAll) return map;
689
+ var propInputs;
690
+ try {
691
+ // Hidden inputs whose name ends with `.property` or `.propertyvalues.property`.
692
+ propInputs = rail.querySelectorAll(
693
+ 'input[name$=".property"], ' +
694
+ 'input[name$=".propertyvalues.property"], ' +
695
+ '[data-cmp-predicate-property]'
696
+ );
697
+ } catch (e) { return map; }
698
+
699
+ for (var i = 0; i < propInputs.length; i++) {
700
+ var node = propInputs[i];
701
+ var prop = (node.tagName === 'INPUT' ? node.value : node.getAttribute('data-cmp-predicate-property')) || '';
702
+ prop = String(prop);
703
+ if (!prop || map[prop]) continue;
704
+
705
+ var section = (node.closest && node.closest(
706
+ '.cmp-predicate, [data-cmp-is="predicate"], .predicate, ' +
707
+ '.cmp-search-predicate, .filter-section, section, fieldset'
708
+ )) || node.parentNode;
709
+
710
+ // Walk up looking for a section heading. Stop at the rail boundary
711
+ // so we don't accidentally pick up the entire panel's outer label.
712
+ while (section && section !== rail && section.nodeType === 1) {
713
+ var heading = section.querySelector(
714
+ '.cmp-predicate__title, [data-cmp-hook-predicate-title], ' +
715
+ '[data-predicate-title], legend, h2, h3, h4, h5, ' +
716
+ '.predicate-title, .filter-title'
717
+ );
718
+ if (heading && cleanText(heading.textContent)) {
719
+ map[prop] = cleanText(heading.textContent);
720
+ break;
721
+ }
722
+ section = section.parentNode;
723
+ }
724
+ }
725
+ return map;
726
+ }
727
+
728
+ /**
729
+ * Scans the rail for currently-selected filter inputs and groups them by
730
+ * the visible section heading they live under. This is a belt-and-braces
731
+ * capture: it picks up predicates whose state lives only in the DOM (and
732
+ * isn't visible in the URL) — and it lets us emit a clean
733
+ * [{ name: "ASSET TYPE", values: ["Image"] }, ...]
734
+ * even when the property→label map didn't resolve.
735
+ */
736
+ function scanRailSelectedFilters(rail) {
737
+ if (!rail || !rail.querySelectorAll) return [];
738
+ var groupsByLabel = {};
739
+
740
+ var selected;
741
+ try {
742
+ selected = rail.querySelectorAll(
743
+ 'input[type="checkbox"]:checked, ' +
744
+ 'input[type="radio"]:checked, ' +
745
+ '[aria-checked="true"], ' +
746
+ '[data-selected="true"], ' +
747
+ '.is-selected:not(.disabled), ' +
748
+ '.cmp-predicate__option--selected'
749
+ );
750
+ } catch (e) { return []; }
751
+
752
+ for (var i = 0; i < selected.length; i++) {
753
+ var n = selected[i];
754
+ // Hidden, submit, and button inputs are infrastructure, not selections.
755
+ if (n.type === 'hidden' || n.type === 'submit' || n.type === 'button') continue;
756
+
757
+ // Prefer the visible label associated with the input.
758
+ var value = '';
759
+ try {
760
+ if (n.labels && n.labels.length) value = cleanText(n.labels[0].textContent);
761
+ } catch (e) { /* `labels` not supported */ }
762
+ if (!value) {
763
+ var labelEl = (n.closest && n.closest('label')) || null;
764
+ if (labelEl) value = cleanText(labelEl.textContent);
765
+ }
766
+ if (!value) value = cleanText(n.value);
767
+ if (!value || value.toLowerCase() === 'on') continue;
768
+
769
+ // Walk up to the predicate section + its heading.
770
+ var label = '';
771
+ var section = (n.closest && n.closest(
772
+ '.cmp-predicate, [data-cmp-is="predicate"], .predicate, ' +
773
+ '.cmp-search-predicate, .filter-section, section, fieldset'
774
+ )) || null;
775
+ var cur = section;
776
+ while (cur && cur !== rail && cur.nodeType === 1) {
777
+ var heading = cur.querySelector(
778
+ '.cmp-predicate__title, [data-cmp-hook-predicate-title], ' +
779
+ '[data-predicate-title], legend, h2, h3, h4, h5, ' +
780
+ '.predicate-title, .filter-title'
781
+ );
782
+ if (heading && cleanText(heading.textContent)) {
783
+ label = cleanText(heading.textContent);
784
+ break;
785
+ }
786
+ cur = cur.parentNode;
787
+ }
788
+ if (!label) label = 'filter';
789
+
790
+ if (!groupsByLabel[label]) groupsByLabel[label] = [];
791
+ if (groupsByLabel[label].indexOf(value) === -1) groupsByLabel[label].push(value);
792
+ }
793
+
794
+ var out = [];
795
+ for (var k in groupsByLabel) {
796
+ if (groupsByLabel.hasOwnProperty(k)) out.push({ name: k, values: groupsByLabel[k] });
797
+ }
798
+ return out;
799
+ }
800
+
801
+ /**
802
+ * Parses a stat value text into a Float64. Tolerates thousand separators,
803
+ * whitespace, and trailing unit suffixes like "ms", "s", "seconds".
804
+ * Returns null when the text doesn't contain a usable number.
805
+ */
806
+ function parseStatNumber(txt) {
807
+ if (txt == null) return null;
808
+ var s = String(txt).replace(/[\s,]/g, '');
809
+ var m = s.match(/-?\d+(?:\.\d+)?/);
810
+ if (!m) return null;
811
+ var n = parseFloat(m[0]);
812
+ return isFinite(n) ? n : null;
813
+ }
814
+
815
+ /**
816
+ * Classifies a stat-widget label to one of the metrics we surface.
817
+ *
818
+ * Observed ASC label variants (verified against `visa-sit.productioncloud.io`
819
+ * search-stats raw_json captured 2026-05-28):
820
+ * "Displayed" → result_displayed (count shown on current page)
821
+ * "Total" → result_total (total assets matched)
822
+ * "Milliseconds" → search_time_ms (server-side query latency)
823
+ * And the wider OOTB ASC family:
824
+ * "Time", "Time (ms)", "Search Time", "Elapsed", "Duration",
825
+ * "Latency", "Response" → search_time_ms
826
+ * "Seconds" → search_time_ms (×1000 → ms)
827
+ * "Assets", "Results", "Hits", "Matches", "Found", "Count"
828
+ * → result_total
829
+ * "Pages" → result_pages
830
+ * "Showing", "Shown" → result_displayed (alternate displayed labels)
831
+ *
832
+ * Returns null for unrecognized labels — the caller must not invent an
833
+ * attribution from position alone unless EVERY label in the widget came
834
+ * back null (see readSearchStatistics() pass 2).
835
+ */
836
+ function classifyStatLabel(label) {
837
+ var s = String(label || '').toLowerCase();
838
+ if (!s) return null;
839
+ if (/\b(millisecond|msec|\bms\b)/.test(s)) return { key: 'time_ms', unit: 'ms' };
840
+ if (/\b(second|\bs\b)\b/.test(s)) return { key: 'time_ms', unit: 's' };
841
+ if (/\b(time|elapsed|duration|latency|response)\b/.test(s))
842
+ return { key: 'time_ms', unit: 'ms' };
843
+ if (/\b(displayed|showing|shown|visible)\b/.test(s))
844
+ return { key: 'displayed', unit: '' };
845
+ if (/\b(asset|result|hit|match|found|total|count)\b/.test(s))
846
+ return { key: 'total', unit: '' };
847
+ if (/\bpages?\b/.test(s)) return { key: 'pages', unit: '' };
848
+ return null;
849
+ }
850
+
851
+ /**
852
+ * Reads the ASC `cmp-search-statistics` widget into a normalized shape:
853
+ * { container,
854
+ * stats: {
855
+ * time_ms, total, pages,
856
+ * raw, // [{ idx, label, value }] in DOM order — diagnostic
857
+ * claimed // Set<idx> of blocks already attributed to a metric
858
+ * }
859
+ * }
860
+ * `time_ms`, `total`, `pages` are Float64s (or null when not displayed);
861
+ * `raw` is an ordered list so we can inspect classifier mistakes from
862
+ * the back-end (we JSON-serialize it onto every search_executed event
863
+ * as `custom_dimensions.search_stats_raw_json`). Returns
864
+ * `{ container: <el|null>, stats: null }` when the widget hasn't been
865
+ * mounted yet OR has no populated `.value` cells.
866
+ *
867
+ * Positional fallback (1st=total, 2nd=time_ms, 3rd=pages) only fires
868
+ * for blocks NOT already claimed by the label classifier — so a single
869
+ * cell can never be attributed to two metrics at once.
870
+ */
871
+ function readSearchStatistics() {
872
+ var container = $(SELECTORS.searchStatistics);
873
+ if (!container || !container.querySelectorAll) {
874
+ return { container: null, stats: null };
875
+ }
876
+
877
+ // First-pass: gather (index, label, value) tuples from every leaf
878
+ // `.statistic` block. We deliberately exclude the outer `.statistics`
879
+ // wrapper that `[class*="statistic"]` would otherwise match.
880
+ var statBlocks = container.querySelectorAll(
881
+ '.statistic, [class*="statistic"]:not(.statistics)'
882
+ );
883
+ var rows = [];
884
+ for (var i = 0; i < statBlocks.length; i++) {
885
+ var block = statBlocks[i];
886
+ if (block.querySelector && block.querySelector('.statistic')) continue;
887
+
888
+ var labelEl = block.querySelector('.label, [class*="label"]');
889
+ var valueEl = block.querySelector('.value, [class*="value"]');
890
+ if (!valueEl) continue;
891
+
892
+ var labelText = labelEl ? cleanText(labelEl.textContent) : '';
893
+ var rawText = cleanText(valueEl.textContent);
894
+ var n = parseStatNumber(rawText);
895
+ rows.push({ idx: rows.length, label: labelText, valueText: rawText, value: n });
896
+ }
897
+ if (!rows.length || !rows.some(function (r) { return r.value !== null; })) {
898
+ return { container: container, stats: null };
899
+ }
900
+
901
+ var stats = {
902
+ time_ms: null,
903
+ total: null,
904
+ pages: null,
905
+ displayed: null,
906
+ raw: rows.map(function (r) { return { idx: r.idx, label: r.label, value: r.valueText }; })
907
+ };
908
+ var claimed = {};
909
+ var anyClassified = false;
910
+
911
+ // Pass 1: label-driven classification — authoritative whenever the
912
+ // label is recognized. Skips blocks whose `.value` was empty.
913
+ for (var k = 0; k < rows.length; k++) {
914
+ var r = rows[k];
915
+ if (r.value === null) continue;
916
+ var c = classifyStatLabel(r.label);
917
+ if (!c) continue;
918
+ anyClassified = true;
919
+ // First match wins for each metric, so a duplicate label (rare) on
920
+ // a later block doesn't clobber an earlier one.
921
+ if (c.key === 'time_ms' && stats.time_ms === null) {
922
+ // Convert seconds → ms when label explicitly says seconds, so
923
+ // the metric column is always milliseconds regardless of label.
924
+ stats.time_ms = c.unit === 's' ? r.value * 1000 : r.value;
925
+ claimed[r.idx] = true;
926
+ } else if (c.key === 'total' && stats.total === null) {
927
+ stats.total = r.value;
928
+ claimed[r.idx] = true;
929
+ } else if (c.key === 'pages' && stats.pages === null) {
930
+ stats.pages = r.value;
931
+ claimed[r.idx] = true;
932
+ } else if (c.key === 'displayed' && stats.displayed === null) {
933
+ stats.displayed = r.value;
934
+ claimed[r.idx] = true;
935
+ }
936
+ }
937
+
938
+ // Pass 2: positional fallback. We deliberately keep this STRICT — it
939
+ // only fires when *no* label in the widget was recognized at all (a
940
+ // re-themed deployment with non-English / custom labels). Otherwise we
941
+ // trust the labels we DID recognize and leave any unclassified blocks
942
+ // out of the event, so an unrelated tile (e.g. "Displayed") can never
943
+ // bleed into `result_pages` or `search_time_ms`.
944
+ if (!anyClassified) {
945
+ // Stock ASC OOTB column order: 1) total assets, 2) time (ms), 3) pages.
946
+ if (rows[0] && rows[0].value !== null) {
947
+ stats.total = rows[0].value;
948
+ claimed[rows[0].idx] = true;
949
+ }
950
+ if (rows[1] && rows[1].value !== null) {
951
+ stats.time_ms = rows[1].value;
952
+ claimed[rows[1].idx] = true;
953
+ }
954
+ if (rows[2] && rows[2].value !== null) {
955
+ stats.pages = rows[2].value;
956
+ claimed[rows[2].idx] = true;
957
+ }
958
+ }
959
+
960
+ return { container: container, stats: stats };
961
+ }
962
+
963
+ /**
964
+ * Waits for a search-statistics widget to be populated for the CURRENT
965
+ * search and then invokes `cb(stats)`. Falls back to `cb(stats|null)`
966
+ * after `timeoutMs` (default 3000) so the search_executed event is never
967
+ * silenced indefinitely just because the widget didn't show up.
968
+ *
969
+ * `reader` is the page-specific stats-reader function returning the
970
+ * shared `{ container, stats: { time_ms, total, pages, displayed, raw } }`
971
+ * shape — `readSearchStatistics` for ASC, `readAssetExplorerSearchStatistics`
972
+ * for the React-based explorer. This way the wait/observe/baseline logic
973
+ * is written once and both contexts get the same race-safety guarantees.
974
+ *
975
+ * On the first invocation per page load the currently-displayed value is
976
+ * trusted (server-side rendered for the URL we just loaded). On every
977
+ * subsequent invocation — i.e. a pushState navigation — we cache the
978
+ * pre-call snapshot and require a MutationObserver hit AND a value
979
+ * difference vs the snapshot before resolving. That avoids attributing
980
+ * the previous search's "Time" reading to the new search.
981
+ *
982
+ * Returns a `cancel()` function so a fresh search that fires before the
983
+ * previous wait completes can abort the previous wait without leaving
984
+ * dangling observers.
985
+ */
986
+ function waitForSearchStats(reader, timeoutMs, cb) {
987
+ var read = typeof reader === 'function' ? reader : readSearchStatistics;
988
+ var done = false;
989
+ var mo = null;
990
+ var timer = null;
991
+
992
+ function teardown() {
993
+ if (mo) { try { mo.disconnect(); } catch (e) {} mo = null; }
994
+ if (timer) { clearTimeout(timer); timer = null; }
995
+ }
996
+
997
+ function finish(stats) {
998
+ if (done) return;
999
+ done = true;
1000
+ teardown();
1001
+ try { cb(stats); } catch (e) { /* swallow */ }
1002
+ }
1003
+
1004
+ var initial = read();
1005
+ var baselineTime = initial.stats ? initial.stats.time_ms : null;
1006
+ var baselineTot = initial.stats ? initial.stats.total : null;
1007
+
1008
+ // First search of the page: the widget's current value WAS rendered for
1009
+ // this URL (either SSR or by the SDK's earlier auto-init pass), so we
1010
+ // can fire immediately.
1011
+ if (__searchFireCount === 0 && initial.stats && baselineTime !== null) {
1012
+ finish(initial.stats);
1013
+ return function noopCancel() {};
1014
+ }
1015
+
1016
+ var observeRoot = initial.container || document.body || document.documentElement;
1017
+
1018
+ timer = setTimeout(function () {
1019
+ // Hard timeout: fire with whatever the widget is showing right now,
1020
+ // even if it didn't change from the baseline. Better to record the
1021
+ // search with no time than to drop it.
1022
+ var late = read();
1023
+ finish(late.stats || null);
1024
+ }, timeoutMs || 3000);
1025
+
1026
+ if (typeof MutationObserver === 'function' && observeRoot) {
1027
+ try {
1028
+ mo = new MutationObserver(function () {
1029
+ var probe = read();
1030
+ if (!probe.stats || probe.stats.time_ms === null) return;
1031
+ // Require at least one of the two key cells to have changed vs
1032
+ // baseline. Cards, pagination, and skeleton loaders also mutate
1033
+ // the DOM while the search XHR is in flight — we don't want any
1034
+ // of those to count as "stats ready".
1035
+ if (probe.stats.time_ms !== baselineTime || probe.stats.total !== baselineTot) {
1036
+ finish(probe.stats);
1037
+ }
1038
+ });
1039
+ mo.observe(observeRoot, {
1040
+ childList: true,
1041
+ subtree: true,
1042
+ characterData: true
1043
+ });
1044
+ } catch (e) { /* fall back to timer-only path */ }
1045
+ }
1046
+
1047
+ return function cancel() {
1048
+ if (done) return;
1049
+ done = true;
1050
+ teardown();
1051
+ };
1052
+ }
1053
+
1054
+ /**
1055
+ * Pretty-fallback when the property→label map didn't have an entry. Picks
1056
+ * the most meaningful trailing token of a JCR-style path so reports don't
1057
+ * have to render `jcr:content/metadata/ps:assettype` unaltered.
1058
+ *
1059
+ * jcr:content/metadata/ps:assettype → ps:assettype
1060
+ * jcr:content/metadata/cq:tags → cq:tags
1061
+ * jcr:content/jcr:lastModified → jcr:lastModified
1062
+ */
1063
+ function deriveFallbackName(prop) {
1064
+ if (!prop) return '';
1065
+ var s = String(prop);
1066
+ var slash = s.lastIndexOf('/');
1067
+ return slash >= 0 ? s.slice(slash + 1) : s;
1068
+ }
1069
+
1070
+ /**
1071
+ * Detects an asset-preview / details URL anywhere in the path. Matches
1072
+ * both layouts we've observed on visa-sit.productioncloud.io:
1073
+ *
1074
+ * ASC (root-level):
1075
+ * /details/image.html/content/dam/ps/branded-assets/Rolex-1.jpeg
1076
+ *
1077
+ * Asset Explorer (nested under the AEM page path):
1078
+ * /content/ps/global/us/en/home/asset-explorer/details/image.html/content/dam/ps/brand-toolkit/bmwi4_029.jpg
1079
+ *
1080
+ * We deliberately require the captured `assetPath` to start with
1081
+ * `/content/`, so a page accidentally named `details.html` somewhere else
1082
+ * in the tree can't match. Returns null when the URL isn't a details
1083
+ * page in either layout.
1084
+ */
1085
+ function detectDetailsAssetPath() {
1086
+ var m = location.pathname.match(/\/details\/([^/]+)\.html(\/content\/.+)$/);
1087
+ if (!m) return null;
1088
+ return { assetType: m[1], assetPath: m[2] };
1089
+ }
1090
+
1091
+ /**
1092
+ * Walks up from a clicked element looking for a DAM asset path:
1093
+ * 1. `data-asset-path`, `data-asset`, `data-cmp-asset`, or
1094
+ * `data-foundation-collection-item-id` carrying `/content/dam/…`.
1095
+ * 2. An ancestor `<a href="/details/…">` from which we extract the path.
1096
+ * Returns '' if nothing matches.
1097
+ */
1098
+ function extractAssetPathFromEl(el) {
1099
+ var cur = el;
1100
+ while (cur && cur !== document.body && cur.nodeType === 1) {
1101
+ // `data-asset-share-asset` is the ASC convention used by the
1102
+ // explorer tiles (`<button data-asset-share-id="add-to-cart"
1103
+ // data-asset-share-asset="/content/dam/...">`). Check it first so
1104
+ // we don't accidentally walk up to a card-level fallback when the
1105
+ // button itself already carries the precise asset.
1106
+ var dataAttrs = [
1107
+ 'data-asset-share-asset',
1108
+ 'data-asset-path',
1109
+ 'data-asset',
1110
+ 'data-cmp-asset',
1111
+ 'data-foundation-collection-item-id',
1112
+ 'data-path'
1113
+ ];
1114
+ for (var i = 0; i < dataAttrs.length; i++) {
1115
+ var v = cur.getAttribute && cur.getAttribute(dataAttrs[i]);
1116
+ if (v && /^\/content\/dam\//.test(v)) return v;
1117
+ }
1118
+ var href = (cur.getAttribute && (cur.getAttribute('data-href') || cur.getAttribute('href'))) || '';
1119
+ if (href) {
1120
+ var mm = href.match(/\/details\/[^/]+\.html(\/content\/dam\/[^\s?#]+)/);
1121
+ if (mm) return mm[1];
1122
+ }
1123
+ cur = cur.parentNode;
1124
+ }
1125
+ return '';
1126
+ }
1127
+
1128
+ /**
1129
+ * Parses a URL or query-string fragment into a plain object. Trivial
1130
+ * shim around `URLSearchParams` that survives IE / older Safari where
1131
+ * the constructor isn't available. Used to pull `downloadId` and
1132
+ * `artifactId` from the asset-download anchor href.
1133
+ */
1134
+ function parseUrlParams(href) {
1135
+ var out = {};
1136
+ if (!href) return out;
1137
+ var q = String(href);
1138
+ var hashIdx = q.indexOf('#');
1139
+ if (hashIdx >= 0) q = q.slice(0, hashIdx);
1140
+ var qIdx = q.indexOf('?');
1141
+ if (qIdx < 0) return out;
1142
+ var pairs = q.slice(qIdx + 1).split('&');
1143
+ for (var i = 0; i < pairs.length; i++) {
1144
+ var kv = pairs[i].split('=');
1145
+ if (!kv[0]) continue;
1146
+ var k, v;
1147
+ try { k = decodeURIComponent(kv[0].replace(/\+/g, ' ')); } catch (e) { k = kv[0]; }
1148
+ try { v = kv.length > 1 ? decodeURIComponent(kv[1].replace(/\+/g, ' ')) : ''; } catch (e) { v = kv[1] || ''; }
1149
+ out[k] = v;
1150
+ }
1151
+ return out;
1152
+ }
1153
+
1154
+ /**
1155
+ * Reads the current contents of the ASC cart modal (if open). Returns
1156
+ * an array of unique `/content/dam/...` paths discovered via, in
1157
+ * order:
1158
+ *
1159
+ * 1. `data-asset-share-asset` attributes (preferred — the cart
1160
+ * template renders these on each row),
1161
+ * 2. `data-asset-path` / `data-asset` / `data-cmp-asset` as
1162
+ * fallbacks for older / themed ASC builds,
1163
+ * 3. `<a href="/.../details/<type>.html/content/dam/...">` links,
1164
+ * 4. hidden `<input name="path">` form fields (legacy ASC).
1165
+ *
1166
+ * Returns `[]` when the modal isn't currently in the DOM — the
1167
+ * caller can attach an empty `cart_asset_paths_json=""` and a
1168
+ * `cart_item_count=0` so reports can distinguish "no cart open" from
1169
+ * "cart open but empty".
1170
+ */
1171
+ function readCartContents() {
1172
+ var modal = document.querySelector(SELECTORS.cartModal);
1173
+ if (!modal) return [];
1174
+ var paths = [];
1175
+ var seen = {};
1176
+ function add(p) {
1177
+ if (!p) return;
1178
+ if (!/^\/content\/dam\//.test(p)) return;
1179
+ if (seen[p]) return;
1180
+ seen[p] = true;
1181
+ paths.push(p);
1182
+ }
1183
+ var attrAttempts = ['data-asset-share-asset', 'data-asset-path', 'data-asset', 'data-cmp-asset'];
1184
+ for (var a = 0; a < attrAttempts.length; a++) {
1185
+ var els = modal.querySelectorAll('[' + attrAttempts[a] + ']');
1186
+ for (var i = 0; i < els.length; i++) {
1187
+ add(els[i].getAttribute(attrAttempts[a]));
1188
+ }
1189
+ }
1190
+ var anchors = modal.querySelectorAll('a[href*="/details/"]');
1191
+ for (var j = 0; j < anchors.length; j++) {
1192
+ var href = anchors[j].getAttribute('href') || '';
1193
+ var m = href.match(/\/details\/[^/]+\.html(\/content\/dam\/[^\s?#]+)/);
1194
+ if (m) add(m[1]);
1195
+ }
1196
+ var inputs = modal.querySelectorAll('input[name="path"], input[name="paths"]');
1197
+ for (var k = 0; k < inputs.length; k++) {
1198
+ add(inputs[k].value);
1199
+ }
1200
+ return paths;
1201
+ }
1202
+
1203
+ // ─── 7. User identity resolution ─────────────────────────
1204
+ function readCachedUserId() {
1205
+ try { return localStorage.getItem(CACHE_KEY_USER) || ''; } catch (e) { return ''; }
1206
+ }
1207
+ function writeCachedUserId(u) {
1208
+ try { localStorage.setItem(CACHE_KEY_USER, String(u || '')); } catch (e) { /* private mode etc. */ }
1209
+ }
1210
+
1211
+ /**
1212
+ * Resolves the AEM authorizable id of the currently logged-in user.
1213
+ * Resolution order:
1214
+ * 1. host-page-provided `window.IL_VISA_USER_RESOLVER` (sync string or Promise)
1215
+ * 2. `<meta name="cq:user" | "user" | "user-id">`
1216
+ * 3. `/libs/granite/security/currentuser.json` (Granite endpoint)
1217
+ *
1218
+ * Calls `cb('')` for anonymous sessions; never throws.
1219
+ *
1220
+ * We deliberately use the unwrapped (pre-install) `fetch` so that our
1221
+ * own identity probe doesn't echo through the network interception
1222
+ * installed below for asset_download.
1223
+ */
1224
+ var ORIG_FETCH = (typeof window.fetch === 'function') ? window.fetch.bind(window) : null;
1225
+
1226
+ function resolveCurrentUser(cb) {
1227
+ try {
1228
+ if (typeof window.IL_VISA_USER_RESOLVER === 'function') {
1229
+ var v = window.IL_VISA_USER_RESOLVER();
1230
+ if (typeof v === 'string') { cb(v || ''); return; }
1231
+ if (v && typeof v.then === 'function') {
1232
+ v.then(function (s) { cb(typeof s === 'string' ? s : ''); }, function () { cb(''); });
1233
+ return;
1234
+ }
1235
+ }
1236
+ } catch (e) { /* fall through */ }
1237
+
1238
+ var meta = document.querySelector('meta[name="cq:user"], meta[name="user"], meta[name="user-id"]');
1239
+ if (meta && meta.getAttribute('content')) { cb(meta.getAttribute('content')); return; }
1240
+
1241
+ if (ORIG_FETCH) {
1242
+ ORIG_FETCH(CURRENT_USER_ENDPOINT, {
1243
+ credentials: 'same-origin',
1244
+ headers: { 'Accept': 'application/json' }
1245
+ })
1246
+ .then(function (r) { return r && r.ok ? r.json() : null; })
1247
+ .then(function (j) {
1248
+ if (!j) { cb(''); return; }
1249
+ cb(j.authorizableId || j.id || j.userId || j.name || '');
1250
+ })
1251
+ .catch(function () { cb(''); });
1252
+ return;
1253
+ }
1254
+ cb('');
1255
+ }
1256
+
1257
+ function resolveAndIdentifyUser() {
1258
+ var cached = readCachedUserId();
1259
+ if (cached) identify(cached);
1260
+ resolveCurrentUser(function (u) {
1261
+ if (u && u !== cached) {
1262
+ writeCachedUserId(u);
1263
+ identify(u);
1264
+ }
1265
+ });
1266
+ }
1267
+
1268
+ // ─── 8. URL-driven events ────────────────────────────────
1269
+
1270
+ // Cross-call state for trackSearchExecuted ↔ waitForSearchStats. Kept at
1271
+ // the bootstrap scope (not per-call) so we can flush an in-flight wait
1272
+ // when the user navigates to a new search before the previous one's
1273
+ // statistics widget finished updating — otherwise the old call's
1274
+ // MutationObserver would pick up the NEW search's stats.
1275
+ var __searchFireCount = 0;
1276
+ var __cancelInflightStatsWait = null;
1277
+ var __flushInflightSearchNow = null;
1278
+
1279
+ /**
1280
+ * EVENT (login page only): Anonymous landing on the Login page.
1281
+ *
1282
+ * The SDK already auto-fires a `page_view` on every load (including this
1283
+ * one), but we add an explicit `login_page_view` event so the Reports
1284
+ * "login funnel" panel can distinguish login-page traffic from generic
1285
+ * site traffic and segment anonymous visitors before identify() fires.
1286
+ */
1287
+ function trackLoginPageView() {
1288
+ if (!isLoginPage()) return;
1289
+ track('login_page_view', {
1290
+ page_type: 'login',
1291
+ auth_state: 'anonymous',
1292
+ page_url: location.href,
1293
+ referrer: document.referrer || ''
1294
+ }, {}, 'anonymous');
1295
+ }
1296
+
1297
+ /**
1298
+ * EVENT 1 (search): fires when the current URL is a search-results page.
1299
+ *
1300
+ * ASC submits the search form via GET, so every search materializes as
1301
+ * a navigation. The new page-load runs this bootstrap fresh; if the URL
1302
+ * carries `?fulltext=…` we have a verified search execution AND all the
1303
+ * inputs the user supplied (term, semantic toggle, fuzzy toggle, rail
1304
+ * filters, ordering, layout, pagination) right there in the query string.
1305
+ *
1306
+ * This is more reliable than hooking the submit handler because it also
1307
+ * captures bookmarked searches, browser-back navigations, and shareable
1308
+ * search URLs — every one of which counts as a "search executed" event.
1309
+ */
1310
+ function trackSearchExecuted(q) {
1311
+ if (!q.hasOwnProperty('fulltext')) return;
1312
+
1313
+ // A new search arrived before the previous wait completed. Fire the
1314
+ // previous event NOW with whatever it has — we cannot let its
1315
+ // MutationObserver pick up THIS search's stats and mis-attribute them.
1316
+ if (__flushInflightSearchNow) {
1317
+ try { __flushInflightSearchNow(); } catch (e) {}
1318
+ __flushInflightSearchNow = null;
1319
+ }
1320
+ if (__cancelInflightStatsWait) {
1321
+ try { __cancelInflightStatsWait(); } catch (e) {}
1322
+ __cancelInflightStatsWait = null;
1323
+ }
1324
+
1325
+ // 1. URL is the canonical source of WHICH filters were applied — group,
1326
+ // property, operation, values are all encoded there.
1327
+ var urlFilters = extractFilters(q);
1328
+
1329
+ // 2. Enrich each URL filter with the human-readable section heading
1330
+ // from the right rail (ASSET TYPE, MARKETING FUNCTION / INDUSTRY,
1331
+ // APPLICATION & USE, ORIGIN, ASSET USAGE RIGHTS, LANGUAGE / REGION,
1332
+ // YEAR, LAST MODIFIED, CREATED, …). Falls back to the property's
1333
+ // trailing JCR segment if the rail isn't present (e.g. event fired
1334
+ // from a shared URL on a page without the rail).
1335
+ var rail = findFilterRail();
1336
+ var labelMap = buildPropertyLabelMap(rail);
1337
+ for (var i = 0; i < urlFilters.length; i++) {
1338
+ var f = urlFilters[i];
1339
+ f.name = labelMap[f.property] || deriveFallbackName(f.property);
1340
+ }
1341
+
1342
+ // 3. DOM-only sweep as a safety net — captures any predicate that is
1343
+ // selected in the rail but didn't appear in the URL (e.g. local UI
1344
+ // state that hadn't been submitted yet, or predicates encoded by a
1345
+ // non-standard component). Indexed by visible section heading so
1346
+ // reports can render it without per-filter mapping.
1347
+ var domFilters = scanRailSelectedFilters(rail);
1348
+
1349
+ var dims = {
1350
+ search_term: safeStr(q.fulltext),
1351
+ semantic_search: String(safeStr(q.semanticSearchEnabled).toLowerCase() === 'true'),
1352
+ fuzzy_search: String(safeStr(q.fuzzySearchEnabled).toLowerCase() === 'true'),
1353
+ filters_json: urlFilters.length ? JSON.stringify(urlFilters) : '',
1354
+ filters_dom_json: domFilters.length ? JSON.stringify(domFilters) : '',
1355
+ orderby: safeStr(q.orderby),
1356
+ order_dir: safeStr(q['orderby.sort']),
1357
+ layout: safeStr(q.layout),
1358
+ search_context: 'asc',
1359
+ page_url: location.href,
1360
+ page_referrer: document.referrer || ''
1361
+ };
1362
+ var metrics = {
1363
+ filter_count: urlFilters.length,
1364
+ filter_dom_count: domFilters.length,
1365
+ result_offset: parseInt(safeStr(q['p.offset']) || '0', 10) || 0,
1366
+ result_limit: parseInt(safeStr(q['p.limit']) || '0', 10) || 0
1367
+ };
1368
+
1369
+ var fired = false;
1370
+ function fireWithStats(stats) {
1371
+ if (fired) return;
1372
+ fired = true;
1373
+ __cancelInflightStatsWait = null;
1374
+ __flushInflightSearchNow = null;
1375
+
1376
+ if (stats) {
1377
+ if (stats.time_ms !== null) metrics.search_time_ms = stats.time_ms;
1378
+ if (stats.total !== null) metrics.result_total = stats.total;
1379
+ if (stats.pages !== null) metrics.result_pages = stats.pages;
1380
+ if (stats.displayed !== null) metrics.result_displayed = stats.displayed;
1381
+ dims.search_stats_ready = 'true';
1382
+ // Persist the raw label→value pairs in DOM order so any classifier
1383
+ // misattribution can be diagnosed from the back-end (e.g. ASC
1384
+ // re-labels "Time (ms)" → "Search Speed" in a future release).
1385
+ // Truncated to 240 chars to stay well under any ClickHouse Map
1386
+ // value size limit and avoid bloating event payloads.
1387
+ try {
1388
+ if (stats.raw && stats.raw.length) {
1389
+ var rawJson = JSON.stringify(stats.raw);
1390
+ dims.search_stats_raw_json = rawJson.length > 240
1391
+ ? rawJson.slice(0, 240)
1392
+ : rawJson;
1393
+ }
1394
+ } catch (e) { /* swallow */ }
1395
+ } else {
1396
+ dims.search_stats_ready = 'false';
1397
+ }
1398
+
1399
+ // Fourth arg is the event subtype — surfaces in ClickHouse's
1400
+ // event_subtype column. ASC fires our bootstrap once per full page
1401
+ // load, but also navigates via history.pushState when the user
1402
+ // tweaks a filter / pagination / layout / sort. We re-fire search
1403
+ // events on those pushState transitions too (see installSpaNavHooks
1404
+ // below), and tag both initial + SPA fires with the SAME subtype so
1405
+ // reports don't have to special-case how the URL was reached.
1406
+ track('search_executed', dims, metrics, 'asset_search');
1407
+ __searchFireCount++;
1408
+ }
1409
+
1410
+ // Stash a synchronous flush hook so the next trackSearchExecuted call
1411
+ // can force this one to fire (without stats) before starting its own
1412
+ // wait — see the early-return block at the top of this function.
1413
+ __flushInflightSearchNow = function () { fireWithStats(null); };
1414
+ __cancelInflightStatsWait = waitForSearchStats(readSearchStatistics, 3000, fireWithStats);
1415
+ }
1416
+
1417
+ /**
1418
+ * EVENT 2 (asset preview): fires when the current URL is an ASC details
1419
+ * page — i.e. a thumbnail click in the results grid navigated here.
1420
+ *
1421
+ * The asset path (`/content/dam/…`) is the suffix of `location.pathname`
1422
+ * after `/details/<type>.html`; the asset type is the segment in front
1423
+ * of `.html` (image, video, document, 3d, audio, …).
1424
+ */
1425
+ function trackAssetPreview() {
1426
+ var info = detectDetailsAssetPath();
1427
+ if (!info) return;
1428
+ var assetName = (info.assetPath.split('/').pop() || '');
1429
+ var dotIdx = assetName.lastIndexOf('.');
1430
+ var assetExt = dotIdx > 0 ? assetName.slice(dotIdx + 1).toLowerCase() : '';
1431
+ track('asset_preview', {
1432
+ asset_path: info.assetPath,
1433
+ asset_type: info.assetType,
1434
+ asset_name: assetName,
1435
+ asset_extension: assetExt,
1436
+ page_url: location.href,
1437
+ page_referrer: document.referrer || ''
1438
+ }, {}, 'asset_detail');
1439
+ }
1440
+
1441
+ /**
1442
+ * Wraps `history.pushState` / `history.replaceState` (and listens for
1443
+ * `popstate`) so we re-evaluate the URL on every SPA navigation and
1444
+ * re-fire `search_executed` / `asset_preview` if appropriate.
1445
+ *
1446
+ * Why this matters: Asset Share Commons rewires its in-page filter /
1447
+ * sort / layout / pagination controls to call `history.pushState`
1448
+ * rather than doing a full page reload. Without this hook the SDK's
1449
+ * own pushState wrapper still fires a `page_view` with
1450
+ * `event_subtype = "spa_navigation"`, but our search_executed event
1451
+ * (with `search_term`, `semantic_search`, `fuzzy_search`,
1452
+ * `filters_json`, etc. on the `custom_dimensions` map) would never
1453
+ * fire on those in-page transitions.
1454
+ *
1455
+ * Dedup: we keep the previous URL in a closure variable and skip
1456
+ * re-firing when the URL hasn't actually changed (e.g. some libraries
1457
+ * call replaceState with the current state on hash-only updates).
1458
+ */
1459
+ function installSpaNavHooks() {
1460
+ if (window.__ilVisaSpaHooked) return;
1461
+ window.__ilVisaSpaHooked = true;
1462
+
1463
+ var lastUrl = location.href;
1464
+
1465
+ function reevaluate() {
1466
+ try {
1467
+ var nowUrl = location.href;
1468
+ if (nowUrl === lastUrl) return;
1469
+ lastUrl = nowUrl;
1470
+ var q = parseQuery();
1471
+ trackSearchExecuted(q);
1472
+ trackAssetPreview();
1473
+ } catch (e) { /* swallow — never break the host page */ }
1474
+ }
1475
+
1476
+ // Defer slightly so the URL change has actually settled in the address
1477
+ // bar by the time we read `location.href` (some routers call pushState
1478
+ // synchronously inside an event handler that hasn't yet committed).
1479
+ function scheduleReevaluate() {
1480
+ try { (window.requestAnimationFrame || setTimeout)(reevaluate, 0); }
1481
+ catch (e) { setTimeout(reevaluate, 0); }
1482
+ }
1483
+
1484
+ window.addEventListener('popstate', scheduleReevaluate);
1485
+ window.addEventListener('hashchange', scheduleReevaluate);
1486
+
1487
+ if (window.history && typeof history.pushState === 'function') {
1488
+ var origPush = history.pushState;
1489
+ history.pushState = function () {
1490
+ var ret = origPush.apply(this, arguments);
1491
+ scheduleReevaluate();
1492
+ return ret;
1493
+ };
1494
+ }
1495
+ if (window.history && typeof history.replaceState === 'function') {
1496
+ var origReplace = history.replaceState;
1497
+ history.replaceState = function () {
1498
+ var ret = origReplace.apply(this, arguments);
1499
+ scheduleReevaluate();
1500
+ return ret;
1501
+ };
1502
+ }
1503
+ }
1504
+
1505
+ // ─── 8b. Asset Explorer (React) ──────────────────────────
1506
+
1507
+ /**
1508
+ * Returns true when the current URL is the React-based Asset Explorer
1509
+ * (e.g. /asset-explorer.html#/content/dam/ps). We accept the URL signal
1510
+ * first because it doesn't require the DOM to have settled, and fall
1511
+ * back to a DOM probe for themed deployments that mount the explorer
1512
+ * under a different path.
1513
+ */
1514
+ function isAssetExplorerPage() {
1515
+ var p = location.pathname;
1516
+ // Asset-preview / details URLs are a *child* of the explorer page
1517
+ // (`.../asset-explorer/details/<type>.html/<asset-path>`) and we want
1518
+ // those to fall into the ASC-style branch so trackAssetPreview() fires.
1519
+ // The details-detector above is the authoritative match for that.
1520
+ if (detectDetailsAssetPath()) return false;
1521
+ // URL path heuristic: matches both `/asset-explorer.html` (vanity URL)
1522
+ // and `/content/.../asset-explorer.html` (resolved page path).
1523
+ if (/\/asset[-_]?explorer(\.html|\/|$)/i.test(p)) return true;
1524
+ if (document.querySelector('[class*="_directoryExplorer_"], .directory-explorer')) return true;
1525
+ return false;
1526
+ }
1527
+
1528
+ function findAssetExplorerRoot() {
1529
+ return $(SELECTORS.assetExplorerRoot);
1530
+ }
1531
+
1532
+ /**
1533
+ * Locates the visible search input. Falls back to placeholder-text match
1534
+ * if the [class*="_input_"] selectors haven't been baked into a themed
1535
+ * deployment yet.
1536
+ */
1537
+ function findAssetExplorerSearchInput() {
1538
+ var byClass = $(SELECTORS.assetExplorerSearchInput);
1539
+ if (byClass) return byClass;
1540
+ var inputs = document.querySelectorAll('input[type="text"], input:not([type])');
1541
+ for (var i = 0; i < inputs.length; i++) {
1542
+ var p = inputs[i].getAttribute('placeholder') || '';
1543
+ if (TEXT_PATTERNS.aeSearchPlaceholder.test(p)) return inputs[i];
1544
+ }
1545
+ return null;
1546
+ }
1547
+
1548
+ /**
1549
+ * Returns the current `#/content/dam/...` folder path the explorer is
1550
+ * showing. Strips the leading `#` and any embedded query suffix so the
1551
+ * value is directly comparable to AEM JCR paths.
1552
+ */
1553
+ function readAssetExplorerFolderPath() {
1554
+ var h = String(location.hash || '');
1555
+ h = h.replace(/^#/, '');
1556
+ var qIdx = h.indexOf('?');
1557
+ if (qIdx >= 0) h = h.slice(0, qIdx);
1558
+ return h;
1559
+ }
1560
+
1561
+ /**
1562
+ * Reads the on/off state of a labelled toggle inside the Search Options
1563
+ * modal. Toggle markup varies across React component libraries so we
1564
+ * walk several known patterns before giving up:
1565
+ *
1566
+ * 1. native checkbox / radio (`checked`)
1567
+ * 2. `aria-checked` / `aria-pressed` / `aria-selected`
1568
+ * 3. class names containing "checked", "active", "enabled", "on"
1569
+ * 4. `data-state="on"` (Radix UI) / `data-selected="true"`
1570
+ *
1571
+ * Returns `'true'` / `'false'` strings so the value drops directly into
1572
+ * the ClickHouse `custom_dimensions` map without further serialization,
1573
+ * and `''` when the labelled row isn't present (modal not open). The
1574
+ * caller treats `''` as "unknown" and won't emit a misleading default.
1575
+ */
1576
+ function readAssetExplorerToggleState(labelRe) {
1577
+ var rows = document.querySelectorAll(SELECTORS.assetExplorerSearchOptionRow);
1578
+ for (var i = 0; i < rows.length; i++) {
1579
+ var row = rows[i];
1580
+ var text = cleanText(row.textContent || '');
1581
+ if (!labelRe.test(text)) continue;
1582
+
1583
+ // 1. native form control
1584
+ var checkbox = row.querySelector('input[type="checkbox"], input[type="radio"]');
1585
+ if (checkbox && checkbox.checked !== undefined) {
1586
+ return String(!!checkbox.checked);
1587
+ }
1588
+
1589
+ // 2. ARIA
1590
+ var ariaChecked = row.querySelector('[aria-checked], [aria-pressed], [aria-selected]');
1591
+ if (ariaChecked) {
1592
+ var v = ariaChecked.getAttribute('aria-checked')
1593
+ || ariaChecked.getAttribute('aria-pressed')
1594
+ || ariaChecked.getAttribute('aria-selected');
1595
+ if (v === 'true' || v === 'false') return v;
1596
+ }
1597
+
1598
+ // 3. data-state / data-selected
1599
+ var dataStated = row.querySelector('[data-state], [data-selected]');
1600
+ if (dataStated) {
1601
+ var ds = (dataStated.getAttribute('data-state') || '').toLowerCase();
1602
+ if (ds === 'on' || ds === 'checked' || ds === 'true') return 'true';
1603
+ if (ds === 'off' || ds === 'unchecked' || ds === 'false') return 'false';
1604
+ var sel = (dataStated.getAttribute('data-selected') || '').toLowerCase();
1605
+ if (sel === 'true') return 'true';
1606
+ if (sel === 'false') return 'false';
1607
+ }
1608
+
1609
+ // 4. class-name heuristic on the row OR its toggle child
1610
+ var classRoot = row.querySelector('[class*="toggle"], [class*="switch"], [role="switch"]') || row;
1611
+ var cls = (classRoot.className && classRoot.className.baseVal !== undefined)
1612
+ ? classRoot.className.baseVal // SVG element
1613
+ : String(classRoot.className || '');
1614
+ if (/(^|[\s_-])(active|checked|enabled|on|selected)([\s_-]|$)/i.test(cls)) return 'true';
1615
+ if (/(^|[\s_-])(inactive|unchecked|disabled|off)([\s_-]|$)/i.test(cls)) return 'false';
1616
+
1617
+ // Row matched but we couldn't determine state — return empty so the
1618
+ // caller emits "" rather than a misleading default.
1619
+ return '';
1620
+ }
1621
+ return '';
1622
+ }
1623
+
1624
+ /**
1625
+ * Reads the Asset Explorer search-statistics tiles.
1626
+ *
1627
+ * The live visa-sit.productioncloud.io build renders three tiles inside a
1628
+ * `<div class="_statContainer_1qyta_1">` (camelCase suffix → not
1629
+ * matched by `[class*="_stat_"]`!) where each tile is a sibling
1630
+ * `<div>` containing a `<div class="_value_1qyta_9">N</div>` and a
1631
+ * sibling `<div class="_label_*">LABEL</div>`. We try in order:
1632
+ *
1633
+ * 1. find the stats container (or fall back to the filter rail),
1634
+ * 2. for every `[class*="_value_"]` descendant, pair it with a
1635
+ * `[class*="_label_"]` peer found by climbing the closest tile
1636
+ * wrapper (`<div>` parent) — covers both
1637
+ * "value-then-label" and "label-then-value" tile layouts,
1638
+ * 3. as a last resort, regex-parse the container's textContent for
1639
+ * `<number><whitespace?><LABEL>` so a stripped-down themed build
1640
+ * with no _value_/_label_ class hints still resolves.
1641
+ *
1642
+ * Returns the same `{ container, stats: { time_ms, total, pages,
1643
+ * displayed, raw } }` shape as readSearchStatistics() so the shared
1644
+ * waitForSearchStats() works unchanged.
1645
+ */
1646
+ function readAssetExplorerSearchStatistics() {
1647
+ var container = $(SELECTORS.assetExplorerSearchStatistics);
1648
+ if (!container) return { container: null, stats: null };
1649
+
1650
+ var rows = [];
1651
+ var seen = {};
1652
+
1653
+ function pushRow(label, valueText, value) {
1654
+ var key = (label || '').toLowerCase() + ':' + valueText;
1655
+ if (seen[key]) return;
1656
+ seen[key] = true;
1657
+ rows.push({ idx: rows.length, label: label, valueText: valueText, value: value });
1658
+ }
1659
+
1660
+ // ── Strategy 1: _value_ / _label_ pairing ───────────────
1661
+ // Walk every `[class*="_value_"]` in the container, then look for a
1662
+ // sibling/uncle/parent text that's the label. This handles the
1663
+ // `_statContainer_ > div[i] > {_value_, _label_}` shape and the
1664
+ // common variant where value and label are wrapped together in
1665
+ // a `<div>` tile.
1666
+ var valueEls = container.querySelectorAll('[class*="_value_"]');
1667
+ for (var i = 0; i < valueEls.length; i++) {
1668
+ var vEl = valueEls[i];
1669
+ var valueText = cleanText(vEl.textContent);
1670
+ var n = parseStatNumber(valueText);
1671
+ if (n === null) continue;
1672
+
1673
+ // Skip $value$ blocks that aren't direct text values (e.g., a
1674
+ // nested wrapper). Only first-level numeric content qualifies.
1675
+ if (!/^[-+]?\d/.test(valueText)) continue;
1676
+
1677
+ var labelText = '';
1678
+
1679
+ // a) Sibling [class*="_label_"]
1680
+ if (vEl.parentElement) {
1681
+ var sibLabel = vEl.parentElement.querySelector('[class*="_label_"]');
1682
+ if (sibLabel && sibLabel !== vEl) labelText = cleanText(sibLabel.textContent);
1683
+ }
1684
+
1685
+ // b) Walk up one level — tile may wrap value+label in a div whose
1686
+ // parent has a separate [class*="_label_"] child.
1687
+ if (!labelText && vEl.parentElement && vEl.parentElement.parentElement) {
1688
+ var unc = vEl.parentElement.parentElement.querySelector('[class*="_label_"]');
1689
+ if (unc && unc !== vEl) labelText = cleanText(unc.textContent);
1690
+ }
1691
+
1692
+ // c) Adjacent textContent — parent's text minus the value
1693
+ if (!labelText && vEl.parentElement) {
1694
+ var parentText = cleanText(vEl.parentElement.textContent);
1695
+ if (parentText && parentText.indexOf(valueText) >= 0) {
1696
+ var residual = parentText.replace(valueText, '').trim();
1697
+ // Only keep if residual is short (a label) not a paragraph.
1698
+ if (residual && residual.length <= 80) labelText = residual;
1699
+ }
1700
+ }
1701
+
1702
+ pushRow(labelText, valueText, n);
1703
+ }
1704
+
1705
+ // ── Strategy 2: regex over container text ───────────────
1706
+ // Pattern: `<number><whitespace?><LABEL>` repeated (e.g.
1707
+ // "4 DISPLAYED 4 TOTAL 11 MILLISECONDS" or "4DISPLAYED…").
1708
+ if (!rows.length) {
1709
+ var fullText = cleanText(container.textContent || '');
1710
+ var re = /(\d+(?:[.,]\d+)?)\s*(displayed|showing|shown|visible|total|results?|assets?|hits?|matches?|found|count|milliseconds?|seconds?|elapsed|duration|time|pages?)\b/gi;
1711
+ var m;
1712
+ while ((m = re.exec(fullText)) !== null) {
1713
+ var rv = parseStatNumber(m[1]);
1714
+ if (rv === null) continue;
1715
+ pushRow(m[2], m[1], rv);
1716
+ }
1717
+ }
1718
+
1719
+ if (!rows.length || !rows.some(function (r) { return r.value !== null; })) {
1720
+ return { container: container, stats: null };
1721
+ }
1722
+
1723
+ var stats = {
1724
+ time_ms: null,
1725
+ total: null,
1726
+ pages: null,
1727
+ displayed: null,
1728
+ raw: rows.map(function (r) { return { idx: r.idx, label: r.label, value: r.valueText }; })
1729
+ };
1730
+
1731
+ // Label-driven classification. We deliberately DO NOT carry the
1732
+ // positional fallback over from the ASC reader — React layouts
1733
+ // have no stable left-to-right ordering convention and a silent
1734
+ // no-op is safer than a confident mis-attribution.
1735
+ for (var k = 0; k < rows.length; k++) {
1736
+ var r = rows[k];
1737
+ if (r.value === null) continue;
1738
+ var c = classifyStatLabel(r.label);
1739
+ if (!c) continue;
1740
+ if (c.key === 'time_ms' && stats.time_ms === null) {
1741
+ stats.time_ms = c.unit === 's' ? r.value * 1000 : r.value;
1742
+ } else if (c.key === 'total' && stats.total === null) {
1743
+ stats.total = r.value;
1744
+ } else if (c.key === 'pages' && stats.pages === null) {
1745
+ stats.pages = r.value;
1746
+ } else if (c.key === 'displayed' && stats.displayed === null) {
1747
+ stats.displayed = r.value;
1748
+ }
1749
+ }
1750
+
1751
+ return { container: container, stats: stats };
1752
+ }
1753
+
1754
+ /**
1755
+ * Reads the currently-selected filters from the right-rail facet panel.
1756
+ * Returns an array of `{ name, values[] }` blocks keyed by section
1757
+ * heading text — same shape `filters_dom_json` carries on the ASC
1758
+ * search_executed event so dashboards can pivot on either context
1759
+ * uniformly. An empty array (no selections) is the normal default;
1760
+ * the caller emits `filters_dom_json=""` in that case.
1761
+ *
1762
+ * Detection strategies, applied in order until something is found:
1763
+ * 1. Native form controls (`input[type="checkbox"]:checked`,
1764
+ * `input[type="radio"]:checked`).
1765
+ * 2. ARIA: `[aria-checked="true"]`, `[aria-selected="true"]`,
1766
+ * `[aria-pressed="true"]`.
1767
+ * 3. data-state: `[data-state="checked" | "on" | "selected"]`,
1768
+ * `[data-selected="true"]`.
1769
+ * 4. Class-name heuristic — any element under the rail with a class
1770
+ * containing "_selected", "_checked", "_active", or "_on" that
1771
+ * ISN'T paired with an "un-" prefix on the same chip.
1772
+ *
1773
+ * Each match is grouped under its enclosing section heading; the
1774
+ * heading is resolved by walking up to the closest filter-section
1775
+ * container and reading its first heading-class child.
1776
+ */
1777
+ function readAssetExplorerFilters() {
1778
+ var rail = $(SELECTORS.assetExplorerFilterRail);
1779
+ if (!rail) return [];
1780
+
1781
+ // Live visa-sit.productioncloud.io filter rail captures show section
1782
+ // headings landing on classes the original `_filterSection_`-anchored
1783
+ // logic never saw. Climb up to 8 ancestor levels and, at each step,
1784
+ // look for either a previous-sibling or first-child element whose
1785
+ // class matches the heading patterns OR whose textContent is a
1786
+ // short ALL-CAPS label. The ALL-CAPS fallback handles builds
1787
+ // where the heading element has no recognisable class (just a plain
1788
+ // <div>FACET NAME</div>).
1789
+ //
1790
+ // We deliberately keep `[class*="_label_"]` / `[class*="_name_"]` /
1791
+ // `[class*="_header_"]` OUT of the heading selector — in this React
1792
+ // build the CHIP itself wraps its visible text in `_label_<hash>`,
1793
+ // and the chip's label appears in DOM order BEFORE its input, so
1794
+ // matching `_label_` would walk straight into the chip's own text
1795
+ // and return it as the section heading (v1.1.3 bug: "2026" / "Image"
1796
+ // ended up as section names). The ALL-CAPS visibility test below
1797
+ // is the more reliable signal for actual section names.
1798
+ var HEADING_SELECTOR =
1799
+ '[class*="_heading_"], [class*="_title_"], [class*="_sectionTitle_"], ' +
1800
+ '[class*="_categoryName_"], [class*="_facetTitle_"], [class*="_groupName_"], ' +
1801
+ '[class*="_groupTitle_"], [class*="_sectionHeader_"], [class*="_facetHeader_"], ' +
1802
+ '[class*="_categoryHeader_"], [class*="_filterHeader_"], [class*="_filterTitle_"], ' +
1803
+ 'h1, h2, h3, h4, h5, h6, legend, summary';
1804
+
1805
+ function looksLikeFacetHeading(txt) {
1806
+ if (!txt) return false;
1807
+ if (txt.length < 3 || txt.length > 80) return false;
1808
+ // Reject stat tiles ("4 DISPLAYED") and pure numbers ("2026").
1809
+ if (/^\d/.test(txt)) return false;
1810
+ // Must contain at least one A-Z letter and NO lowercase letters
1811
+ // — observed facets on this build are 100% uppercase with optional
1812
+ // punctuation: ASSET TYPE, MARKETING FUNCTION / INDUSTRY,
1813
+ // APPLICATION & USE, ORIGIN, ASSET USAGE RIGHTS,
1814
+ // LANGUAGE / REGION, YEAR.
1815
+ if (!/[A-Z]/.test(txt)) return false;
1816
+ if (/[a-z]/.test(txt)) return false;
1817
+ // Allowed character set — uppercase letters, digits (rare),
1818
+ // whitespace, and a handful of punctuation marks seen in facet
1819
+ // names. Anything else is probably a chip with weird casing.
1820
+ if (!/^[A-Z0-9 &/().,\-]+$/.test(txt)) return false;
1821
+ // Reject pure punctuation / pure whitespace.
1822
+ if (!/[A-Z]{2,}/.test(txt) && txt.length < 4) return false;
1823
+ return true;
1824
+ }
1825
+
1826
+ function sectionHeadingFor(el) {
1827
+ var ancestor = el;
1828
+ for (var depth = 0; depth < 8 && ancestor && ancestor !== rail; depth++) {
1829
+ // a) Heading-class previous sibling at this depth
1830
+ var prev = ancestor.previousElementSibling;
1831
+ while (prev) {
1832
+ if (prev.matches && prev.matches(HEADING_SELECTOR)) {
1833
+ var t1 = cleanText(prev.textContent || '');
1834
+ if (t1) return t1.slice(0, 80);
1835
+ }
1836
+ // ALL-CAPS plain element with short text counts too
1837
+ var pt = cleanText(prev.textContent || '');
1838
+ if (looksLikeFacetHeading(pt)) return pt.slice(0, 80);
1839
+ prev = prev.previousElementSibling;
1840
+ }
1841
+ // b) Heading-class first child of THIS ancestor (before the chip)
1842
+ var children = ancestor.children;
1843
+ for (var i = 0; i < children.length; i++) {
1844
+ var c = children[i];
1845
+ if (c === el) break;
1846
+ if (c.contains && c.contains(el)) continue; // skip the chip's branch
1847
+ if (c.matches && c.matches(HEADING_SELECTOR)) {
1848
+ var t2 = cleanText(c.textContent || '');
1849
+ if (t2) return t2.slice(0, 80);
1850
+ }
1851
+ // ALL-CAPS plain element
1852
+ var ct = cleanText(c.textContent || '');
1853
+ if (looksLikeFacetHeading(ct)) return ct.slice(0, 80);
1854
+ }
1855
+ ancestor = ancestor.parentElement;
1856
+ }
1857
+ return '';
1858
+ }
1859
+
1860
+ function chipLabel(el) {
1861
+ var inp;
1862
+ if (el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'OPTION') {
1863
+ inp = el;
1864
+ }
1865
+ // Prefer an associated <label>, then aria-label, then visible text.
1866
+ if (inp && inp.id) {
1867
+ var lab = document.querySelector('label[for="' + CSS.escape(inp.id) + '"]');
1868
+ if (lab) return cleanText(lab.textContent || '');
1869
+ }
1870
+ var aria = el.getAttribute && el.getAttribute('aria-label');
1871
+ if (aria) return aria;
1872
+ // Climb to the nearest row/chip wrapper for the visible text — the
1873
+ // raw element itself might be an inner input/svg with no text.
1874
+ var wrapper = el.closest('label, li, [role="option"], [role="treeitem"], [role="menuitem"], [class*="_option_"], [class*="_chip_"], [class*="_item_"], [class*="_row_"]') || el;
1875
+ return cleanText(wrapper.textContent || '').slice(0, 120);
1876
+ }
1877
+
1878
+ var bySection = {};
1879
+ function record(el) {
1880
+ var section = sectionHeadingFor(el) || 'unknown';
1881
+ var label = chipLabel(el);
1882
+ if (!label) return;
1883
+ if (!bySection[section]) bySection[section] = [];
1884
+ // Dedup within the same section (a checkbox + its <label> wrapper
1885
+ // can both match the class-name heuristic).
1886
+ if (bySection[section].indexOf(label) < 0) bySection[section].push(label);
1887
+ }
1888
+
1889
+ // 1. native form controls
1890
+ var natives = rail.querySelectorAll('input[type="checkbox"]:checked, input[type="radio"]:checked');
1891
+ for (var n = 0; n < natives.length; n++) record(natives[n]);
1892
+
1893
+ // 2. ARIA / data-state
1894
+ var ariaSel = rail.querySelectorAll(
1895
+ '[aria-checked="true"], [aria-selected="true"], [aria-pressed="true"], ' +
1896
+ '[data-state="checked"], [data-state="on"], [data-state="selected"], ' +
1897
+ '[data-selected="true"]'
1898
+ );
1899
+ for (var a = 0; a < ariaSel.length; a++) record(ariaSel[a]);
1900
+
1901
+ // 3. class-name heuristic — narrow to elements whose className is
1902
+ // SHORT (likely a chip) and contains a positive state marker.
1903
+ var clsCandidates = rail.querySelectorAll(
1904
+ '[class*="_selected_"], [class*="_checked_"], [class*="_active_"], [class*="_on_"], [class*="_isSelected"]'
1905
+ );
1906
+ for (var c = 0; c < clsCandidates.length; c++) {
1907
+ var el = clsCandidates[c];
1908
+ var cls = (el.className && el.className.baseVal !== undefined) ? el.className.baseVal : String(el.className || '');
1909
+ if (cls.length > 240) continue; // skip container-level matches
1910
+ if (/_unselected|_unchecked|_inactive|_off/i.test(cls)) continue;
1911
+ // Skip elements that are descendants of an already-matched native
1912
+ // input — record() already handled them.
1913
+ if (el.querySelector('input[type="checkbox"]:checked, input[type="radio"]:checked')) continue;
1914
+ record(el);
1915
+ }
1916
+
1917
+ var out = [];
1918
+ for (var s in bySection) {
1919
+ if (bySection.hasOwnProperty(s)) {
1920
+ out.push({ name: s, values: bySection[s] });
1921
+ }
1922
+ }
1923
+ return out;
1924
+ }
1925
+
1926
+ // Cross-call state for trackAssetExplorerSearch (mirrors the ASC pair).
1927
+ var __aeCancelInflightStatsWait = null;
1928
+ var __aeFlushInflightSearchNow = null;
1929
+ // Dedup: avoid re-firing the same {term, semantic, fuzzy, folder} combo
1930
+ // when several triggers (Enter + form submit + click) overlap on a
1931
+ // single user action. Compared by string equality with the LAST fired
1932
+ // signature; cleared on hashchange.
1933
+ var __aeLastFiredSig = '';
1934
+
1935
+ /**
1936
+ * Emits `search_executed` (subtype `asset_search`) for the React Asset
1937
+ * Explorer page. Captures search term + semantic/fuzzy toggles + the
1938
+ * current folder + the stats widget once it settles. The `trigger`
1939
+ * argument records HOW the search was initiated (enter, submit, click,
1940
+ * options_close, filter_click, input_debounced) so we can prune the
1941
+ * hooks later once we see which paths actually fire in production.
1942
+ */
1943
+ function trackAssetExplorerSearch(searchTerm, opts) {
1944
+ opts = opts || {};
1945
+ searchTerm = safeStr(searchTerm).trim();
1946
+ if (!searchTerm) return;
1947
+
1948
+ var semantic = (typeof opts.semantic === 'string')
1949
+ ? opts.semantic
1950
+ : readAssetExplorerToggleState(TEXT_PATTERNS.semantic);
1951
+ var fuzzy = (typeof opts.fuzzy === 'string')
1952
+ ? opts.fuzzy
1953
+ : readAssetExplorerToggleState(TEXT_PATTERNS.fuzzy);
1954
+ var folder = readAssetExplorerFolderPath();
1955
+ var trigger = safeStr(opts.trigger);
1956
+ var filters = readAssetExplorerFilters();
1957
+ var filtersJson = filters.length ? JSON.stringify(filters) : '';
1958
+
1959
+ // Dedup signature includes the filter selection — flipping a single
1960
+ // facet on/off should re-fire even if the search term is unchanged,
1961
+ // since the result set itself changes.
1962
+ var sig = [searchTerm, semantic, fuzzy, folder, filtersJson].join('|');
1963
+ if (sig === __aeLastFiredSig && !opts.forceDedupBypass) return;
1964
+ __aeLastFiredSig = sig;
1965
+
1966
+ if (__aeFlushInflightSearchNow) {
1967
+ try { __aeFlushInflightSearchNow(); } catch (e) {}
1968
+ __aeFlushInflightSearchNow = null;
1969
+ }
1970
+ if (__aeCancelInflightStatsWait) {
1971
+ try { __aeCancelInflightStatsWait(); } catch (e) {}
1972
+ __aeCancelInflightStatsWait = null;
1973
+ }
1974
+
1975
+ var dims = {
1976
+ search_term: searchTerm,
1977
+ semantic_search: semantic,
1978
+ fuzzy_search: fuzzy,
1979
+ search_context: 'asset_explorer',
1980
+ search_trigger: trigger,
1981
+ folder_path: folder,
1982
+ filters_dom_json: filtersJson,
1983
+ page_url: location.href,
1984
+ page_referrer: document.referrer || ''
1985
+ };
1986
+ var metrics = {
1987
+ filter_dom_count: filters.reduce(function (acc, g) { return acc + (g.values ? g.values.length : 0); }, 0)
1988
+ };
1989
+
1990
+ var fired = false;
1991
+ function fireWithStats(stats) {
1992
+ if (fired) return;
1993
+ fired = true;
1994
+ __aeCancelInflightStatsWait = null;
1995
+ __aeFlushInflightSearchNow = null;
1996
+
1997
+ if (stats) {
1998
+ if (stats.time_ms !== null) metrics.search_time_ms = stats.time_ms;
1999
+ if (stats.total !== null) metrics.result_total = stats.total;
2000
+ if (stats.pages !== null) metrics.result_pages = stats.pages;
2001
+ if (stats.displayed !== null) metrics.result_displayed = stats.displayed;
2002
+ dims.search_stats_ready = 'true';
2003
+ try {
2004
+ if (stats.raw && stats.raw.length) {
2005
+ var rawJson = JSON.stringify(stats.raw);
2006
+ dims.search_stats_raw_json = rawJson.length > 240 ? rawJson.slice(0, 240) : rawJson;
2007
+ }
2008
+ } catch (e) { /* swallow */ }
2009
+ } else {
2010
+ dims.search_stats_ready = 'false';
2011
+ }
2012
+
2013
+ track('search_executed', dims, metrics, 'asset_search');
2014
+ __searchFireCount++;
2015
+ }
2016
+
2017
+ __aeFlushInflightSearchNow = function () { fireWithStats(null); };
2018
+ __aeCancelInflightStatsWait = waitForSearchStats(readAssetExplorerSearchStatistics, 3000, fireWithStats);
2019
+ }
2020
+
2021
+ /**
2022
+ * Emits a `folder_navigation` event with subtype `asset_browse`. The
2023
+ * `tree_action` dim distinguishes how the navigation was triggered so
2024
+ * a single event type can describe every kind of folder interaction:
2025
+ *
2026
+ * - "hash_change" — the URL hash route changed (true navigation)
2027
+ * - "click" — user clicked a folder label in the side tree
2028
+ * - "expand" — user expanded a tree node
2029
+ * - "collapse" — user collapsed a tree node
2030
+ *
2031
+ * The tree-action variants also carry `tree_target_label` (the visible
2032
+ * text of the clicked node) and `tree_target_class_hint` (the first
2033
+ * 240 chars of the target's className) so we can refine the action
2034
+ * detection later without re-instrumenting the page.
2035
+ */
2036
+ function trackAssetExplorerFolderNavigation(opts) {
2037
+ opts = opts || {};
2038
+ var folder = readAssetExplorerFolderPath();
2039
+ var action = safeStr(opts.tree_action) || 'hash_change';
2040
+ // Skip the initial page_load / hash_change variants when the React
2041
+ // app hasn't set its default route yet — the next real hashchange
2042
+ // will fire a clean event. We still fire on click/expand/collapse
2043
+ // even with an empty folder so a no-op gesture is observable.
2044
+ if (!folder && (action === 'hash_change' || action === 'page_load')) return;
2045
+ var dims = {
2046
+ folder_path: folder,
2047
+ search_context: 'asset_explorer',
2048
+ tree_action: action,
2049
+ page_url: location.href,
2050
+ page_referrer: document.referrer || ''
2051
+ };
2052
+ if (opts.tree_target_label) {
2053
+ dims.tree_target_label = safeStr(opts.tree_target_label).slice(0, 120);
2054
+ }
2055
+ if (opts.tree_target_class_hint) {
2056
+ dims.tree_target_class_hint = safeStr(opts.tree_target_class_hint).slice(0, 240);
2057
+ }
2058
+ track('folder_navigation', dims, {}, 'asset_browse');
2059
+ }
2060
+
2061
+ // ─── 9. DOM-driven hooks (clicks) ────────────────────────
2062
+
2063
+ // ── Login page hooks (preserved from earlier login-only bootstrap) ──
2064
+
2065
+ function hookSignInSubmit() {
2066
+ var form = $(SELECTORS.loginForm);
2067
+ var btn = $(SELECTORS.signInButton);
2068
+ if (!btn) {
2069
+ btn = closestMatchByText(document, 'button, a, [role="button"], input[type="submit"]', TEXT_PATTERNS.signIn);
2070
+ }
2071
+ function fire(reason) {
2072
+ var userInput = $(SELECTORS.userField);
2073
+ var typedUser = (userInput && (userInput.value || '').trim()) || '';
2074
+ if (typedUser) identify(typedUser);
2075
+ track('login_attempt', {
2076
+ method: 'credentials',
2077
+ attempt_user: typedUser,
2078
+ submit_reason: reason || 'click',
2079
+ page_url: location.href
2080
+ });
2081
+ flush();
2082
+ }
2083
+ if (btn) btn.addEventListener('click', function () { fire('click'); }, { capture: true });
2084
+ if (form) form.addEventListener('submit', function () { fire('submit'); }, { capture: true });
2085
+ }
2086
+
2087
+ function hookSsoClick() {
2088
+ var btn = $(SELECTORS.ssoButton);
2089
+ if (!btn) {
2090
+ btn = closestMatchByText(document, 'button, a, [role="button"]', TEXT_PATTERNS.lionSso);
2091
+ }
2092
+ if (!btn) return;
2093
+ btn.addEventListener('click', function () {
2094
+ track('sso_click', {
2095
+ method: 'lion_login',
2096
+ sso_provider: 'lion',
2097
+ button_text: visibleText(btn).substring(0, 120),
2098
+ page_url: location.href
2099
+ });
2100
+ flush();
2101
+ }, { capture: true });
2102
+ }
2103
+
2104
+ function hookTermsClick() {
2105
+ var link = $(SELECTORS.termsLink);
2106
+ if (!link) {
2107
+ link = closestMatchByText(document, 'a, button, [role="link"]', TEXT_PATTERNS.terms);
2108
+ }
2109
+ if (!link) return;
2110
+ link.addEventListener('click', function () {
2111
+ track('terms_click', {
2112
+ link_url: (link.getAttribute && link.getAttribute('href')) || '',
2113
+ link_text: visibleText(link).substring(0, 120),
2114
+ page_url: location.href
2115
+ });
2116
+ flush();
2117
+ }, { capture: true });
2118
+ }
2119
+
2120
+ // ── ASC click delegation (one body-level listener, survives SPA mutations) ──
2121
+
2122
+ /**
2123
+ * Body-level click listener that matches Add-to-Cart and Share buttons
2124
+ * across both the search-results grid (tile + table) and the asset detail
2125
+ * page. Uses `closest()` so it works whether the user clicks the icon,
2126
+ * the label, or any descendant of the button.
2127
+ */
2128
+ function installAscClickDelegation() {
2129
+ if (window.__ilVisaClickDelegated) return;
2130
+ window.__ilVisaClickDelegated = true;
2131
+
2132
+ function tryClosest(target, selector) {
2133
+ try { return target.closest(selector); } catch (e) { return null; }
2134
+ }
2135
+
2136
+ document.addEventListener('click', function (e) {
2137
+ var target = e.target;
2138
+ if (!target || target.nodeType !== 1 || !target.closest) return;
2139
+
2140
+ // The dispatch ordering matters — match the MOST SPECIFIC
2141
+ // data-asset-share-id first so cart-level controls don't fall
2142
+ // through to asset-level handlers. Each branch returns to
2143
+ // prevent a single user click from emitting multiple events.
2144
+
2145
+ // ── 1. Cart-level "Download Cart" (data-asset-share-id="download-all") ──
2146
+ // The user-confirmed intent to start downloading the entire
2147
+ // cart. A second confirmation modal appears AFTER this click;
2148
+ // the actual binaries are produced asynchronously and surface
2149
+ // in the downloads modal as individual downloadbinaries.json
2150
+ // anchors (covered by branch 3 below).
2151
+ var dlAllBtn = tryClosest(target, SELECTORS.cartDownloadButton);
2152
+ if (dlAllBtn) {
2153
+ var dlContents = readCartContents();
2154
+ var dlContentsJson = dlContents.length ? JSON.stringify(dlContents) : '';
2155
+ if (dlContentsJson.length > 480) dlContentsJson = dlContentsJson.slice(0, 480);
2156
+ track('cart_download', {
2157
+ cart_asset_paths_json: dlContentsJson,
2158
+ page_url: location.href,
2159
+ page_referrer: document.referrer || ''
2160
+ }, {
2161
+ cart_item_count: dlContents.length
2162
+ }, 'cart_action');
2163
+ return;
2164
+ }
2165
+
2166
+ // ── 2. Cart-level "Share Cart" (data-asset-share-id="share-all") ──
2167
+ // Clicking this OPENS a second modal where the user enters
2168
+ // recipient emails + public flag + optional date range. The
2169
+ // real share doesn't happen until that form is submitted,
2170
+ // which we capture in `installShareFormHook()`. To survive the
2171
+ // cart-modal closing before the share form is filled in, we
2172
+ // stash the cart snapshot module-globally so the submit
2173
+ // handler can attach it to the cart_share event.
2174
+ var shareAllBtn = tryClosest(target, SELECTORS.cartShareButton);
2175
+ if (shareAllBtn) {
2176
+ var shContents = readCartContents();
2177
+ var shContentsJson = shContents.length ? JSON.stringify(shContents) : '';
2178
+ if (shContentsJson.length > 480) shContentsJson = shContentsJson.slice(0, 480);
2179
+ // Stash for the submit handler.
2180
+ window.__ilVisaPendingCartShare = {
2181
+ paths: shContents,
2182
+ paths_json: shContentsJson,
2183
+ captured_at: Date.now()
2184
+ };
2185
+ // "Intent to share" event — useful for the funnel
2186
+ // (clicked → completed) and fires regardless of whether
2187
+ // the user actually submits the form.
2188
+ track('cart_share_initiated', {
2189
+ cart_asset_paths_json: shContentsJson,
2190
+ page_url: location.href,
2191
+ page_referrer: document.referrer || ''
2192
+ }, {
2193
+ cart_item_count: shContents.length
2194
+ }, 'cart_action');
2195
+ return;
2196
+ }
2197
+
2198
+ // ── 3. Per-artifact download link (downloadbinaries.json) ──
2199
+ // Fired when a user clicks any individual download anchor in
2200
+ // the downloads modal. This is the REAL "asset_download" event
2201
+ // — the binary leaves the server on this click, unlike the
2202
+ // cart-download button above which is just the user's intent
2203
+ // to start the download pipeline.
2204
+ var dlLink = tryClosest(target, SELECTORS.downloadBinaryLink);
2205
+ if (dlLink) {
2206
+ var href = dlLink.getAttribute('href') || '';
2207
+ var params = parseUrlParams(href);
2208
+ var endpoint = href.split('?')[0];
2209
+ track('asset_download', {
2210
+ download_id: params.downloadId || '',
2211
+ artifact_id: params.artifactId || '',
2212
+ download_endpoint: endpoint,
2213
+ download_source: 'downloads_modal',
2214
+ download_method: 'binary_link_click',
2215
+ page_url: location.href,
2216
+ page_referrer: document.referrer || ''
2217
+ });
2218
+ return;
2219
+ }
2220
+
2221
+ // ── 4. Per-artifact "remove from downloads" button ──
2222
+ var dlRemoveBtn = tryClosest(target, SELECTORS.downloadRemoveButton);
2223
+ if (dlRemoveBtn) {
2224
+ track('download_removed', {
2225
+ download_id: dlRemoveBtn.getAttribute('data-asset-share-download-id') || '',
2226
+ page_url: location.href
2227
+ }, {}, 'cart_action');
2228
+ return;
2229
+ }
2230
+
2231
+ // ── 5. Asset-level "Add to Cart" tile button ──
2232
+ // Now that the cart-level controls are handled above, anything
2233
+ // remaining with `data-asset-share-id="add-to-cart"` is the
2234
+ // per-asset variant. We DO NOT rely on the button's visible
2235
+ // text — the icon-only variant has none — and pull the asset
2236
+ // path straight off `data-asset-share-asset` via the extractor.
2237
+ var cartBtn = tryClosest(target, SELECTORS.addToCart);
2238
+ if (!cartBtn) {
2239
+ // Visible-text fallback for installations that haven't been
2240
+ // migrated to the data-asset-share-id convention yet.
2241
+ var cartCandidate = tryClosest(target, 'button, a, [role="button"], [role="menuitem"]');
2242
+ if (cartCandidate && TEXT_PATTERNS.cart.test(visibleText(cartCandidate))) {
2243
+ cartBtn = cartCandidate;
2244
+ }
2245
+ }
2246
+ if (cartBtn) {
2247
+ track('asset_add_to_cart', {
2248
+ asset_path: extractAssetPathFromEl(cartBtn),
2249
+ page_url: location.href
2250
+ });
2251
+ return;
2252
+ }
2253
+
2254
+ // ── 6. Header cart-icon click (opens cart modal) ──
2255
+ var cartOpen = tryClosest(target, SELECTORS.cartOpenButton);
2256
+ if (cartOpen) {
2257
+ track('cart_open', { page_url: location.href }, {}, 'cart_action');
2258
+ return;
2259
+ }
2260
+
2261
+ // ── 7. Header download-icon click (opens downloads modal) ──
2262
+ var dlOpen = tryClosest(target, SELECTORS.downloadsOpenButton);
2263
+ if (dlOpen) {
2264
+ track('downloads_open', { page_url: location.href }, {}, 'cart_action');
2265
+ return;
2266
+ }
2267
+
2268
+ // ── 8. Asset-level Share button ──
2269
+ var shareBtn = tryClosest(target, SELECTORS.shareButton);
2270
+ if (!shareBtn) {
2271
+ var shareCandidate = tryClosest(target, 'button, a, [role="button"], [role="menuitem"]');
2272
+ // Visible-text fallback — explicitly reject anything that sits
2273
+ // under the cart-modal or matches the cart-share selector, so
2274
+ // a generic /share/i click on Share Cart can't fall through
2275
+ // to asset_share here.
2276
+ if (shareCandidate &&
2277
+ TEXT_PATTERNS.share.test(visibleText(shareCandidate)) &&
2278
+ !TEXT_PATTERNS.cart.test(visibleText(shareCandidate)) &&
2279
+ !tryClosest(shareCandidate, SELECTORS.cartShareButton) &&
2280
+ !tryClosest(shareCandidate, SELECTORS.cartModal)) {
2281
+ shareBtn = shareCandidate;
2282
+ }
2283
+ }
2284
+ if (shareBtn) {
2285
+ track('asset_share', {
2286
+ asset_path: extractAssetPathFromEl(shareBtn),
2287
+ page_url: location.href
2288
+ });
2289
+ }
2290
+ }, { capture: true });
2291
+ }
2292
+
2293
+ /**
2294
+ * Parses the recipient e-mail field. The input is `<input
2295
+ * type="email" multiple name="email">` and the user typically types
2296
+ * `a@b.com, c@d.com, e@f.com` (the placeholder advertises a
2297
+ * comma-delimited list). We accept commas, semicolons, and
2298
+ * whitespace as separators, trim and de-dupe (case-insensitive),
2299
+ * and drop anything that doesn't look vaguely like an e-mail. The
2300
+ * returned array preserves the user's typed order for the first
2301
+ * occurrence of each address.
2302
+ */
2303
+ function parseRecipientEmails(raw) {
2304
+ if (!raw) return [];
2305
+ var parts = String(raw).split(/[,;\s]+/);
2306
+ var out = [];
2307
+ var seen = {};
2308
+ for (var i = 0; i < parts.length; i++) {
2309
+ var t = (parts[i] || '').trim();
2310
+ if (!t) continue;
2311
+ // Loose validation — we only want to drop obvious garbage
2312
+ // like trailing punctuation; the server will do real
2313
+ // validation downstream. We DO require an `@` plus a `.`
2314
+ // somewhere after it.
2315
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)) continue;
2316
+ var key = t.toLowerCase();
2317
+ if (seen[key]) continue;
2318
+ seen[key] = true;
2319
+ out.push(t);
2320
+ }
2321
+ return out;
2322
+ }
2323
+
2324
+ /**
2325
+ * Captures the share-modal form submission. The cart-level "Share
2326
+ * Cart" button (handled in installAscClickDelegation, branch 2)
2327
+ * fires a `cart_share_initiated` intent event AND stashes the cart
2328
+ * contents in `window.__ilVisaPendingCartShare` because the cart
2329
+ * modal usually closes before the share form is filled in. When
2330
+ * the user actually submits the share form, this hook fires the
2331
+ * REAL `cart_share` event with:
2332
+ *
2333
+ * - share_emails – comma-joined list (480-char cap)
2334
+ * - share_emails_count – metric, distinct after dedupe
2335
+ * - share_is_public – "true" / "false"
2336
+ * - share_start_date – yyyy-mm-dd (public-only)
2337
+ * - share_end_date – yyyy-mm-dd (public-only)
2338
+ * - share_date_range_days – metric, end-start in days (>=0)
2339
+ * - cart_asset_paths_json – snapshot from button-click stash,
2340
+ * falls back to a fresh
2341
+ * readCartContents() if the stash
2342
+ * expired (e.g. the user reloaded
2343
+ * between clicking and submitting)
2344
+ *
2345
+ * Capture phase + non-passive so we get the submit BEFORE ASC's
2346
+ * own jQuery validator can call preventDefault on an invalid form;
2347
+ * we still fire the event so the funnel sees the attempt. The
2348
+ * stash is cleared after a successful read so a subsequent
2349
+ * unrelated form submission can't accidentally inherit it.
2350
+ */
2351
+ function installShareFormHook() {
2352
+ if (window.__ilVisaShareFormHooked) return;
2353
+ window.__ilVisaShareFormHooked = true;
2354
+
2355
+ document.addEventListener('submit', function (e) {
2356
+ var form = e.target;
2357
+ if (!form || form.nodeType !== 1) return;
2358
+ var matchSelf = false;
2359
+ try { matchSelf = form.matches && form.matches(SELECTORS.shareModal); } catch (err) { /* ignore */ }
2360
+ // The event target IS the form, but be defensive in case the
2361
+ // template ever wraps the submission in a parent element.
2362
+ if (!matchSelf) {
2363
+ var ancestor = null;
2364
+ try { ancestor = form.closest && form.closest(SELECTORS.shareModal); } catch (err) { /* ignore */ }
2365
+ if (!ancestor) return;
2366
+ form = ancestor;
2367
+ }
2368
+
2369
+ var emailInput = form.querySelector(SELECTORS.shareEmailInput);
2370
+ var emails = parseRecipientEmails(emailInput && emailInput.value);
2371
+ var emailsJoined = emails.join(',');
2372
+ if (emailsJoined.length > 480) emailsJoined = emailsJoined.slice(0, 480);
2373
+
2374
+ // "Share Publicly" — the explicit checkbox match comes first.
2375
+ // If multiple checkboxes exist in the form (some themes add a
2376
+ // T&C tickbox), we look for the one paired with the "Share
2377
+ // Publicly" label by walking up to the .ui.checkbox wrapper.
2378
+ var publicChecked = false;
2379
+ var cbCandidates = form.querySelectorAll(SELECTORS.sharePublicCheckbox);
2380
+ for (var i = 0; i < cbCandidates.length; i++) {
2381
+ var cb = cbCandidates[i];
2382
+ var wrap = cb.closest('.ui.checkbox, .field');
2383
+ var lbl = wrap && (wrap.querySelector('label') || wrap);
2384
+ var txt = lbl ? (lbl.textContent || '').trim() : '';
2385
+ if (cbCandidates.length === 1 || /share\s*publicly/i.test(txt)) {
2386
+ publicChecked = !!cb.checked;
2387
+ break;
2388
+ }
2389
+ }
2390
+
2391
+ var startEl = form.querySelector(SELECTORS.shareStartDateInput);
2392
+ var expiryEl = form.querySelector(SELECTORS.shareExpiryDateInput);
2393
+ var startDate = (startEl && startEl.value) || '';
2394
+ var expiryDate = (expiryEl && expiryEl.value) || '';
2395
+ // Heuristic — if the dates are populated but the checkbox
2396
+ // matcher missed (e.g. the theme rebrands the label), treat
2397
+ // the share as public anyway. Better to over-tag than miss
2398
+ // the public-share population entirely.
2399
+ if (!publicChecked && (startDate || expiryDate)) publicChecked = true;
2400
+
2401
+ var rangeDays = 0;
2402
+ if (startDate && expiryDate) {
2403
+ var s = Date.parse(startDate);
2404
+ var e2 = Date.parse(expiryDate);
2405
+ if (!isNaN(s) && !isNaN(e2)) rangeDays = Math.max(0, Math.round((e2 - s) / 86400000));
2406
+ }
2407
+
2408
+ var stash = window.__ilVisaPendingCartShare;
2409
+ var stashFresh = stash && (Date.now() - stash.captured_at < 10 * 60 * 1000);
2410
+ var pathsJson, pathsCount;
2411
+ if (stashFresh) {
2412
+ pathsJson = stash.paths_json || '';
2413
+ pathsCount = (stash.paths && stash.paths.length) || 0;
2414
+ } else {
2415
+ var fresh = readCartContents();
2416
+ pathsJson = fresh.length ? JSON.stringify(fresh) : '';
2417
+ if (pathsJson.length > 480) pathsJson = pathsJson.slice(0, 480);
2418
+ pathsCount = fresh.length;
2419
+ }
2420
+ window.__ilVisaPendingCartShare = null;
2421
+
2422
+ track('cart_share', {
2423
+ share_emails: emailsJoined,
2424
+ share_is_public: publicChecked ? 'true' : 'false',
2425
+ share_start_date: publicChecked ? startDate : '',
2426
+ share_end_date: publicChecked ? expiryDate : '',
2427
+ cart_asset_paths_json: pathsJson,
2428
+ page_url: location.href,
2429
+ page_referrer: document.referrer || ''
2430
+ }, {
2431
+ share_emails_count: emails.length,
2432
+ share_date_range_days: rangeDays,
2433
+ cart_item_count: pathsCount
2434
+ }, 'cart_action');
2435
+ }, { capture: true });
2436
+ }
2437
+
2438
+ // ─── 9b. Asset Explorer (React) hooks ────────────────────
2439
+
2440
+ /**
2441
+ * Wires every plausible search trigger on /asset-explorer.html. The
2442
+ * page is a React SPA that doesn't expose a single canonical "search
2443
+ * submit" event, so we listen at the document level (capture phase)
2444
+ * for the four observed user intents:
2445
+ *
2446
+ * - Enter pressed inside the search input
2447
+ * - Native form submit (Enter or a button reachable via submit())
2448
+ * - The Search Options modal closing (treated as "user accepted
2449
+ * semantic/fuzzy choice and the search will now run")
2450
+ * - A click on any element inside the right-rail filter wrapper
2451
+ * (treated as "user changed a facet and a new search will run")
2452
+ *
2453
+ * Plus a debounced `input` listener so live-typing scenarios — if any —
2454
+ * still record the eventual term. Every fire carries a `search_trigger`
2455
+ * dimension so we can drop the redundant hooks once we see what the
2456
+ * page actually emits in ClickHouse.
2457
+ *
2458
+ * Dedup is centralized inside trackAssetExplorerSearch() via
2459
+ * __aeLastFiredSig so overlapping triggers (Enter + form submit) on the
2460
+ * same user action collapse into a single event.
2461
+ */
2462
+ function installAssetExplorerHooks() {
2463
+ if (window.__ilVisaAEHooked) return;
2464
+ window.__ilVisaAEHooked = true;
2465
+
2466
+ function currentTerm() {
2467
+ var inp = findAssetExplorerSearchInput();
2468
+ return inp ? (inp.value || '').trim() : '';
2469
+ }
2470
+
2471
+ function fireWithTrigger(trigger) {
2472
+ var term = currentTerm();
2473
+ if (!term) return;
2474
+ trackAssetExplorerSearch(term, { trigger: trigger });
2475
+ }
2476
+
2477
+ // ── 1. Enter inside the search input ─────────────────────
2478
+ document.addEventListener('keydown', function (e) {
2479
+ if (e.key !== 'Enter' && e.keyCode !== 13) return;
2480
+ var t = e.target;
2481
+ if (!t || t.nodeType !== 1) return;
2482
+ // Match either the explorer's React input OR any text input that
2483
+ // sits under the explorer root (themed deployments may swap the
2484
+ // CSS-Module class).
2485
+ var inExplorer = t.closest && t.closest(SELECTORS.assetExplorerRoot);
2486
+ if (!inExplorer) return;
2487
+ if (t.tagName !== 'INPUT' && t.tagName !== 'TEXTAREA') return;
2488
+ setTimeout(function () { fireWithTrigger('enter'); }, 0);
2489
+ }, { capture: true });
2490
+
2491
+ // ── 2. Native form submit ────────────────────────────────
2492
+ document.addEventListener('submit', function (e) {
2493
+ var f = e.target;
2494
+ if (!f || !f.closest) return;
2495
+ if (!f.closest(SELECTORS.assetExplorerRoot)) return;
2496
+ setTimeout(function () { fireWithTrigger('submit'); }, 0);
2497
+ }, { capture: true });
2498
+
2499
+ // ── 3. Search Options modal close ───────────────────────
2500
+ // We can't always observe the modal-close gesture directly (escape
2501
+ // key, clicking the backdrop, clicking a confirm button). Instead,
2502
+ // watch for the modal element being REMOVED from the DOM and treat
2503
+ // that as "user finished tweaking semantic/fuzzy".
2504
+ if (typeof MutationObserver === 'function') {
2505
+ var modalState = { open: false };
2506
+ try {
2507
+ var mo = new MutationObserver(function () {
2508
+ var modal = document.querySelector(
2509
+ '[class*="_searchOptionModal_"], [class*="_searchOption_Modal_"], [class*="_searchOptionsModal_"]'
2510
+ );
2511
+ var nowOpen = !!modal;
2512
+ if (modalState.open && !nowOpen) {
2513
+ setTimeout(function () { fireWithTrigger('options_close'); }, 0);
2514
+ }
2515
+ modalState.open = nowOpen;
2516
+ });
2517
+ mo.observe(document.body || document.documentElement, {
2518
+ childList: true,
2519
+ subtree: true
2520
+ });
2521
+ } catch (e) { /* fall through */ }
2522
+ }
2523
+
2524
+ // ── 4. Filter-rail clicks ───────────────────────────────
2525
+ document.addEventListener('click', function (e) {
2526
+ var t = e.target;
2527
+ if (!t || !t.closest) return;
2528
+ var rail = t.closest(SELECTORS.assetExplorerFilterRail);
2529
+ if (!rail) return;
2530
+ // Defer past React's re-render so the term + stats reflect the
2531
+ // new filter state when we read them.
2532
+ setTimeout(function () {
2533
+ // We bypass the term-empty check via forceDedupBypass=false so
2534
+ // a filter-only narrow over an empty search isn't tracked here;
2535
+ // it falls into folder_navigation territory.
2536
+ fireWithTrigger('filter_click');
2537
+ }, 30);
2538
+ }, { capture: true });
2539
+
2540
+ // ── 5. Debounced typing (catch-all for auto-search builds) ──
2541
+ var debounceTimer = null;
2542
+ document.addEventListener('input', function (e) {
2543
+ var t = e.target;
2544
+ if (!t || t.nodeType !== 1) return;
2545
+ if (t.tagName !== 'INPUT') return;
2546
+ if (!t.closest || !t.closest(SELECTORS.assetExplorerRoot)) return;
2547
+ var inp = findAssetExplorerSearchInput();
2548
+ if (!inp || t !== inp) return;
2549
+ if (debounceTimer) clearTimeout(debounceTimer);
2550
+ debounceTimer = setTimeout(function () {
2551
+ fireWithTrigger('input_debounced');
2552
+ }, 800);
2553
+ }, { capture: true });
2554
+
2555
+ // ── 6. Hash-route folder navigation ─────────────────────
2556
+ window.addEventListener('hashchange', function () {
2557
+ // Reset the search-event dedup signature so the new folder's first
2558
+ // search records cleanly even if its (term, toggles) happen to
2559
+ // match the previous folder's.
2560
+ __aeLastFiredSig = '';
2561
+ trackAssetExplorerFolderNavigation({ tree_action: 'hash_change' });
2562
+ });
2563
+
2564
+ // ── 7. Folder-tree click delegation ─────────────────────
2565
+ // Every click anywhere inside the side directory tree fires
2566
+ // folder_navigation(subtype=asset_browse) so we observe folder
2567
+ // selections (which usually also trigger hashchange) AND
2568
+ // expand/collapse gestures (which do not). We best-effort classify
2569
+ // the action via aria-expanded mutation, fall back to "click" if
2570
+ // we can't tell, and tag the event with diagnostic dims so the
2571
+ // refinement is data-driven from ClickHouse.
2572
+ document.addEventListener('click', function (e) {
2573
+ var target = e.target;
2574
+ if (!target || target.nodeType !== 1 || !target.closest) return;
2575
+ var tree = target.closest(SELECTORS.assetExplorerFolderTree);
2576
+ if (!tree) return;
2577
+ // Skip clicks that landed in the rail's facet panel — that's the
2578
+ // right side (search_executed/filter_click territory), not the
2579
+ // left tree. The selectors *can* overlap on extremely permissive
2580
+ // builds where both panels share `_wrapper_` ancestors.
2581
+ if (target.closest(SELECTORS.assetExplorerFilterRail)) return;
2582
+
2583
+ // Find the closest folder-row element so we can capture the
2584
+ // folder label (visible text) and the aria-expanded state.
2585
+ // Tree-row markup we expect (best-effort):
2586
+ // [role="treeitem"] | [class*="_treeNode_"] | [class*="_node_"]
2587
+ // | the immediate clickable wrapper (`<li>` / `<button>`).
2588
+ var node = target.closest(
2589
+ '[role="treeitem"], [class*="_treeNode_"], [class*="_node_"], [class*="_folder_"], [class*="_item_"], li, button, a'
2590
+ ) || target;
2591
+
2592
+ var labelEl = node.querySelector('[class*="_label_"], [class*="_name_"], [class*="_title_"]') || node;
2593
+ var label = cleanText(labelEl.textContent || '').slice(0, 120);
2594
+
2595
+ var preExpanded = node.getAttribute && node.getAttribute('aria-expanded');
2596
+
2597
+ // Sample the className for diagnostic use — strip whitespace and
2598
+ // cap aggressively to avoid blowing the custom_dimensions column.
2599
+ var cls = (target.className && target.className.baseVal !== undefined)
2600
+ ? target.className.baseVal
2601
+ : String(target.className || '');
2602
+
2603
+ // Snapshot the node's current className too — some React tree
2604
+ // libs put the expanded/collapsed state directly on the row
2605
+ // (`_isOpen`, `_expanded`, `_collapsed`, `_open`) rather than on
2606
+ // an aria-expanded attribute, so we'll need both pre- and post-
2607
+ // click className samples to classify the gesture.
2608
+ var preNodeCls = (node.className && node.className.baseVal !== undefined)
2609
+ ? node.className.baseVal
2610
+ : String(node.className || '');
2611
+
2612
+ // Live React Asset Explorer uses classes like `_toggleIcon_<hash>`
2613
+ // on the expand/collapse chevron. Anything matching one of these
2614
+ // unambiguous "this is a toggle gesture" prefixes is treated as
2615
+ // an expand/collapse even when aria-expanded never shows up.
2616
+ var TOGGLE_CLS_RE = /(?:^|[\s_-])(?:_?toggleIcon|_?toggle|_?chevron|_?arrow|_?caret|_?expand(?:er|Icon)?|_?collapse(?:r|Icon)?)(?:[\s_-]|$)/i;
2617
+ var isToggle = TOGGLE_CLS_RE.test(cls);
2618
+
2619
+ // Defer to the next tick so the React state has had time to apply
2620
+ // the click (aria-expanded flips, classNames toggled, hash routes
2621
+ // pushed, etc.) before we classify. The hashchange listener above
2622
+ // is independent and will fire its own event if the URL changes.
2623
+ setTimeout(function () {
2624
+ var postExpanded = node.getAttribute && node.getAttribute('aria-expanded');
2625
+ var postNodeCls = (node.className && node.className.baseVal !== undefined)
2626
+ ? node.className.baseVal
2627
+ : String(node.className || '');
2628
+
2629
+ // ── Strategy 1: aria-expanded mutation ───────────────
2630
+ var action = null;
2631
+ if (preExpanded !== null && postExpanded !== null && preExpanded !== postExpanded) {
2632
+ action = (postExpanded === 'true') ? 'expand' : 'collapse';
2633
+ } else if (postExpanded === 'true' && preExpanded === null) {
2634
+ action = 'expand';
2635
+ } else if (postExpanded === 'false' && preExpanded === null) {
2636
+ action = 'collapse';
2637
+ }
2638
+
2639
+ // ── Strategy 2: className state on the row ───────────
2640
+ // React tree libs commonly emit `_isOpen_<hash>` / `_expanded_<hash>`
2641
+ // / `_isCollapsed_<hash>` / `_collapsed_<hash>` on the row when
2642
+ // the open state changes. Compare pre vs post — if either flag
2643
+ // appeared / disappeared, that's our action.
2644
+ if (!action) {
2645
+ var EXP_RE = /_(?:isOpen|expanded|open(?![A-Za-z]))/i;
2646
+ var COLL_RE = /_(?:isClosed|collapsed|closed)/i;
2647
+ var preExp = EXP_RE.test(preNodeCls);
2648
+ var postExp = EXP_RE.test(postNodeCls);
2649
+ var preColl = COLL_RE.test(preNodeCls);
2650
+ var postColl = COLL_RE.test(postNodeCls);
2651
+ if (!preExp && postExp) action = 'expand';
2652
+ else if (preExp && !postExp) action = 'collapse';
2653
+ else if (!preColl && postColl) action = 'collapse';
2654
+ else if (preColl && !postColl) action = 'expand';
2655
+ }
2656
+
2657
+ // ── Strategy 3: toggle-class hint without direction ──
2658
+ // Click landed on an unambiguous toggle icon but we couldn't
2659
+ // determine direction from the row state. Record the gesture
2660
+ // as a generic `toggle` — still strictly more useful than
2661
+ // `click` because dashboards can split tree-navigation events
2662
+ // from open/close gestures.
2663
+ if (!action) {
2664
+ action = isToggle ? 'toggle' : 'click';
2665
+ }
2666
+
2667
+ // The handler also fires for clicks that ALSO trigger a hash
2668
+ // change. We DO NOT dedup against the hashchange-fired event
2669
+ // here — the user explicitly asked for every click / expand /
2670
+ // collapse gesture to be tracked, so emitting both a click
2671
+ // event AND a hash_change event for the same gesture is the
2672
+ // desired behaviour. Differentiate via the `tree_action` dim
2673
+ // in reports.
2674
+ trackAssetExplorerFolderNavigation({
2675
+ tree_action: action,
2676
+ tree_target_label: label,
2677
+ tree_target_class_hint: cls
2678
+ });
2679
+ }, 0);
2680
+ }, { capture: true });
2681
+ }
2682
+
2683
+ // ─── 10. Network interception for downloads ──────────────
2684
+
2685
+ /**
2686
+ * Emits `asset_download` if a request matches the ASC download endpoint.
2687
+ * Extracts `asset_path` (`path`) and `rendition_name` (`renditionName`)
2688
+ * directly from the form-encoded POST body so the event reflects exactly
2689
+ * what the user requested (single-asset, ZIP of renditions, etc.).
2690
+ */
2691
+ function emitDownloadIfMatch(method, url, body) {
2692
+ if (!url) return;
2693
+ if (method && String(method).toUpperCase() !== 'POST') return;
2694
+ if (!ENDPOINTS.download.test(url)) return;
2695
+ var info = parseFormBody(body);
2696
+ track('asset_download', {
2697
+ asset_path: safeStr(info.path),
2698
+ rendition_name: safeStr(info.renditionName),
2699
+ download_endpoint: url,
2700
+ page_url: location.href
2701
+ });
2702
+ }
2703
+
2704
+ /**
2705
+ * Wraps `window.fetch` and `XMLHttpRequest.prototype.{open,send}` once
2706
+ * per page. Idempotent across hot-reloads of the bootstrap. Always calls
2707
+ * the original implementation so site behavior is unchanged.
2708
+ */
2709
+ function installNetworkHooks() {
2710
+ if (typeof window.fetch === 'function' && !window.__ilVisaFetchPatched) {
2711
+ window.__ilVisaFetchPatched = true;
2712
+ var origFetch = window.fetch;
2713
+ window.fetch = function (input, init) {
2714
+ try {
2715
+ var url = typeof input === 'string' ? input : (input && input.url) || '';
2716
+ var method = (init && init.method) || (input && input.method) || 'GET';
2717
+ var body = init && init.body;
2718
+ emitDownloadIfMatch(method, url, body);
2719
+ } catch (e) { /* swallow — never break the page */ }
2720
+ return origFetch.apply(this, arguments);
2721
+ };
2722
+ }
2723
+
2724
+ if (typeof window.XMLHttpRequest === 'function' && !window.__ilVisaXhrPatched) {
2725
+ window.__ilVisaXhrPatched = true;
2726
+ var XHRProto = window.XMLHttpRequest.prototype;
2727
+ var origOpen = XHRProto.open;
2728
+ var origSend = XHRProto.send;
2729
+ XHRProto.open = function (method, url) {
2730
+ this.__ilVisaMethod = method;
2731
+ this.__ilVisaUrl = url;
2732
+ return origOpen.apply(this, arguments);
2733
+ };
2734
+ XHRProto.send = function (body) {
2735
+ try { emitDownloadIfMatch(this.__ilVisaMethod, this.__ilVisaUrl, body); } catch (e) {}
2736
+ return origSend.apply(this, arguments);
2737
+ };
2738
+ }
2739
+ }
2740
+
2741
+ // ─── 11. Orchestration ───────────────────────────────────
2742
+
2743
+ var HOOK_FLAG = '__il_visa_hooked__';
2744
+
2745
+ /**
2746
+ * Login-page hook installer. Idempotent thanks to per-element flags so the
2747
+ * MutationObserver can re-run safely as the SPA mounts late controls.
2748
+ */
2749
+ function safeHookLoginAll() {
2750
+ function once(el, name, fn) {
2751
+ if (!el || el[HOOK_FLAG + name]) return;
2752
+ el[HOOK_FLAG + name] = true;
2753
+ fn();
2754
+ }
2755
+ var form = $(SELECTORS.loginForm);
2756
+ var signBtn = $(SELECTORS.signInButton)
2757
+ || closestMatchByText(document, 'button, a, [role="button"], input[type="submit"]', TEXT_PATTERNS.signIn);
2758
+ var ssoBtn = $(SELECTORS.ssoButton)
2759
+ || closestMatchByText(document, 'button, a, [role="button"]', TEXT_PATTERNS.lionSso);
2760
+ var terms = $(SELECTORS.termsLink)
2761
+ || closestMatchByText(document, 'a, button, [role="link"]', TEXT_PATTERNS.terms);
2762
+
2763
+ once(form, 'form', function () {
2764
+ form.addEventListener('submit', function () {
2765
+ var userInput = $(SELECTORS.userField);
2766
+ var typedUser = (userInput && (userInput.value || '').trim()) || '';
2767
+ if (typedUser) identify(typedUser);
2768
+ track('login_attempt', {
2769
+ method: 'credentials',
2770
+ attempt_user: typedUser,
2771
+ submit_reason: 'submit',
2772
+ page_url: location.href
2773
+ });
2774
+ flush();
2775
+ }, { capture: true });
2776
+ });
2777
+
2778
+ once(signBtn, 'sign', function () {
2779
+ signBtn.addEventListener('click', function () {
2780
+ var userInput = $(SELECTORS.userField);
2781
+ var typedUser = (userInput && (userInput.value || '').trim()) || '';
2782
+ if (typedUser) identify(typedUser);
2783
+ track('login_attempt', {
2784
+ method: 'credentials',
2785
+ attempt_user: typedUser,
2786
+ submit_reason: 'click',
2787
+ page_url: location.href
2788
+ });
2789
+ flush();
2790
+ }, { capture: true });
2791
+ });
2792
+
2793
+ once(ssoBtn, 'sso', function () {
2794
+ ssoBtn.addEventListener('click', function () {
2795
+ track('sso_click', {
2796
+ method: 'lion_login',
2797
+ sso_provider: 'lion',
2798
+ button_text: visibleText(ssoBtn).substring(0, 120),
2799
+ page_url: location.href
2800
+ });
2801
+ flush();
2802
+ }, { capture: true });
2803
+ });
2804
+
2805
+ once(terms, 'terms', function () {
2806
+ terms.addEventListener('click', function () {
2807
+ track('terms_click', {
2808
+ link_url: (terms.getAttribute && terms.getAttribute('href')) || '',
2809
+ link_text: visibleText(terms).substring(0, 120),
2810
+ page_url: location.href
2811
+ });
2812
+ flush();
2813
+ }, { capture: true });
2814
+ });
2815
+ }
2816
+
2817
+ function start() {
2818
+ if (!initSdk()) {
2819
+ console.warn('[IL-VISA] Infralytiqs SDK not loaded — bootstrap aborted');
2820
+ return;
2821
+ }
2822
+
2823
+ // Identity FIRST so subsequent events carry user_id.
2824
+ // (Cache-hit path is sync; Granite-fetch path updates identity for the
2825
+ // next event batch — pre-flush events are already correctly tagged via
2826
+ // the SDK's identify-then-flush ordering.)
2827
+ resolveAndIdentifyUser();
2828
+
2829
+ // URL-driven events (fire once on page load), dispatched by context.
2830
+ if (isLoginPage()) {
2831
+ trackLoginPageView();
2832
+ safeHookLoginAll();
2833
+
2834
+ if (typeof MutationObserver === 'function') {
2835
+ var mo = new MutationObserver(function () { safeHookLoginAll(); });
2836
+ mo.observe(document.documentElement || document.body, {
2837
+ childList: true,
2838
+ subtree: true
2839
+ });
2840
+ // Stop watching after 20s — by then the SPA has settled and anything
2841
+ // we missed isn't going to appear from a page-load mutation.
2842
+ setTimeout(function () { mo.disconnect(); }, 20000);
2843
+ }
2844
+ } else if (isAssetExplorerPage()) {
2845
+ // React-based Asset Explorer (/asset-explorer.html#/content/dam/...)
2846
+ // — search and folder browsing live entirely in client-side state,
2847
+ // so we rely on DOM event hooks rather than URL parsing.
2848
+ installAssetExplorerHooks();
2849
+ // Asset preview / download / cart / share interactions piggy-back on
2850
+ // the same delegated listeners as ASC. They're a no-op if the page
2851
+ // doesn't render those affordances.
2852
+ installAscClickDelegation();
2853
+ installShareFormHook();
2854
+ installNetworkHooks();
2855
+ // Initial folder-view ping so reports see the user landed.
2856
+ // tagged "page_load" to distinguish from later interactions.
2857
+ trackAssetExplorerFolderNavigation({ tree_action: 'page_load' });
2858
+ } else {
2859
+ var q = parseQuery();
2860
+ trackSearchExecuted(q);
2861
+ trackAssetPreview();
2862
+ installAscClickDelegation();
2863
+ installShareFormHook();
2864
+ installNetworkHooks();
2865
+ // ASC drives in-page filter / sort / layout / pagination changes
2866
+ // through history.pushState — without this our URL-driven events
2867
+ // would only fire on hard reloads.
2868
+ installSpaNavHooks();
2869
+ }
2870
+ }
2871
+
2872
+ // ─── 12. Entry point ─────────────────────────────────────
2873
+ function waitForSdkAndStart() {
2874
+ var attempts = 0;
2875
+ var max = 50;
2876
+ (function tick() {
2877
+ if (getApi()) {
2878
+ start();
2879
+ return;
2880
+ }
2881
+ if (++attempts >= max) {
2882
+ console.warn('[IL-VISA] Infralytiqs SDK never appeared after ' + (max * 100) + 'ms');
2883
+ return;
2884
+ }
2885
+ setTimeout(tick, 100);
2886
+ })();
2887
+ }
2888
+
2889
+ if (document.readyState === 'loading') {
2890
+ document.addEventListener('DOMContentLoaded', waitForSdkAndStart, { once: true });
2891
+ } else {
2892
+ waitForSdkAndStart();
2893
+ }
2894
+ })();