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