@sharadtech/infralytiqs-sdk 1.0.1 → 1.0.2

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