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