@depict-ai/utilishared 1.0.28 → 1.0.30

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.
@@ -0,0 +1,2534 @@
1
+ /// <reference path="../jsx.d.ts" />
2
+ import { EUnavailabilityType } from "@depict-ai/types/api/TrackV2Request";
3
+ export const version = "1.0.30";
4
+ export const is_debug: boolean;
5
+ /**
6
+ * Sets the prefix of dlog, dwarn, and derror messages in the browser console. Defaults to `[Depict]`.
7
+ */
8
+ export const set_browser_prefix: (str: any) => void;
9
+ export function dlog(...args: any[]): void;
10
+ export function dwarn(...args: any[]): void;
11
+ export function derror(...args: any[]): void;
12
+ /**
13
+ * Adds things to the object we send to backend in the query params to report the package versions used
14
+ */
15
+ export const version_info: {
16
+ [key: string]: string;
17
+ };
18
+ export function add_to_version_info(package_name: string, version: string): void;
19
+ /**
20
+ * Adds the version info to the query params of a URL
21
+ * @param url: a URL object or a string containing a relative or absolute URL
22
+ * @returns the same type as the input but with added query params
23
+ */
24
+ export function add_version_query_params<T extends string | URL>(url: T): T;
25
+ /**
26
+ * Encoding UTF8 ⇢ base64
27
+ */
28
+ export function base64_encode_unicode(str: any): string;
29
+ /**
30
+ * Decoding base64 ⇢ UTF8
31
+ */
32
+ export function base64_decode_unicode(str: any): string;
33
+ /**
34
+ * Class containing state that an IPNS operates on. It's only exported for type info and in case that you want to use it for instanceof checks.
35
+ * subscribers is an array of functions that get called every time push_value is called with a new value AND all previous subscribers are done
36
+ * queue is the queue of values that subscribers gets called with
37
+ * last_processed_value is the last value that the subscribers were called with
38
+ * push_value adds a new value to the queue and triggers the calling of the subscribers if they're done
39
+ * subscriber_done decrements the number of subscribers we are waiting for, if this isn't called call_subscribers will get stuck. It also triggers a new call to call_subscribers
40
+ */
41
+ export class RawObservableInformation<T> {
42
+ subscribers_: ((val: T) => void)[];
43
+ waiting_for_update_: number;
44
+ queue_: T[];
45
+ last_processed_value_: T | undefined;
46
+ has_had_value_: boolean;
47
+ push_value_: (value: T) => void;
48
+ call_subscribers_: () => void;
49
+ subscriber_done_: () => void;
50
+ }
51
+ /**
52
+ * Makes an asyncIterable function out of a RawObservableInformation instance
53
+ */
54
+ export function make_simple_async_iterable<T>(state: RawObservableInformation<T>): ((...values: T[]) => void) & {
55
+ [Symbol.asyncIterator](): {
56
+ next(): Promise<{
57
+ value: T;
58
+ done: false;
59
+ }>;
60
+ return(): Promise<{
61
+ value: T;
62
+ done: false;
63
+ }>;
64
+ };
65
+ };
66
+ /**
67
+ * You know how you can write `break` inside of a `for await` loop to exit it? Well, this lets you break the loop from outside. Pass any async iterable that never throws and you will get back a function and a specially proxied async iterable. Whenever you call the function all for await loops iterating the returned iterable will break. Note: This will add some extra ticks because awaiting thenable objects takes more ticks than awaiting promises.
68
+ * @param async_iterable The async iterable you want to make exitable
69
+ * @return An array containing a function, the exit function, and a wrapped async iterable
70
+ */
71
+ export function make_asyncIterable_exiter<T>(async_iterable: AsyncIterable<T>): [() => void, AsyncIterable<T>];
72
+ export type IPNS<T> = ((...values: T[]) => void) & AsyncIterable<T> & {
73
+ exit: () => void;
74
+ state: T | undefined;
75
+ latest_call_value: T | undefined;
76
+ };
77
+ /**
78
+ * Creates an async iterable IPNS with "the old" API (we should maybe create a new one? idk). BUT which is resistant against things taking more than one tick. Meaning you can use `await` in the `for await` body without missing values
79
+ * # More about IPNS
80
+ * It's a form of observable. Basically an infinite promise.
81
+ * You await it by using for-await and you resolve it (as often as you like) by calling it.
82
+ * List of random details:
83
+ * 1. You can call it as fast as you like, the values will propagate into the for-awaits once all for-awaits have finished processing the value
84
+ * 2. Giving it multiple arguments and calling it multiple times is the same thing
85
+ * 3. IPNS.exit(); is going to make all for-await loops currently awaiting it exit EXCEPT for ones with currently executing loop bodies. Means if you do `IPNS.exit()` it won't exit the current loop - for that you need to use `break`. It does not change the IPNS in any other way so you can continue using it afterwards.
86
+ * 4. You can use make_asyncIterable_exiter() to make individual for-await loop exit (stop awaiting the infinite promise) from the outside
87
+ * 5. You can of course break and return any time from the for-await to stop awaiting
88
+ * 6. IPNS.state gives you the value that's currently processed inside of the for-awaits from the outside
89
+ * 7. IPNS.latest_call_value is the value that the IPNS was last called with (it doesn't have to have propagated everywhere yet)
90
+ * @param exitable Whether the async iterator should return the currently resolving value on the first call or not
91
+ * @param {state_obj} RawObservableInformation instance that contains the actual inner values of the IPNS
92
+ * @return An IPNS.
93
+ */
94
+ export function async_iterable_ipns<T>(async_iterator_should_return_state_on_first_call?: boolean, state_obj?: RawObservableInformation<T>): IPNS<T>;
95
+ /**
96
+ * Takes an IPNS that always resolves with state on first await and returns one that's in sync with the first one and doesn't
97
+ * @param ipns IPNS to create "clone" of
98
+ * @return A "cloned" ipns with the desired state-behavior. Keep in mind that exiting this one will not exit the one that was cloned.
99
+ */
100
+ export function make_ipns_stateless<T>(ipns: IPNS<T>): IPNS<any>;
101
+ /**
102
+ * Takes an IPNS that doesn't resolve with state on first await and returns one that's in sync with the first one and does
103
+ * @param ipns IPNS to create "clone" of
104
+ * @return A "cloned" ipns with the desired state-behavior. Keep in mind that exiting this one will not exit the one that was cloned.
105
+ */
106
+ export function make_ipns_stateful<T>(ipns: IPNS<T>): IPNS<any>;
107
+ /**
108
+ * @deprecated please use report instead and provide a severity
109
+ */
110
+ export function err(exception: Error | any, error_for_stack?: Error): undefined;
111
+ /**
112
+ * is_available_in: this function returns a promise that resolves once a variable has been defined inside of an object - or instantly, if it's already defined.
113
+ * The function uses getters and setters instead of polling which means it doesn't waste any resources.
114
+ * If there are already getters or setters the function will proxy them, retaining their original functionality.
115
+ * Only drawback is you can only wait for the variable being defined once, not for every change.
116
+ * @param obj The base object to look in
117
+ * @param property The property to wait for first
118
+ * @param ...sub_objects_to_wait_for A list of further properties to wait for in the result of the last awaited thing
119
+ * @return A promise containing the value of the variable that has been defined
120
+ */
121
+ export function is_available_in(obj: Object, property: PropertyKey, ...sub_objects_to_wait_for: PropertyKey[]): any;
122
+ export function find_descriptor(obj: Object, prop: PropertyKey): PropertyDescriptor | undefined;
123
+ export function variable_setter_to_ipns<T>(obj: Object, variable: PropertyKey, async_iterator_should_return_state_on_first_call?: boolean): IPNS<T>;
124
+ export const Sentry: Hub | {
125
+ captureException: (...args: any[]) => void;
126
+ captureMessage: (...args: any[]) => void;
127
+ withScope: (...args: any[]) => void;
128
+ };
129
+ /**
130
+ * Severity level to send to sentry.
131
+ * We can also send `log`, `info`, `debug`, `critical` and `fatal` but we haven't had a need for it yet.
132
+ */
133
+ type Severity = "error" | "warning";
134
+ /**
135
+ * Wraps a function in a try/catch that sends the error to sentry.
136
+ * Also works for functions returning a promise/async functions.
137
+ * If the function threw the wrapped function will return `undefined`
138
+ * @param fn The function to wrap
139
+ * @param message The message of the sentry error
140
+ * @param severity The severity level to send to sentry
141
+ */
142
+ export function catchify<T extends any[], X>(fn: (...args: T) => X, message?: string, severity?: Severity): (...args: T) => X extends Promise<any> ? Promise<undefined | Awaited<X>> : X | undefined;
143
+ /**
144
+ * Send error message with given severity and extra info to sentry
145
+ * @param msg Error object to send to sentry or an array containing an error and a human-readable description for said error
146
+ * @param severity How severe the error is.
147
+ * - `"error"` - Things like not finding the market, unexpected product-id format. Even one of these errors is cause for concern.
148
+ * - `"warning"` - Things that we expect to happen _sometimes_, like network errors. A couple of them is normal,
149
+ * but if we suddenly get 1000s then that's an issue
150
+ * @param input_data An object with extra information to sent to sentry.
151
+ *
152
+ * @example
153
+ * report([err, "Got to few recs"], "warning", {
154
+ * product_id,
155
+ * })
156
+ */
157
+ export function report(msg: Error | [Error, string], severity: Severity, input_data?: {
158
+ [key: string]: any;
159
+ stack?: never;
160
+ }): void;
161
+ /**
162
+ * Gives a random number between min and max (potentially including min and max).
163
+ * @param min The minimum number.
164
+ * @param max The maximum number.
165
+ * @returns a random number
166
+ */
167
+ export function rand(min: number, max: number): number;
168
+ export type AsyncFunction<A extends any[], O> = (...args: A) => Promise<O>;
169
+ /**
170
+ * Wraps an async function and makes sure the returned wrapped function can only be "executing" once at the same time.
171
+ * @param the_function an async function to wrap
172
+ * @return The same function but wrapped so that it can only run once at once, no matter how often you call it
173
+ */
174
+ export function deparallelize<A extends any[], O>(the_function: AsyncFunction<A, O>): (...args: A) => Promise<Awaited<O> | undefined>;
175
+ /**
176
+ * Like deparallelize but it makes sure that the last call of the function, while it's busy, will be executed after it's no longer busy.
177
+ */
178
+ export function deparallelize_no_drop<A extends any[], O>(the_function: AsyncFunction<A, O>): (...args: A) => Promise<Awaited<O> | undefined>;
179
+ /**
180
+ * @deprecated use async_iterable_ipns instead. It has a nicer API and more of an ecosystem.
181
+ */
182
+ export class infinite_promise_no_skip<T> {
183
+ #private;
184
+ promise: Promise<T>;
185
+ resolve: (value: T) => void;
186
+ }
187
+ type ws_event_callback = typeof WebSocket.prototype.onmessage;
188
+ export interface AutoReconnectingWS {
189
+ onclose: ws_event_callback;
190
+ onerrror: ws_event_callback;
191
+ onmessage: ws_event_callback;
192
+ onopen: ws_event_callback;
193
+ }
194
+ export class AutoReconnectingWS extends EventTarget {
195
+ #private;
196
+ current_socket: WebSocket;
197
+ restart_ws: (arg0?: any) => any;
198
+ increase_fails(): void;
199
+ send(...args: Parameters<typeof WebSocket.prototype.send>): Promise<void>;
200
+ constructor(url: string, protocols?: string | string[], options?: {
201
+ max_backoff_ms?: number;
202
+ });
203
+ }
204
+ export class DepictAPIWS extends AutoReconnectingWS {
205
+ #private;
206
+ ensure_sent(payload: {
207
+ id: string;
208
+ event?: depict_body;
209
+ [key: string]: any;
210
+ }): Promise<any[]>;
211
+ constructor(...params: [url: ConstructorParameters<typeof AutoReconnectingWS>[0], protocols?: ConstructorParameters<typeof AutoReconnectingWS>[1], options?: ConstructorParameters<typeof AutoReconnectingWS>[2] & Partial<{
212
+ initial_retry_ms: number;
213
+ }>]);
214
+ }
215
+ /**
216
+ * Returns a random string
217
+ * @return A random string, containing a-z, 0-9 and occasionally a dot (`.`)
218
+ */
219
+ export function random_string(): string;
220
+ export function make_random_classname(): string;
221
+ export const base_url: string;
222
+ export type event_types = "page_view" | "click" | "add_to_cart" | "purchase" | "element_visible";
223
+ declare const allowed_keys: readonly ["tenant", "market", "type", "user_id", "session_id", "product_id", "entity_identifiers", "url", "entity_price", "currency", "document_referrer", "document_width", "attribution_id", "recommendation_id", "click_location", "ab_test_group", "variant_ids", "dsid", "transaction_id", "error_type", "detail", "recommendation_type", "search_result_id", "product_listing_result_id"];
224
+ export type depict_body = Partial<{ [K in (typeof allowed_keys)[number]]: any }>;
225
+ export type depict_payload = depict_body[];
226
+ type any_properties = {
227
+ [key: string]: any;
228
+ };
229
+ export type noisy_depict_payload = (depict_body & any_properties)[];
230
+ export const filter_depict_payload: (payload: noisy_depict_payload) => depict_payload | undefined;
231
+ export const send_websocket: (bodies: depict_payload) => Promise<void | undefined>;
232
+ export const send_depict_unfiltered: (payload: depict_payload, use_ws?: any) => boolean | Promise<void | undefined> | undefined;
233
+ export const foolproof_send_beacon: (url: string, payload: {
234
+ [key: string]: any;
235
+ }) => boolean | undefined;
236
+ export const send_depict: (payload: noisy_depict_payload, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
237
+ export let get_depict_id: () => string;
238
+ export let get_user_id: () => string;
239
+ export let get_session_id: () => string | undefined;
240
+ export const set_depict_id_fn: (newfn: () => string) => (() => string) | undefined;
241
+ export const set_user_id_fn: (newfn: () => string) => (() => string) | undefined;
242
+ export const set_session_id_fn: (newfn: () => string) => (() => string) | undefined;
243
+ export type TrackingEventContextData = {
244
+ user_id: string;
245
+ dsid: string;
246
+ session_id?: string;
247
+ url: string;
248
+ document_width: number;
249
+ document_referrer: string;
250
+ };
251
+ export const get_tracking_event_context_data: () => TrackingEventContextData;
252
+ /**
253
+ * Sends a depict tracking event with prefilled data
254
+ */
255
+ export const depict_prefilled: (vars: Partial<{
256
+ type: any;
257
+ detail: any;
258
+ url: any;
259
+ currency: any;
260
+ tenant: any;
261
+ market: any;
262
+ user_id: any;
263
+ session_id: any;
264
+ product_id: any;
265
+ entity_identifiers: any;
266
+ entity_price: any;
267
+ document_referrer: any;
268
+ document_width: any;
269
+ attribution_id: any;
270
+ recommendation_id: any;
271
+ click_location: any;
272
+ ab_test_group: any;
273
+ variant_ids: any;
274
+ dsid: any;
275
+ transaction_id: any;
276
+ error_type: any;
277
+ recommendation_type: any;
278
+ search_result_id: any;
279
+ product_listing_result_id: any;
280
+ }> & {
281
+ [key: string]: any;
282
+ }, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
283
+ export const depict_click: (vars: Partial<{
284
+ type: any;
285
+ detail: any;
286
+ url: any;
287
+ currency: any;
288
+ tenant: any;
289
+ market: any;
290
+ user_id: any;
291
+ session_id: any;
292
+ product_id: any;
293
+ entity_identifiers: any;
294
+ entity_price: any;
295
+ document_referrer: any;
296
+ document_width: any;
297
+ attribution_id: any;
298
+ recommendation_id: any;
299
+ click_location: any;
300
+ ab_test_group: any;
301
+ variant_ids: any;
302
+ dsid: any;
303
+ transaction_id: any;
304
+ error_type: any;
305
+ recommendation_type: any;
306
+ search_result_id: any;
307
+ product_listing_result_id: any;
308
+ }> & {
309
+ [key: string]: any;
310
+ }) => boolean | Promise<void | undefined> | undefined;
311
+ export const depict_add_to_cart: (vars: Partial<{
312
+ type: any;
313
+ detail: any;
314
+ url: any;
315
+ currency: any;
316
+ tenant: any;
317
+ market: any;
318
+ user_id: any;
319
+ session_id: any;
320
+ product_id: any;
321
+ entity_identifiers: any;
322
+ entity_price: any;
323
+ document_referrer: any;
324
+ document_width: any;
325
+ attribution_id: any;
326
+ recommendation_id: any;
327
+ click_location: any;
328
+ ab_test_group: any;
329
+ variant_ids: any;
330
+ dsid: any;
331
+ transaction_id: any;
332
+ error_type: any;
333
+ recommendation_type: any;
334
+ search_result_id: any;
335
+ product_listing_result_id: any;
336
+ }> & {
337
+ [key: string]: any;
338
+ }) => boolean | Promise<void | undefined> | undefined;
339
+ export type ConsentObj = {
340
+ marketing: boolean;
341
+ necessary: boolean;
342
+ preferences: boolean;
343
+ statistics: boolean;
344
+ };
345
+ export function get_cookie(cookie_name: string): string | undefined;
346
+ export function Promise_Any<T>(promises: (T | PromiseLike<T>)[] | Iterable<T | PromiseLike<T>>): Promise<T>;
347
+ /**
348
+ * Broadcasts the product id of the current page to a BroadcastChannel `right_click_attribution`.
349
+ * This enables a page in another tab where right-clicking on a recommendation yielded to the opening of this page to send click tracking events.
350
+ */
351
+ export function broadcast_product_id(product_id: string): Promise<void>;
352
+ /**
353
+ * This function is a post processor for recommendation renderer which adds a "new tab listener" to the recommendations. That means that it will listen for right-and wheel clicks on the elements and if a tab opens (=broadcasts the product id) of the clicked product it emulates a click event (using contextmenu_callback)
354
+ * @param elements Elements that event listeners will be added on
355
+ * @param display The display to take the product_id from
356
+ * @param info InfoForProcessing to get Tenant instance out of
357
+ * @return `elements` 1:1
358
+ */
359
+ export function add_new_tab_listener(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info?: any, get_event_listener_remover?: (remover: VoidFunction) => void): NodeListOf<ChildNode> | Node_Array;
360
+ /**
361
+ * This is the event handler for the new tab tracking function (add_new_tab_listener)
362
+ * @param e Click event
363
+ * @param product_id product_id of clicked product
364
+ * @return A promise resolving to void after 60s or when the product id was broadcasted
365
+ */
366
+ export function contextmenu_callback(e: Event, product_id: string): Promise<void>;
367
+ /**
368
+ * Make parts of a type optional
369
+ *
370
+ * From: https://github.com/Microsoft/TypeScript/issues/25760#issuecomment-614417742
371
+ */
372
+ type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>;
373
+ export class ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
374
+ constructor(opts: {
375
+ element_: ElemType;
376
+ selector_: SelectorType;
377
+ disconnector_: Disconnector;
378
+ mutation_record_?: MutationRecord;
379
+ event_?: ListenerNames;
380
+ });
381
+ }
382
+ export interface ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
383
+ element: ElemType;
384
+ selector: SelectorType;
385
+ disconnector: Disconnector;
386
+ mutation_record?: MutationRecord;
387
+ event?: ListenerNames;
388
+ }
389
+ /**
390
+ * Element.querySelectorAll is broken in Chrome 37-latest, use this instead.
391
+ * Related bug: https://bugs.chromium.org/p/chromium/issues/detail?id=1286047
392
+ * @param element Quite broadly anything you'd normaly call querySelectorAll on, including "null"
393
+ * @param selector The selector to search for
394
+ * @return Stock return value
395
+ */
396
+ export function patched_querySelectorAll<T extends Element>(element: Element | Document | DocumentFragment | null, selector: string): NodeListOf<T> | T[] | undefined;
397
+ export interface ElementObserver {
398
+ /**
399
+ * Immediately calls the callback with an ElementObserverEvent for nodes existing in the DOM that match the provided selector OR are the selector,
400
+ * also calls the callback with an ElementObserverEvent whenever ANYTHING in the DOM occurs that makes an element match the provided selector.
401
+ * @param selector Selector string or element to listen for
402
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
403
+ */
404
+ onexists: EO_listener_also_taking_els;
405
+ /**
406
+ * Dispatches an ElementObserverEvent whenever a node is added to the DOM that matches the specified selector OR is the selector.
407
+ * @param selector CSS selector or element to observe
408
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
409
+ **/
410
+ oncreation: EO_listener_also_taking_els;
411
+ /**
412
+ * Dispatches an ElementObserverEvent whenever a node is removed from the DOM that matches the specified selector OR is the selector.
413
+ * @param selector CSS selector or element to observe
414
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
415
+ */
416
+ onremoved: EO_listener_also_taking_els;
417
+ /**
418
+ * Dispatches an ElementObserverEvent whenever a node that matches the specified selector or its children change in the DOM.
419
+ * @param selector CSS selector or element to observe
420
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
421
+ */
422
+ onchange: EO_listener;
423
+ /**
424
+ * Immediately calls the callback with an ElementObserverEvent on nodes that match the provided selector OR are the selector.
425
+ * @param selector Selector string or element to look for in the DOM
426
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
427
+ */
428
+ ifexists: EO_listener_also_taking_els;
429
+ /**
430
+ * See docs for observer.onexists. Will return a Promise that resolves to the element out of the first call of an observer.onexists callback.
431
+ * @param selector Selector string or element to wait for
432
+ * @param timeout timeout to stop listening and resolve the Promise with `undefined`
433
+ */
434
+ wait_for_element: <ElemType extends HTMLElement = HTMLElement>(selector: string | ElemType, timeout?: number) => Promise<ElemType>;
435
+ /**
436
+ * See docs for observer.on<listener>. Will return a Promise that resolves to the first element that matches the given listener and selector. I.e. `wait_for_listener("removed", ".old-recs");` will resolve to the first element matching `.old-recs` that is removed from the DOM
437
+ * @param listener one of the possible functions on ElementObserver that start with "on", without the "on". So "creation", "change", "exists" or "removed"
438
+ * @param selector String containing CSS selector
439
+ * @param timeout timeout to stop listening and resolve the Promise with `undefined`
440
+ */
441
+ wait_for_listener: <ElemType extends HTMLElement = HTMLElement, SelectorType = string | CallbackableNode>(listener: SelectorType extends CallbackableNode ? "creation" | "removed" : "exists" | "creation" | "removed" | "change", selector: SelectorType, timeout?: number) => Promise<ElemType>;
442
+ }
443
+ export class ElementObserver {
444
+ #private;
445
+ constructor(options?: {
446
+ territory?: HTMLElement | Document | DocumentFragment;
447
+ });
448
+ }
449
+ type EO_listener = <ElemType extends HTMLElement = HTMLElement>(selector: string, callback: ObserverCallbackFunction<ElemType>) => Disconnector;
450
+ type EO_listener_also_taking_els = <ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode>(selector: SelectorType, callback: ObserverCallbackFunction<ElemType, SelectorType>) => Disconnector;
451
+ type ListenerNames = "exists" | "creation" | "removed" | "change";
452
+ type ObserverCallbackFunction<ElemType extends CallbackableNode, SelectorType extends string | CallbackableNode = string | CallbackableNode> = (event: ElementObserverEvent<ElemType, SelectorType>) => any;
453
+ export type Disconnector = () => unknown;
454
+ type CallbackableNode = Element | Text | Comment;
455
+ /**
456
+ * Epic alien tech that categorizes DOM mutations, allowing one to listen and quickly (+2 ticks in the microtask queue, all before paint) react to DOM mutations such as elements (matching a selector) being added, deleted or changed.
457
+ */
458
+ export const observer: ElementObserver;
459
+ /**
460
+ * Useful for the `thresholds` option of IntersectionObserver - if you want to be notified at a 10% change, call this and set num_steps to 10. Pls see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/thresholds
461
+ * @param numSteps How many steps (notifications) there should be between 0 and 100% intersection
462
+ * @return Stuff to give to IntersectionObserver
463
+ */
464
+ export function buildThresholdList(numSteps: number): number[];
465
+ /**
466
+ * A Post processor for Recommendation renderer to add impression tracking to all displays
467
+ */
468
+ export const impression_tracking_post_processor: RR_PostProcessor<any>;
469
+ interface ImpressionTrackingOptions {
470
+ /** The element to observe for impressions. */
471
+ element: HTMLElement;
472
+ /** The impression data to send to the api (this is combined with context data) */
473
+ data: ExplicitImpressionEventData;
474
+ /** When true the element will be observed by the IntersectionObserver only after it's inserted into the DOM.
475
+ * Sometimes with a pollyfilled IntersectionObserver it ignores elements that are not in the DOM yet.
476
+ * Defaults to true.
477
+ * */
478
+ wait_for_dom_insertion?: boolean;
479
+ }
480
+ /**
481
+ * Registers the passed element for impression tracking.
482
+ * The element will be observed for intersection with the viewport.
483
+ * Also handles sending the impression event.
484
+ *
485
+ * @return A function to stop observing the element for impressions
486
+ */
487
+ export const impression_track_element: ({
488
+ element,
489
+ data,
490
+ wait_for_dom_insertion
491
+ }: ImpressionTrackingOptions) => () => void;
492
+ /** The start and end visibility threshold for an intersection to count as an impression */
493
+ export let impression_threshold: number[];
494
+ export const set_impression_threshold: (start: number, end: number) => number[];
495
+ /** The minimum duration the element has to be visible above the thresholds before it counts as an impression */
496
+ export const has_to_be_intersecting_for = 500;
497
+ /** What explicit information is needed to form an ImpressionEvent */
498
+ export type ExplicitImpressionEventData = {
499
+ recommendation_type?: string;
500
+ entity_price?: number;
501
+ market?: string;
502
+ tenant?: string;
503
+ product_id?: string;
504
+ } & ({
505
+ recommendation_id: string;
506
+ } | {
507
+ search_result_id: string;
508
+ } | {
509
+ product_listing_result_id: string;
510
+ } | {
511
+ suggestions_result_id: string;
512
+ });
513
+ /** What an impression event looks like when sent to the api */
514
+ export type ImpressionEvent = {
515
+ /** The type for impression events should be element_visible */
516
+ type: "element_visible";
517
+ } & (ExplicitImpressionEventData | TrackingEventContextData);
518
+ /**
519
+ * Sends an impression event to the api.
520
+ *
521
+ * Impression events always use websockets.
522
+ */
523
+ export const send_impression_event: (data: Optional<ImpressionEvent, "type">) => void;
524
+ /**
525
+ * Adds an event listener to a given element (example: recommendation link) which adds the provided product_id and recommendation_id to the 'depict' localStorage object
526
+ * @param {HTMLElement} a_element - The element to listen on the "click event"
527
+ * @param {string} product_id - A unique identifier for the product which can be used to rerecognize it on the product page
528
+ * @param {string} recommendation_id - The recommendation ID of the recommendation
529
+ * @param {Function} additional_listener - An additional function to execute onclick
530
+ */
531
+ export function bind_tracking_to_link(a_element: Element, product_id: string, recommendation_id: string, additional_listener?: Function): ((e: Event) => void) | undefined;
532
+ export type A2CTrackingFunction = (product_id: string, recommendation_id: string, was_unmatching: boolean, event: Event) => any;
533
+ /**
534
+ * Adds an event listener to a given element (example: the purchase button) which calls `tracking_fn(product_id,recommendation_id)` if the product_id exists in the 'depict' localStorage object
535
+ * @param {HTMLElement} button - The element to listen on the "click event"
536
+ * @param {Function} get_product_id - A function to get the product_id of the current page/the product associated with the add to cart button
537
+ * @param {A2CTrackingFunction} tracking_fn - A function which gets executed on click of button
538
+ * @param {Boolean} [unmatching_tracking] - also call tracking_fn on products not found in localStorage.
539
+ */
540
+ export function bind_to_a2c_button(button: Element, get_product_id: (url?: string, e?: Event) => string | Promise<string>, tracking_fn: A2CTrackingFunction, unmatching_tracking?: boolean, event?: string): Promise<void>;
541
+ type after_navig_fn = (arg0: Parameters<typeof history.replaceState | typeof history.pushState>, what_happened: "replaceState" | "pushState") => any;
542
+ /**
543
+ * AsyncIterable which resolves with the new href every time location.href changes
544
+ */
545
+ export const stateless_href_change_ipns: IPNS<string>;
546
+ /**
547
+ * AsyncIterable which resolves when you await it with the current href and then once every time it changes
548
+ */
549
+ export const href_change_ipns: IPNS<string>;
550
+ /**
551
+ * Functions to instantly (synchronously) call when a "popstate" event occurs, before the href_change_ipns' resolve
552
+ * This kind of bypasses the IPNS' point, and I'm sorry for that inconsistency, but I'm working on a feature that's not in the roadmap and am encountering issues due to the 1 tick delay of the IPNS. IPNS were a mistake, I'm sorry for them.
553
+ */
554
+ export const instant_exec_on_suspect_history_change: Set<(what_happened?: "replaceState" | "pushState" | "popstate", args?: PopStateEvent | Parameters<typeof history.replaceState> | Parameters<typeof history.pushState>) => void>;
555
+ export function on_next_navigation(callback: (new_href: string) => void): Promise<void>;
556
+ /**
557
+ * Proxies history.pushState, and, if the second argument is true, history.replaceState so that it executes the provided `after_navigation` function after the navigation (calling the original function) but before returning to what called it.
558
+ * Please also consider adding a listener to the `popstate` event (`window.addEventListener("popstate", handler)`) to cover ALL navigation possibilities.
559
+ * @param after_navigation Function to call after history.replaceState and history.pushState
560
+ * @param replace_replaceState=true Whether to call the function also on history.replaceState.
561
+ * @return Void
562
+ */
563
+ export function history_replacer(after_navigation: after_navig_fn, replace_replaceState?: boolean): Promise<void>;
564
+ interface TrackingData {
565
+ /** The active market, if any */
566
+ market?: string;
567
+ /** The merchant id */
568
+ tenant: string;
569
+ }
570
+ export interface PageViewEventData extends TrackingData {
571
+ /** If the page is a pdp, include the product_id */
572
+ product_id?: string;
573
+ }
574
+ export interface PageViewTrackingData extends TrackingData {
575
+ /** A function that returns the product_id of the product being displayed on href,
576
+ * if the href points to a PDP */
577
+ get_product_id: (href: string) => string | undefined | Promise<string | undefined>;
578
+ }
579
+ /**
580
+ * Sends a page_view event to Depict tracking if it hasn't been sent yet for the current page url
581
+ * It also broadcasts the current URL to a BroadcastChannel using the function `broadcast_url`, this is used for right click + open in new tab tracking
582
+ * @return A promise resolving to void
583
+ */
584
+ export function send_page_view_if_needed(data: PageViewEventData): Promise<void>;
585
+ /**
586
+ * Sends a page_view event to Depict tracking, and another one any time the page URL changes
587
+ */
588
+ export function send_page_view_on_navigation(data: PageViewTrackingData): Promise<void>;
589
+ export function make_tracker_send_to_depict(ga_tracker: any, append_to_url?: string): void;
590
+ export function create_ga_queue(): void;
591
+ /**
592
+ * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
593
+ * @return Current consent status, whether selected or not
594
+ */
595
+ export const cookiebot_get_consent: () => any;
596
+ /**
597
+ * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
598
+ * @return Consent status, once selected
599
+ */
600
+ export function cookiebot_wait_for_consent(): Promise<boolean>;
601
+ /**
602
+ * Returns an IPNS that resolves with initial consent when Cookiebot has loaded, or immediately if a consent cookie already exists.
603
+ * As well as a new consent object every time the consent status has changed
604
+ * @return An IPNS resolving to the consent object
605
+ */
606
+ export function cookiebot_get_cookie_ipns(): IPNS<ConsentObj>;
607
+ /**
608
+ * Anonymize Depict id until required consent level has been given through Cookiebot.
609
+ *
610
+ * This can be used for tenants using Cookiebot for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
611
+ * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
612
+ * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
613
+ *
614
+ * NOTE that this uses {@link set_depict_id_fn} to set {@link get_depict_id} and shouldn't be mixed with other uses of {@link set_depict_id_fn}.
615
+ */
616
+ export const init_cookiebot_tracking: (anon_id?: any) => Promise<void | undefined>;
617
+ declare global {
618
+ interface Window {
619
+ Cookiebot?: {
620
+ name: string;
621
+ consented: boolean;
622
+ declined: boolean;
623
+ changed: boolean;
624
+ hasResponse: boolean;
625
+ consentID: string;
626
+ consent: Consent;
627
+ isOutsideEU: boolean;
628
+ isOutOfRegion: boolean;
629
+ host: string;
630
+ domain: string;
631
+ currentPath: string;
632
+ doNotTrack: boolean;
633
+ consentLevel: string;
634
+ isRenewal: boolean;
635
+ forceShow: boolean;
636
+ dialog: null;
637
+ responseMode: string;
638
+ serial: string;
639
+ scriptId: string;
640
+ scriptElement: ScriptElement;
641
+ whitelist: any[];
642
+ cookieList: CookieList;
643
+ pathlist: any[];
644
+ userIsInPath: boolean;
645
+ cookieEnabled: boolean;
646
+ versionChecked: boolean;
647
+ versionRequested: boolean;
648
+ version: number;
649
+ latestVersion: number;
650
+ isNewVersion: boolean;
651
+ CDN: string;
652
+ source: string;
653
+ retryCounter: number;
654
+ frameRetryCounter: number;
655
+ bulkConsentFrameRetryCounter: number;
656
+ setOnloadFrameRetryCounter: number;
657
+ optOutLifetime: number;
658
+ consentLifetime: null;
659
+ framework: string;
660
+ hasFramework: boolean;
661
+ frameworkBlocked: boolean;
662
+ frameworkLoaded: boolean;
663
+ iframeReady: boolean;
664
+ iframe: Iframe;
665
+ bulkconsent: null;
666
+ bulkresetdomains: any[];
667
+ bulkconsentsubmitted: boolean;
668
+ isbulkrenewal: boolean;
669
+ wipe: Wipe;
670
+ consentUTC: Date;
671
+ IABConsentString: string;
672
+ GACMConsentString: string;
673
+ dataLayerName: string;
674
+ loaded: boolean;
675
+ autoblock: boolean;
676
+ mutationObserver: null;
677
+ mutationCounter: number;
678
+ mutationFallback: boolean;
679
+ mutationFallbackDocAttributes: any[];
680
+ mutationHandlerFallbackCharsetLoaded: boolean;
681
+ mutationAppName: string;
682
+ mutationEventListeners: any[];
683
+ mutationOnloadEventListeners: any[];
684
+ mutateEventListeners: boolean;
685
+ mutationHandlerFirstScript: null;
686
+ postPonedMutations: any[];
687
+ nonAsyncMutations: any[];
688
+ deferMutations: any[];
689
+ geoRegions: any[];
690
+ userCountry: string;
691
+ userCulture: string;
692
+ windowOnloadTriggered: boolean;
693
+ botDetectionDisabled: boolean;
694
+ regulations: Regulations;
695
+ regulationRegions: RegulationRegions;
696
+ commonTrackers: CommonTrackers;
697
+ configuration: Configuration;
698
+ inlineConfiguration: null;
699
+ processLinkClickCounter: number;
700
+ performanceEntriesCounter: number;
701
+ OverrideEventListenersOnloadFired: any[];
702
+ OverrideEventListenersOnloadToFire: any[];
703
+ fallbackScriptNodes: any[];
704
+ fallbackDeferNodes: any[];
705
+ };
706
+ }
707
+ }
708
+ export interface CommonTrackers {
709
+ domains: Domain[];
710
+ }
711
+ export interface Domain {
712
+ d: string;
713
+ c: number[];
714
+ }
715
+ export interface Configuration {
716
+ loaded: boolean;
717
+ loadRetry: number;
718
+ tags: any[];
719
+ trackingDomains: any[];
720
+ }
721
+ export interface Consent {
722
+ stamp: string;
723
+ necessary: boolean;
724
+ preferences: boolean;
725
+ statistics: boolean;
726
+ marketing: boolean;
727
+ }
728
+ export interface CookieList {
729
+ cookieTablePreference: any[];
730
+ cookieTableStatistics: any[];
731
+ cookieTableAdvertising: any[];
732
+ cookieTableUnclassified: any[];
733
+ }
734
+ export interface Iframe {
735
+ cookieconsentDataStyleDisplay: string;
736
+ mtjQuery171028673205955022363: number;
737
+ }
738
+ export interface RegulationRegions {
739
+ gdpr: string[];
740
+ ccpa: string[];
741
+ lgpd: string[];
742
+ }
743
+ export interface Regulations {
744
+ gdprApplies: boolean;
745
+ ccpaApplies: boolean;
746
+ lgpdApplies: boolean;
747
+ }
748
+ export interface ScriptElement {}
749
+ export interface Wipe {
750
+ preferences: boolean;
751
+ statistics: boolean;
752
+ marketing: boolean;
753
+ }
754
+ /**
755
+ * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
756
+ * @return Current consent status, whether selected or not
757
+ */
758
+ export const optanon_get_consent: () => any;
759
+ /**
760
+ * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
761
+ * @return Consent status
762
+ */
763
+ export function optanon_wait_for_consent(): Promise<boolean>;
764
+ /**
765
+ * Returns an IPNS that resolves with initial consent when Optanon has loaded, or immediately if a consent cookie already exists.
766
+ * As well as a new consent object every time the consent status has changed
767
+ * @return An IPNS resolving to the consent object
768
+ */
769
+ export function optanon_get_cookie_ipns(): IPNS<ConsentObj>;
770
+ /**
771
+ * Anonymize Depict id until required consent level has been given through OneTrust's Optanon.
772
+ *
773
+ * This can be used for tenants using OneTrust for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
774
+ * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
775
+ * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
776
+ *
777
+ * NOTE that this uses {@link set_depict_id_fn} to set {@link get_depict_id} and shouldn't be mixed with other uses of {@link set_depict_id_fn}.
778
+ */
779
+ export const init_optanon_tracking: (anon_id?: any) => Promise<void | undefined>;
780
+ export const load_gtag: (GA_ID: string, strict?: boolean | undefined) => Promise<void | undefined>;
781
+ export const setup_gtag: (GA_ID: string) => void | undefined;
782
+ export const gtag_view: <T extends Display>(raw_displays: T[], get_product_id: (url?: string | T | undefined) => string | Promise<string>, more?: {
783
+ [key: string]: any;
784
+ list_name?: string | undefined;
785
+ } | ((display: T) => {
786
+ [key: string]: any;
787
+ }) | undefined) => Promise<void | undefined>;
788
+ export const gtag_click: (product_id: string | number, index: number, more?: object | undefined) => Promise<any>;
789
+ export const send_ga: (action: string) => any;
790
+ export const setup_ga: (GAID: string) => void | undefined;
791
+ export const ga_rec_click: () => any;
792
+ export const ga_purchase_click: () => any;
793
+ export const insert_styling: (css: string) => Promise<void | undefined>;
794
+ /**
795
+ * A function meant to use to track the main add to cart button on the product page of an integration.
796
+ * * @param tenant instance of `Tenant` class
797
+ * @param selector The selector to use to find the button
798
+ * @param validator A function that can invalidate the click event before tracking is sent
799
+ * @return A `Disconnector` to stop looking for more add to cart buttons to track
800
+ */
801
+ export const track_a2c: (tenant: Tenant, selector: string, validator?: ((e: Event) => boolean) | undefined) => Disconnector;
802
+ /**
803
+ * Basically a RecRendererResult with less strict typing
804
+ */
805
+ export interface Surface<T extends Display> {
806
+ elements?: Node_Array;
807
+ displays?: T[];
808
+ should_stay_inserted?: Promise<boolean>;
809
+ }
810
+ /**
811
+ * Functions existing on ChildNode that are commonly used to insert recommendations into the DOM
812
+ */
813
+ export type InsertionVerb = "after" | "before" | "replaceWith" | "append" | "prepend" | "replaceChildren";
814
+ /**
815
+ * Tries to extract a product id from an url.
816
+ * The method used to retrive product id used here is very narrow, probably better to use something else instead?
817
+ *
818
+ * @example normal_get_product_id("www.foo.com/bar/baz.html") // "baz"
819
+ *
820
+ * @param url The url to check, defaults to `window.location`
821
+ * @returns
822
+ */
823
+ export const normal_get_product_id: (url?: string) => string;
824
+ declare global {
825
+ interface Document {
826
+ depictwashere: boolean;
827
+ }
828
+ }
829
+ /**
830
+ * If you need custom market logic that {@link depict_init_with_market_logic} doesn't support then use this function.
831
+ *
832
+ * Used to initialize an integration-script, this should always be the entrypoint of an integration.
833
+ *
834
+ * Makes sure that your script doesn't run twice
835
+ */
836
+ export const depict_init: (callback: () => Promise<void>) => void;
837
+ /**
838
+ * Initialize an integration-script like {@link depict_init}, but with automatic handling of unsupported and unknown markets.
839
+ *
840
+ * @param options.extract_market A function that extracts the current market, and if the market is supported, unsupported or unknown
841
+ * @param options.callback If `extract_market` returned a supported market, calls `depict_init` with this callback.
842
+ * @param options.supported_markets Markets where our script should run, in order to get the best typechecking you should add a `as const`
843
+ * modifier to this type like so `["foo", "bar"] as const`.
844
+ * @param options.unsupported_markets Markets we are aware of and where our script shouldn't run.
845
+ * @param options.preferred_demo_market Market to use on .demo.depict.ai, if an override is needed for all users.
846
+ * depict-override-market query parameter will override this behaviour.
847
+ *
848
+ * ### Behaviour
849
+ *
850
+ * - market is unsupported - log to console and exit
851
+ * - market is unknown - report to sentry and exit
852
+ *
853
+ * ### Override market
854
+ *
855
+ * When running in debug mode the market can be overridden by setting a `depict-override-market` query param.
856
+ * For example http://tenant.domain?depict-override-market=ez
857
+ */
858
+ export function depict_init_with_market_logic<T extends readonly string[]>(callback: (market: T[number]) => Promise<void>, get_market: () => Promise<string | undefined> | string | undefined, supported_markets: T, unsupported_markets: string[], preferred_demo_market?: string): void;
859
+ type IdType = string | undefined | Promise<string | undefined>;
860
+ export interface Tenant<ProductId extends IdType> {
861
+ TENANT: string;
862
+ tenant: string;
863
+ MARKET: TwoLetterMarket;
864
+ market: TwoLetterMarket;
865
+ TYPE: string;
866
+ type: string;
867
+ GA_ID: string;
868
+ gaid: string;
869
+ get_product_id: (url?: string) => ProductId extends string | undefined ? string : Promise<string>;
870
+ product_id: (url?: string) => string | Promise<string>;
871
+ dataset: DOMStringMap;
872
+ modify: boolean;
873
+ is_debug: boolean;
874
+ debug: boolean;
875
+ dlog: typeof dlog;
876
+ Sentry: typeof Sentry;
877
+ catchify: typeof catchify;
878
+ err: (...errors: any[]) => undefined;
879
+ }
880
+ /**
881
+ * Tenant class. This describes which site/customer one is on, in which market, and some more information. It also sends the page_view event if not already done and highlights elements with a `.depict` class if `localStorage['highlight-depict']` is `"true"`
882
+ * @param options A object with constructor options
883
+ */
884
+ export class Tenant<ProductId extends IdType = IdType> {
885
+ constructor(options: {
886
+ TENANT?: string;
887
+ TYPE?: string;
888
+ MARKET: TwoLetterMarket;
889
+ GA_ID: string;
890
+ get_product_id: (url?: string) => ProductId;
891
+ current_script_override?: HTMLScriptElement;
892
+ pageview_tracking?: boolean;
893
+ });
894
+ }
895
+ /**
896
+ * This is a list of alpha-2 country codes plus some two letter combinations commonly used to describe markets
897
+ */
898
+ export type TwoLetterMarket = "af" | "al" | "dz" | "as" | "ad" | "ao" | "ai" | "aq" | "ag" | "ar" | "am" | "aw" | "au" | "at" | "az" | "bs" | "bh" | "bd" | "bb" | "by" | "be" | "bz" | "bj" | "bm" | "bt" | "bo" | "bq" | "ba" | "bw" | "bv" | "br" | "io" | "bn" | "bg" | "bf" | "bi" | "cv" | "kh" | "cm" | "ca" | "ky" | "cf" | "td" | "cl" | "cn" | "cx" | "cc" | "co" | "km" | "cd" | "cg" | "ck" | "cr" | "hr" | "cu" | "cw" | "cy" | "cz" | "ci" | "dk" | "dj" | "dm" | "do" | "ec" | "eg" | "sv" | "gq" | "er" | "ee" | "sz" | "et" | "fk" | "fo" | "fj" | "fi" | "fr" | "gf" | "pf" | "tf" | "ga" | "gm" | "ge" | "de" | "gh" | "gi" | "gr" | "gl" | "gd" | "gp" | "gu" | "gt" | "gg" | "gn" | "gw" | "gy" | "ht" | "hm" | "va" | "hn" | "hk" | "hu" | "is" | "in" | "id" | "ir" | "iq" | "ie" | "im" | "il" | "it" | "jm" | "jp" | "je" | "jo" | "kz" | "ke" | "ki" | "kp" | "kr" | "kw" | "kg" | "la" | "lv" | "lb" | "ls" | "lr" | "ly" | "li" | "lt" | "lu" | "mo" | "mg" | "mw" | "my" | "mv" | "ml" | "mt" | "mh" | "mq" | "mr" | "mu" | "yt" | "mx" | "fm" | "md" | "mc" | "mn" | "me" | "ms" | "ma" | "mz" | "mm" | "na" | "nr" | "np" | "nl" | "nc" | "nz" | "ni" | "ne" | "ng" | "nu" | "nf" | "mp" | "no" | "om" | "pk" | "pw" | "ps" | "pa" | "pg" | "py" | "pe" | "ph" | "pn" | "pl" | "pt" | "pr" | "qa" | "mk" | "ro" | "ru" | "rw" | "re" | "bl" | "sh" | "kn" | "lc" | "mf" | "pm" | "vc" | "ws" | "sm" | "st" | "sa" | "sn" | "rs" | "sc" | "sl" | "sg" | "sx" | "sk" | "si" | "sb" | "so" | "za" | "gs" | "ss" | "es" | "lk" | "sd" | "sr" | "sj" | "se" | "ch" | "sy" | "tw" | "tj" | "tz" | "th" | "tl" | "tg" | "tk" | "to" | "tt" | "tn" | "tr" | "tm" | "tc" | "tv" | "ug" | "ua" | "ae" | "gb" | "um" | "us" | "uy" | "uz" | "vu" | "ve" | "vn" | "vg" | "vi" | "wf" | "eh" | "ye" | "zm" | "zw" | "ax" | "uk" | "en" | "da" | "eu" | "sv" | "oc" | "nb" | "sq";
899
+ type ImpressionTrackOptions = {
900
+ t?: Tenant;
901
+ impression_tracking?: false;
902
+ } | {
903
+ impression_tracking: true;
904
+ t: Tenant;
905
+ };
906
+ type TenantSpecificationOptions = {
907
+ t?: Tenant;
908
+ tenant: string;
909
+ market: string;
910
+ get_product_id: (url?: string) => string | Promise<string>;
911
+ } | {
912
+ t: Tenant;
913
+ tenant?: string;
914
+ market?: string;
915
+ get_product_id?: (url?: string) => string | Promise<string>;
916
+ };
917
+ type ElementDiscoveryOptions = {
918
+ product_selector: string;
919
+ product_elements?: null | void | undefined;
920
+ } | {
921
+ product_selector?: null | void | undefined;
922
+ product_elements: HTMLElement[];
923
+ };
924
+ type A2CButtonDiscoveryOptions = {
925
+ a2c_selector: string;
926
+ a2c_elements?: null | void | undefined;
927
+ } | {
928
+ a2c_selector?: null | void | undefined;
929
+ a2c_elements: HTMLElement[];
930
+ };
931
+ /**
932
+ * @deprecated Please use DPC instead.
933
+ * Does not support ModernDisplays.
934
+ */
935
+ export const AIO: (options: {
936
+ attempt_gtag_view_tracking?: boolean | undefined;
937
+ no_gtag?: boolean | undefined;
938
+ shade?: boolean | undefined;
939
+ always_track_a2c?: boolean | undefined;
940
+ get_rec_id?: ((elem: HTMLElement) => string | undefined) | undefined;
941
+ get_prod_id?: ((elem: HTMLElement) => (string | undefined) | Promise<string | undefined>) | undefined;
942
+ get_ga_prod_id?: ((elem: HTMLElement) => string | undefined | Promise<string | undefined>) | undefined;
943
+ click_location_prefix?: ((elem: HTMLElement) => string | undefined) | undefined;
944
+ rec_a2c_selector?: string | undefined;
945
+ rec_a2c_unbubbled?: boolean | undefined;
946
+ get_display?: ((elem: HTMLElement) => Partial<LegacyDisplay> | undefined) | undefined;
947
+ } & ImpressionTrackOptions & TenantSpecificationOptions & ElementDiscoveryOptions & A2CButtonDiscoveryOptions, gtag_options?: {
948
+ [key: string]: any;
949
+ list_name?: string | undefined;
950
+ } | undefined) => Promise<{
951
+ add_a2c_element: (element: HTMLElement) => void;
952
+ add_product_element: (element: HTMLElement) => Promise<void | undefined>;
953
+ } | undefined>;
954
+ export const paint_red: (element: HTMLElement) => void | undefined;
955
+ /**
956
+ * A function that attempts to "serialize" an object to a text representation that helps with debugging when using sentry
957
+ * @param anything Something to try to serialize - this function is crappy and your mileage may vary
958
+ * @param depth How deep to go when recursing
959
+ * @return An object that is somehow closer to text (better serializable by sentry) or text
960
+ */
961
+ export function serialize_object(anything: Object, depth?: number): Object;
962
+ export const wait: (delay: number) => Promise<unknown>;
963
+ /**
964
+ * Fetch with retry and exponetial back off. This is the 2.0 version of the previous Windows proof fetch.
965
+ *
966
+ * Windows proof fetch is a utility which retries fetch requests 10 times when they fail. Reason for this is a certain windows 10 build where the network stack randomly breaks 20% of https connections
967
+ * @param url Url to perform fetch towards
968
+ * @param options Fetch options
969
+ * @param max_retries Max number of retries, defaults to 10
970
+ * @returns The fetch response
971
+ */
972
+ export function fetch_retry(url: RequestInfo, options?: RequestInit, max_retries?: number): Promise<false | Response>;
973
+ type PossibleEndpoint = "general" | "product" | "products" | "category";
974
+ type ExclusiveId = {
975
+ category_id: string;
976
+ product_id?: undefined;
977
+ product_ids?: undefined;
978
+ } | {
979
+ category_id?: undefined;
980
+ product_id: string;
981
+ product_ids?: undefined;
982
+ } | {
983
+ category_id?: undefined;
984
+ product_id?: undefined;
985
+ product_ids: string[];
986
+ } | {
987
+ category_id?: undefined;
988
+ product_id?: undefined;
989
+ product_ids?: undefined;
990
+ };
991
+ type FetchRecsOptions = {
992
+ type: string;
993
+ user_id?: string;
994
+ session_id?: string;
995
+ } & ExclusiveId;
996
+ /**
997
+ * Fetches recommendations from the depict v2 recommendation api.
998
+ * Will select the endpoint after which id property is given.
999
+ *
1000
+ * API Docs: https://api.depict.ai/docs
1001
+ *
1002
+ * Formerly called get_displays
1003
+ */
1004
+ export function fetch_recs<T extends Display = Display>(t: Tenant | {
1005
+ market: string;
1006
+ tenant: string;
1007
+ }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<T[]>;
1008
+ export function fetch_recs_whole_response<R extends {
1009
+ displays: any[];
1010
+ }>(t: Tenant | {
1011
+ market: string;
1012
+ tenant: string;
1013
+ }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<R>;
1014
+ declare function default_get_fetch_url(type: PossibleEndpoint): string;
1015
+ export function ensure_parameter_in_url(url: any, param: any, value: any): string;
1016
+ export function querySelectorUpwards(element: Element | HTMLElement, selector: string): Element | null;
1017
+ export function html2elems(html: string): NodeListOf<ChildNode>;
1018
+ export function html2elem(html: string): Element | null;
1019
+ /** On demo domain: make all urls relative */
1020
+ export function relativify(url: string | RegExp, also_onchange?: boolean, override_dev_url?: string, stfu?: boolean, also_in_all_shadow_roots?: boolean): void;
1021
+ export function querySelectorAllElements<T extends Element>(elements: Node_Iterable, selector: string): T[];
1022
+ export function standard_price_format(price: number, places_after_comma?: number | "auto", decimal_delimiter?: string, thousands_delimiter?: string): string;
1023
+ export function intl_number_format_with_fallback(bcp47_country_code: string, number: number, numberformat_options?: Parameters<typeof Intl.NumberFormat>[1]): string;
1024
+ export function ensure_object_path(obj: object, step1: string, ...path: string[]): any;
1025
+ export function Rec_Renderer<T extends Display>(t: Tenant | null, rendering_options: RR_Options<T>): Promise<RecRendererResult<T>>;
1026
+ export function regex_templating(template: string, display?: Display | {
1027
+ [key: string]: any;
1028
+ }): string;
1029
+ export function clone_deep<T>(obj: T): T;
1030
+ export class InfoForProcessing<T extends Display> {
1031
+ constructor(t: Tenant | null, rendering_options: RR_Options<T>, displays: T[], index?: number, remove_display?: () => void, event_listeners?: [type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions][]);
1032
+ }
1033
+ type RegisterEventListener = (type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions) => void;
1034
+ export interface InfoForProcessing<T extends Display> {
1035
+ t: Tenant;
1036
+ rendering_options: RR_Options<T>;
1037
+ displays: T[];
1038
+ index: number;
1039
+ remove_display?: () => void;
1040
+ register_event_listener: RegisterEventListener;
1041
+ event_listeners?: [type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions][];
1042
+ extras?: {
1043
+ [key: string]: any;
1044
+ };
1045
+ }
1046
+ export type RR_PreProcessor<T extends Display> = (display: T, info: InfoForProcessing<T>) => Promise<T> | T;
1047
+ export type RR_PostProcessor<T extends Display> = (elements: NodeListOf<ChildNode> | Node_Array, display: T, info: InfoForProcessing<T>) => Promise<NodeListOf<ChildNode> | Node_Array> | NodeListOf<ChildNode> | Node_Array;
1048
+ export type RR_Options<T extends Display> = {
1049
+ template: string | ((arg0: T, info: InfoForProcessing<T>) => Promise<string | Node_Array> | string | Node_Array);
1050
+ recs?: T[] | undefined | Promise<T[] | undefined>;
1051
+ type: string;
1052
+ min_items_to_report?: number;
1053
+ min_items_to_run?: number;
1054
+ max_items?: number;
1055
+ extra_api_options?: {
1056
+ [key: string]: any;
1057
+ };
1058
+ pre_processors?: RR_PreProcessor<T>[];
1059
+ post_processors?: RR_PostProcessor<T>[];
1060
+ headers?: HeadersInit;
1061
+ } & FetchRecsOptions;
1062
+ /**
1063
+ * Product properties that are used to render the product cards. Used until early 2023
1064
+ */
1065
+ export interface LegacyDisplay {
1066
+ /**
1067
+ * The URL of the product page.
1068
+ */
1069
+ page_url: any;
1070
+ /**
1071
+ * The URL of the product image.
1072
+ */
1073
+ image_url: string;
1074
+ /** The price of the product. */
1075
+ sale_price: number;
1076
+ /** The original price of the product. */
1077
+ original_price: number;
1078
+ /** The product ID of the product. */
1079
+ product_id: string;
1080
+ /** The Google Analytics product ID */
1081
+ ga_product_id?: string;
1082
+ /** The Google Analytics product IDs */
1083
+ ga_product_ids?: string[];
1084
+ /** The variation IDs */
1085
+ variant_ids?: string[];
1086
+ /** The title */
1087
+ title: string;
1088
+ /** Unique recommendation result ID used by Depict */
1089
+ recommendation_id?: string;
1090
+ /** Unique search result ID used by Depict */
1091
+ search_result_id?: string;
1092
+ /** Unique product listing result ID used by Depict */
1093
+ product_listing_result_id?: string;
1094
+ [key: string]: any;
1095
+ }
1096
+ interface ModernDisplay {
1097
+ /**
1098
+ * The index of the variant to be displayed.
1099
+ */
1100
+ variant_index: number;
1101
+ /**
1102
+ * All variant displays (eg. different colors, sizes) of the product.
1103
+ */
1104
+ variant_displays: any[];
1105
+ /** SKUs of the different variants */
1106
+ variant_skus: string[];
1107
+ /** Product of the different variants */
1108
+ variant_product_ids: string[];
1109
+ /** Unique recommendation result ID used by Depict */
1110
+ recommendation_id?: string;
1111
+ /** Unique search result ID used by Depict */
1112
+ search_result_id?: string;
1113
+ /** Unique product listing result ID used by Depict */
1114
+ product_listing_result_id?: string;
1115
+ /** Recommendation type logic used by Depict */
1116
+ logic?: string;
1117
+ }
1118
+ interface BasicDisplay {
1119
+ product_id: string;
1120
+ /** Unique recommendation result ID used by Depict */
1121
+ recommendation_id?: string;
1122
+ /** Unique search result ID used by Depict */
1123
+ search_result_id?: string;
1124
+ /** Unique product listing result ID used by Depict */
1125
+ product_listing_result_id?: string;
1126
+ /** Recommendation type logic used by Depict */
1127
+ logic?: string;
1128
+ [key: string]: any;
1129
+ }
1130
+ export type Display = LegacyDisplay | ModernDisplay | BasicDisplay;
1131
+ export type Node_Iterable = HTMLCollection | NodeListOf<ChildNode> | Node_Array;
1132
+ export type Node_Array = (Element | Text | Comment)[];
1133
+ export type RecRendererResult<T extends Display> = Record<string, never> | {
1134
+ elements: Node_Array;
1135
+ displays: T[];
1136
+ };
1137
+ /**
1138
+ * Queues a task in the event queue without a timeout like setTimeout does, see https://www.youtube.com/watch?v=cCOL7MC4Pl0
1139
+ * @param callback callback function that gets queued as a task
1140
+ */
1141
+ export function queueMacroTask(callback: VoidFunction): void;
1142
+ interface SDKRenderingInfo {
1143
+ set_on_index_change: (fn: (index: number) => void) => void;
1144
+ merchant: string;
1145
+ market: string;
1146
+ }
1147
+ /**
1148
+ * Creates a handler for sending the "recommendations_inserted" event on new results.
1149
+ * Usage: call make_plp_recommendations_inserted_handler with options and then call the returned functions in your productCardTemplate
1150
+ */
1151
+ export function make_plp_recommendations_inserted_handler(tenant: string, market: string, type: "search" | "category"): <T extends Display>(display: T | null, info?: SDKRenderingInfo) => void;
1152
+ /**
1153
+ * @deprecated this was a stupid idea, it's much easier to read if one just does a quick arrow function that provides the wanted arguments
1154
+ */
1155
+ export function cache_args(fn: any, ...args: any[]): (...unimportant_args: any[]) => any;
1156
+ export const check_displays: (args_0: {
1157
+ recs: Display[] | {
1158
+ displays: Display[];
1159
+ } | Promise<Display[] | {
1160
+ displays: Display[];
1161
+ }>;
1162
+ min_recs?: number | undefined;
1163
+ market: string;
1164
+ type: string;
1165
+ product_id: string | string[] | Promise<string> | Promise<string[]> | ((arg0?: string) => string | string[] | Promise<string> | Promise<string[]>) | undefined;
1166
+ tenant: string;
1167
+ }) => Promise<boolean | undefined>;
1168
+ /**
1169
+ * @deprecated You should no longer need to use this. Use observer.onexists to add an event listener to an element once it exists.
1170
+ */
1171
+ export function require_event_listener(element: Node, event: string, track_id: any, func: EventListenerOrEventListenerObject): void;
1172
+ export const default_view_tracking: (RR_PostProcessor<any> | typeof depict_page_view)[];
1173
+ export const default_click_tracking: (typeof depict_click_tracking_post_processor | typeof add_new_tab_listener)[];
1174
+ export function recs_inserted_tracking<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1175
+ export function gtag_view_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1176
+ export function depict_page_view<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1177
+ export function gtag_click_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1178
+ export function depict_click_tracking_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1179
+ export function add_to_localstorage<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1180
+ export function ga_click<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1181
+ export const should_colorizeLogics: boolean;
1182
+ export function colorize_elements(elements: NodeListOf<ChildNode> | Node_Array, display: Display): NodeListOf<ChildNode> | Node_Array;
1183
+ type Extended_RR_Options<T extends Display> = {
1184
+ view_tracking?: RR_PostProcessor<T>[];
1185
+ click_tracking?: RR_PostProcessor<T>[];
1186
+ } & RR_Options<T>;
1187
+ export function default_rr<T extends Display>(t: Tenant | null, rendering_options: Extended_RR_Options<T>): Promise<RecRendererResult<T>>;
1188
+ type GWVM_Options = {
1189
+ container_selector?: string;
1190
+ start_rows?: number;
1191
+ rows_per_click?: number;
1192
+ recs_per_row?: number | ((showing: number) => number);
1193
+ button?: string | HTMLElement;
1194
+ override_rec_renderer?: typeof Rec_Renderer;
1195
+ title_selector?: string;
1196
+ title?: string | HTMLElement;
1197
+ container_template: string | Node_Array;
1198
+ only_full_rows?: boolean;
1199
+ should_preload?: boolean;
1200
+ };
1201
+ interface GWVM_InfoForProcessing<T extends Display> extends InfoForProcessing<T> {
1202
+ extras: {
1203
+ [key: string]: any;
1204
+ load_more_currently_showing: number;
1205
+ load_more: (num?: number | Event) => void;
1206
+ load_more_ipo: {
1207
+ promise: Promise<number>;
1208
+ resolve: (argument?: number) => void;
1209
+ };
1210
+ };
1211
+ }
1212
+ type GWVM_RR_Post_Pro = (elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: GWVM_InfoForProcessing) => Promise<NodeListOf<ChildNode> | Node_Array> | NodeListOf<ChildNode> | Node_Array;
1213
+ type GWVM_RR_Options = Extended_RR_Options & {
1214
+ post_processors?: GWVM_RR_Post_Pro[];
1215
+ };
1216
+ /**
1217
+ * @deprecated please use RecommendationGrid instead
1218
+ */
1219
+ export function GWVM_Renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: GWVM_Options): Promise<{
1220
+ elements?: ChildNode[] | undefined;
1221
+ load_more?: ((num?: number | Event) => void) | undefined;
1222
+ displays?: Display[] | undefined;
1223
+ }>;
1224
+ /**
1225
+ * Used auto generate recommendations with view more button.
1226
+ * @param t The tenant used for recommendations
1227
+ * @param options Rendering options for recommendations such as total number of recommendations and template.
1228
+ * `GWVM_RR_Options` extends the same typing used for options in `default_rr and` `recommendation-renderer`
1229
+ * @param GWVM_opts Grid options, starting row, rows per view more click, container templates
1230
+ * @param rec_selector The selector used to find the rendered recs (by recommendation renderer
1231
+ * for which the first options object was used) for the width calculation. Default: ".rec_outer".
1232
+ * @deprecated please use RecommendationGrid instead
1233
+ */
1234
+ export function Auto_GWVM(t: Tenant, options: GWVM_RR_Options, GWVM_opts: Omit<GWVM_Options, "recs_per_row">, {
1235
+ rec_selector
1236
+ }?: {
1237
+ rec_selector?: string;
1238
+ }): Promise<{
1239
+ elements?: Node_Array | undefined;
1240
+ load_more?: ((num?: number | Event) => void) | undefined;
1241
+ displays?: Display[] | undefined;
1242
+ }>;
1243
+ /**
1244
+ * @deprecated use async_iterable_ipns instead. This can skip values which yields unexpected results.
1245
+ */
1246
+ export function infinite_promise_creator(): {
1247
+ promise: Promise<unknown>;
1248
+ internal_resolve: ((value: any) => void) | undefined;
1249
+ resolve: (argument?: any) => void;
1250
+ };
1251
+ interface trimmed_GWVM_opts extends Omit<GWVM_Options, "start_rows" | "rows_per_click" | "recs_per_row"> {}
1252
+ /**
1253
+ * @deprecated please rewrite this, basing on RecommendationGrid and its `rows.ipns` option, next time you need infinite scroll
1254
+ */
1255
+ export function infinite_renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: trimmed_GWVM_opts, {
1256
+ rec_selector
1257
+ }?: {
1258
+ rec_selector?: string;
1259
+ }): Promise<{
1260
+ elements?: Node_Array | undefined;
1261
+ load_more?: ((num?: number | Event | undefined) => void) | undefined;
1262
+ displays?: Display[] | undefined;
1263
+ }>;
1264
+ /**
1265
+ * @deprecated Emil's utility in integration.ts is better because it doesn't cause multiply <style> tags and doesn't require a tenant class
1266
+ */
1267
+ export function deprecated_insert_styling(t: Tenant, css: string, extra_html?: string): Promise<void>;
1268
+ /**
1269
+ * @deprecated This is a predecessor to reactive_template which is much more limited (can only have two states) plus it's much more cumbersome to use, which is why I'm deprecating it.
1270
+ */
1271
+ export function placeholder(...args: Parameters<typeof placeholder_worker>): accepted_input_that_resolves_to_elements;
1272
+ type accepted_element_types = Node_Array[0] | Node_Array;
1273
+ type accepted_input_that_resolves_to_elements = accepted_element_types | Promise<accepted_element_types> | (() => accepted_element_types) | (() => Promise<accepted_element_types>);
1274
+ declare function placeholder_worker(placeholder_elements: accepted_input_that_resolves_to_elements, final_elements: accepted_input_that_resolves_to_elements, switching_trigger?: infinite_promise_no_skip<boolean> | Promise<boolean>): Promise<void>;
1275
+ declare global {
1276
+ interface HTMLImageElementWithLoaded extends HTMLImageElement {
1277
+ loaded?: boolean;
1278
+ }
1279
+ interface HTMLSourceElementWithLoaded extends HTMLSourceElement {
1280
+ loaded?: boolean;
1281
+ }
1282
+ }
1283
+ export interface Lazyfier {
1284
+ t: Tenant;
1285
+ container: HTMLElement;
1286
+ selector: string;
1287
+ lazyfinder: lazyfinder;
1288
+ only_load_intersecting: boolean;
1289
+ ignore_data_urls?: boolean;
1290
+ }
1291
+ interface Lazyfier_Options {
1292
+ container?: HTMLElement;
1293
+ lazyfinder?: lazyfinder;
1294
+ selector?: string;
1295
+ wait_for_dominsertion?: boolean | Promise<any>;
1296
+ only_load_intersecting?: boolean;
1297
+ verbose?: boolean;
1298
+ ignore_data_urls?: boolean;
1299
+ }
1300
+ export class Lazyfier {
1301
+ #private;
1302
+ intersection_observer: IntersectionObserver;
1303
+ start_observing_for_new_children_(override_container?: HTMLElement): void;
1304
+ constructor({
1305
+ container,
1306
+ lazyfinder,
1307
+ selector,
1308
+ wait_for_dominsertion,
1309
+ only_load_intersecting,
1310
+ ignore_data_urls,
1311
+ verbose
1312
+ }: Lazyfier_Options);
1313
+ }
1314
+ interface lazyfinder {
1315
+ elements?: HTMLImageElementWithLoaded[];
1316
+ unload?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1317
+ load?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1318
+ }
1319
+ export function test_array_proxy_support(): boolean;
1320
+ export interface Slider_Options {
1321
+ /**
1322
+ * Controls within what distance to hide the left slider button.
1323
+ * The distance is in pixels to the leftmost part of the slider container from the first element in the slider
1324
+ *
1325
+ * Defaults to `10`
1326
+ */
1327
+ dist_to_hide_left?: number;
1328
+ /**
1329
+ * Controls within what distance to hide the right slider button.
1330
+ * The distance is in pixels to the rightmost part of the slider container from the last element in the slider
1331
+ *
1332
+ * Defaults to `10`
1333
+ */
1334
+ dist_to_hide_right?: number;
1335
+ stepstoslide?: number;
1336
+ center_target?: boolean;
1337
+ constructor_plugins?: ((arg0: Slider_Options) => any)[];
1338
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1339
+ correct_bs_targets?: boolean;
1340
+ button_contents?: {
1341
+ right: Node_Iterable;
1342
+ left: Node_Iterable;
1343
+ };
1344
+ button_elems?: {
1345
+ right: HTMLElement;
1346
+ left: HTMLElement;
1347
+ };
1348
+ autoinvalidate_cache?: boolean;
1349
+ }
1350
+ export class Amazing_Slider {
1351
+ #private;
1352
+ container: HTMLElement;
1353
+ insert_here: HTMLElement;
1354
+ intersecting_items_object: {
1355
+ [key: string]: IntersectionObserverEntry;
1356
+ [key: number]: IntersectionObserverEntry;
1357
+ };
1358
+ stepstoslide: number;
1359
+ dist_to_hide_left: number;
1360
+ dist_to_hide_right: number;
1361
+ center_target: boolean;
1362
+ correct_bs_targets: boolean;
1363
+ snap_style?: HTMLStyleElement;
1364
+ on_elements_changed: ((records: MutationRecord[]) => any)[];
1365
+ observer: IntersectionObserver;
1366
+ observe: any;
1367
+ get_index_of_element(target: Element | HTMLElement): number | undefined;
1368
+ first_intersecting_index(min_ratio?: number): number;
1369
+ get first_intersecting(): IntersectionObserverEntry;
1370
+ get index_of_last_element(): number;
1371
+ get currently_selected(): number | undefined;
1372
+ get visible_sizes(): Map<Element, {
1373
+ total_visible: number;
1374
+ ratio_visible: number;
1375
+ margin_left: number;
1376
+ margin_right: number;
1377
+ rect: DOMRect;
1378
+ }>;
1379
+ get cards_fitting_in_viewport(): number;
1380
+ element_by_index(index: number): Element;
1381
+ invalidate_cache(): void;
1382
+ scroll_to_rel(offset: number, harsh?: boolean): void;
1383
+ scroll_to_abs(offset: number, harsh?: boolean): void;
1384
+ constructor({
1385
+ dist_to_hide_left,
1386
+ dist_to_hide_right,
1387
+ stepstoslide,
1388
+ center_target,
1389
+ mutation_plugins,
1390
+ constructor_plugins,
1391
+ correct_bs_targets,
1392
+ button_contents,
1393
+ button_elems,
1394
+ autoinvalidate_cache
1395
+ }: Slider_Options);
1396
+ }
1397
+ export interface Amazing_Lazy_Slider {
1398
+ lazyfier: Lazyfier;
1399
+ }
1400
+ export class Amazing_Lazy_Slider extends Amazing_Slider {
1401
+ constructor(options: Slider_Options, lazyfier_options?: Optional<ConstructorParameters<typeof Lazyfier>[0], "container">);
1402
+ }
1403
+ interface Pro_Slider_Options {
1404
+ container?: string | Node_Iterable;
1405
+ root_selector?: string;
1406
+ override_rec_renderer?: typeof Rec_Renderer;
1407
+ insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1408
+ lazyfier_options?: ConstructorParameters<typeof Amazing_Lazy_Slider>[1];
1409
+ }
1410
+ /**
1411
+ * @deprecated please use RecommendationSlider instead
1412
+ */
1413
+ export function Pro_Slider<T extends Display>(t: Tenant, rendering_options: Extended_RR_Options<T>, options_for_us?: Pro_Slider_Options, slider_options?: Slider_Options): ReturnType<typeof Rec_Renderer<T>>;
1414
+ /**
1415
+ * @deprecated Please use recommendation renderer instead
1416
+ */
1417
+ export class Depict {
1418
+ #private;
1419
+ settings: any;
1420
+ data: any;
1421
+ tracker: void;
1422
+ constructor(settings: any);
1423
+ init(callback: Function, existingDisplays?: object[]): void;
1424
+ loadRecommendations(callback: any): void;
1425
+ trackGAEvent(action: any, index: any, product_id: any, ga_product_ids?: string[]): void;
1426
+ trackPageView(): void;
1427
+ trackClick(index: any): boolean | Promise<void | undefined> | undefined;
1428
+ trackAddToCart(pId: any): boolean | Promise<void | undefined> | undefined;
1429
+ createContainer(root: any, container: any, prepend?: boolean): void;
1430
+ renderTemplate({
1431
+ prep,
1432
+ root,
1433
+ template,
1434
+ itemPreprocessor,
1435
+ itemPostprocessor
1436
+ }?: any): void;
1437
+ }
1438
+ declare global {
1439
+ interface Document {
1440
+ _depict_modify: boolean | undefined;
1441
+ }
1442
+ }
1443
+ interface TemplateToolOptions {
1444
+ max_items?: number;
1445
+ min_items?: number;
1446
+ DNT?: boolean;
1447
+ debug?: boolean;
1448
+ type?: string;
1449
+ product_id?: Function | ((url?: string) => string);
1450
+ sendGa?: boolean;
1451
+ loadHack?: boolean;
1452
+ shade?: boolean;
1453
+ gaid?: string;
1454
+ tenant?: string;
1455
+ market?: string;
1456
+ }
1457
+ /**
1458
+ * @deprecated Please use RecommendationRenderer instead
1459
+ */
1460
+ export const simplified_template_tool: (options: {
1461
+ options: TemplateToolOptions;
1462
+ recs?: object[] | undefined;
1463
+ root: Element;
1464
+ template: string;
1465
+ postProcessor?: Function | undefined;
1466
+ preProcessor?: Function | undefined;
1467
+ }) => Promise<Depict>;
1468
+ interface special_lazyfier_options extends Omit<Lazyfier_Options, "t"> {}
1469
+ interface Deprecated_Slider_Options {
1470
+ dlog?: Function;
1471
+ catchify?: Function;
1472
+ dist_to_hide_left?: number;
1473
+ dist_to_hide_right?: number;
1474
+ stepstoslide?: number;
1475
+ arrow_image?: string;
1476
+ center_target?: boolean;
1477
+ constructor_plugins?: ((arg0: Deprecated_Slider_Options) => any)[];
1478
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1479
+ correct_bs_targets?: boolean;
1480
+ }
1481
+ /**
1482
+ * @deprecated Please use Pro_Slider instead
1483
+ */
1484
+ declare class Deprecated_Amazing_Slider extends Amazing_Lazy_Slider {
1485
+ constructor(static_options: Deprecated_Slider_Options, override_lazyfier_options?: special_lazyfier_options);
1486
+ }
1487
+ export function insert_styling_into_slider(slider: Deprecated_Amazing_Slider): void;
1488
+ interface RR_Slider_Options {
1489
+ container?: string | Node_Iterable;
1490
+ root_selector?: string;
1491
+ Rec_Renderer?: typeof Rec_Renderer;
1492
+ insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1493
+ }
1494
+ /**
1495
+ * @deprecated please use Pro_Slider instead
1496
+ */
1497
+ export function RR_Slider<T extends Display>(t: Tenant, rendering_options: Extended_RR_Options<T>, options_for_us?: RR_Slider_Options, slider_options?: Deprecated_Slider_Options, override_lazyfier_options?: special_lazyfier_options): ReturnType<typeof Rec_Renderer>;
1498
+ type PreProcessor = (tenant: Tenant, display: any, i?: number, with_loadmore?: boolean, with_slider?: boolean, infinite_scroll?: boolean) => any;
1499
+ type PostProcessor = (tenant: Tenant, items: HTMLCollection, display: any, slider?: Deprecated_Amazing_Slider) => HTMLCollection;
1500
+ /**
1501
+ * @deprecated this uses template-tool-v1 which is long surpassed, please use RecommendationGrid or Pro_Slider (based on Recommendation-Renderer) instead
1502
+ */
1503
+ export function get_recs_with_template({
1504
+ t,
1505
+ recs,
1506
+ title,
1507
+ infinite_scroll,
1508
+ with_slider,
1509
+ with_loadmore,
1510
+ template_tool_options,
1511
+ slider_options,
1512
+ pre_processors,
1513
+ post_processors,
1514
+ container_template,
1515
+ // container template
1516
+ template,
1517
+ // recommendation template
1518
+ chunk_size_for_load_more,
1519
+ insertion_promise
1520
+ }: {
1521
+ t: Tenant;
1522
+ recs?: any[];
1523
+ with_loadmore?: boolean;
1524
+ title?: string | Node[] | NodeList;
1525
+ infinite_scroll?: boolean;
1526
+ template_tool_options?: TemplateToolOptions;
1527
+ with_slider?: boolean;
1528
+ slider_options?: Deprecated_Slider_Options;
1529
+ pre_processors?: PreProcessor[];
1530
+ post_processors?: PostProcessor[];
1531
+ container_template: string;
1532
+ template: string;
1533
+ chunk_size_for_load_more?: number;
1534
+ insertion_promise?: Promise<void | unknown>;
1535
+ }): Promise<ChildNode[] | void>;
1536
+ export function default_pre_processor(_t: any, d: any, i: number, with_loadmore: boolean, with_slider: boolean, infinite_scroll: boolean): any;
1537
+ export function default_post_processor(_t: any, itms: HTMLCollection, d: any, slider: Deprecated_Amazing_Slider | null): HTMLCollection;
1538
+ /**
1539
+ * @deprecated please use `fetch_retry()` instead
1540
+ *
1541
+ * Windows proof fetch factory: windows proof fetch is a utility which retries fetch requests 10 times when they fail. Reason for this is a certain windows 10 build where the network stack randomly breaks 20% of https connections
1542
+ * (Note: this thing really should be rewritten with exponential backoff and a better API)
1543
+ * @param dlog logging function to use
1544
+ * @param error_log an array to which errors will be pushed
1545
+ * @return a windows proof fetch function
1546
+ */
1547
+ export const wpff: (dlog: any, error_log?: any[]) => (url: RequestInfo, body: BodyInit, headers?: HeadersInit, decode_json?: boolean, fetch_options?: RequestInit, attempt?: number) => any;
1548
+ export const use_element: <E extends HTMLOrSVGElement = HTMLElement>(callback: (element: E) => void, element: E) => E;
1549
+ export function use_listener<K extends keyof GlobalEventHandlersEventMap, E extends HTMLElement = HTMLElement>(event: K, handler: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, element: E): E;
1550
+ export const classlist: (classes: (string | undefined)[]) => string;
1551
+ type Props = {
1552
+ children?: Elem[] | Elem;
1553
+ onClick?: (e: MouseEvent) => void;
1554
+ [key: string]: any;
1555
+ };
1556
+ type Elem = Node | string;
1557
+ type Component = (props: Props, _unknown?: unknown) => HTMLElement;
1558
+ export const jsx: (tag: string | Component, {
1559
+ children,
1560
+ ...props
1561
+ }: Props, _unknown?: unknown) => JSX.Element;
1562
+ export const jsxs: (tag: string | Component, {
1563
+ children,
1564
+ ...props
1565
+ }: Props, _unknown?: unknown) => JSX.Element;
1566
+ export const chevronRight: HTMLElement;
1567
+ export const chevronLeft: HTMLElement;
1568
+ export const expandingContainer: ({
1569
+ duration
1570
+ }?: {
1571
+ duration?: number;
1572
+ }) => {
1573
+ expand: () => void;
1574
+ content: HTMLDivElement;
1575
+ container: HTMLDivElement;
1576
+ };
1577
+ /**
1578
+ * Like Promise.any but for async iterable infinite promises (object that have `.state` and a [Symbol.asyncIterator]). Returns an array of all current values when one value udpates.
1579
+ * @param iterables Array of IPNS
1580
+ * @return IPNS that resolves with an array of the values of all provided IPNS when one of them resolves
1581
+ */
1582
+ export function zip_async_iterables<T extends any[]>(iterables: IPNS<T[keyof T]>[]): IPNS<T>;
1583
+ /** Overrides that can specify a different amount of columns for certain rows
1584
+ * @param key The row (starts at 1) that you're "selecting" to override
1585
+ * @param value The amount of columns that your selected row should have
1586
+ */
1587
+ type Override = {
1588
+ overrides: Record< /* Row: */number, /* Column: */number>;
1589
+ };
1590
+ export type ColAtSize = /** [ <number of columns>, <min-width>, <max-width>, <spacing> ] */readonly [number, null, string, string | null] | readonly [number, string, string, null, Override] | readonly [number, string, null, string | null] | readonly [number, string, string, string | null] | readonly [number, string, null] | readonly [number, string, string] | readonly [number, null, string] | readonly [number, string];
1591
+ export type ColsAtSize = readonly ColAtSize[];
1592
+ export type LayoutOptions = {
1593
+ container_element: Element;
1594
+ cols_at_size: ColsAtSize;
1595
+ grid_spacing: string;
1596
+ rows: {
1597
+ start_rows?: number;
1598
+ rows_per_click?: number;
1599
+ ipns?: IPNS<number>;
1600
+ max_rows?: number;
1601
+ button?: HTMLElement;
1602
+ } | "all";
1603
+ layout: "slider" | "grid";
1604
+ disable_partial_rows?: boolean;
1605
+ override_vertical_spacing?: string;
1606
+ };
1607
+ export const layout_media_query_header: (min: string, max?: string) => string;
1608
+ /**
1609
+ * Grid: Calculates CSS for a grid with a certain spacing and certain number of columns at certain screen sizes, including a view more button.
1610
+ * @param rows if set to 'all': Just generate grid styling without any viewing/hiding functionality. If an object: start_rows is the number of rows at the beginning. rows_per_click is the amount of rows to view on each view more buttonn click. button is the view more button to display. ipns is an async iterable infinite promise that you can use to get and set the number of currently viewed rows
1611
+ * @param container_element container element of the elements that you want to style and hide
1612
+ * @param cols_at_size An array with sub arrays looking like this: `[n_cols, min_width_media_query, max_width_media_query, grid_spacing_for_size]`, everything after `[n_cols, min_width]` is optional. falsey value for `min_width = no min_width`
1613
+ * @param grid_spacing spacing to use if none is specified for the specific size in `cols_at_size`
1614
+ * @param disable_partial_rows If set to `true`, will not let user press "show more" if next row is a partial row. Example of partial row: `cols_at_size` says we should have 4 recs in the next row but we only have 2 left, so the row just gets 2 instead of 4, meaning it doesn't "fill out".
1615
+ * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1616
+ */
1617
+ export function Layout({
1618
+ rows,
1619
+ container_element,
1620
+ cols_at_size,
1621
+ grid_spacing,
1622
+ layout,
1623
+ disable_partial_rows,
1624
+ override_vertical_spacing
1625
+ }: LayoutOptions): Promise<void>;
1626
+ /** Getting how many recs should be displayed for a certain row (while taking override rules into account)
1627
+ * This returns number of recs for this row and all the previous ones
1628
+ * @param row The "index" of the row (counting from the top). Starts at 1.
1629
+ * @param options Your cols_at_size layout option
1630
+ */
1631
+ export function layout_get_total_rec_amount_for_row(row: number, options: LayoutOptions["cols_at_size"][number]): number;
1632
+ /**
1633
+ * Same as `get_total_rec_amount_for_row` but caps the result to never exceed @param max_recs
1634
+ */
1635
+ export function layout_get_visible_recs_without_partial_rows(rows: number, max_recs: number, options: LayoutOptions["cols_at_size"][number]): number;
1636
+ /**
1637
+ * basically equivalent of n_col_styling css mixin - generates distances for a flex grid with margins
1638
+ * @param selector_beginning Main selector targeting container classname to use in generated css
1639
+ * @param default_grid_spacing_text Spacing to use if not specified in cols_at_size for a specific size
1640
+ * @param cols_at_size An array with sub arrays looking like this: [n_cols, min_width_media_query, max_width_media_query, grid_spacing_for_size], everything after [n_cols, min_width] is optional. falsey value for min_width = no min_width
1641
+ * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1642
+ * @return String of generated CSS
1643
+ */
1644
+ export function n_col_styling_with_dist(selector_beginning: string, default_grid_spacing_text: string, cols_at_size: ColsAtSize, layout: "slider" | "grid", override_vertical_spacing?: string): string;
1645
+ export interface RecommendationGridOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "layout"> {
1646
+ container_elements: Node_Array;
1647
+ container_selector?: string;
1648
+ override_rec_renderer?: typeof default_rr<T>;
1649
+ lazyfier_options?: Omit<Lazyfier_Options, "t">;
1650
+ eager_images?: boolean;
1651
+ }
1652
+ /**
1653
+ * RecommendationGrid: Searches your container_elements for ".grid" or `container_selector`, runs default_rr or `override_rec_renderer` and puts the recs into the found element. Then runs `Grid` on it.
1654
+ * @param t Instance of Tenant
1655
+ * @param recommendation_renderer_options Options for default_rr or override_rec_renderer
1656
+ * @param container_elements The elements from your container template.
1657
+ * @param container_selector Selector for finding the element in container_elements that should be the recommendations' immediate parents. A.k.a the selector for the "insertion point"
1658
+ * @param override_rec_renderer Other recommendation renderer to use apart from default_rr (i.e. placeholder_rr)
1659
+ * @param lazyfier_options Options for Lazyfier which does lazyloading of the images. Optional. Keys with the same name as the options passed by RecommendationGrid will override them.
1660
+ * @param eager_images Don't lazyload images
1661
+ * @param ...options_for_grid Options for Grid. See documentation of Grid.
1662
+ * @constructor
1663
+ */
1664
+ export function RecommendationGrid<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, {
1665
+ container_elements,
1666
+ container_selector,
1667
+ override_rec_renderer,
1668
+ lazyfier_options,
1669
+ eager_images,
1670
+ ...options_for_grid
1671
+ }: RecommendationGridOptions<T>): Promise<RecRendererResult<T>>;
1672
+ export interface EasySliderOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "rows" | "layout"> {
1673
+ rows?: {
1674
+ start_rows?: number;
1675
+ ipns?: IPNS<number>;
1676
+ } | "all";
1677
+ container_elements: Node_Array;
1678
+ container_selector?: string;
1679
+ override_rec_renderer?: typeof default_rr<T>;
1680
+ lazyfier_options?: Omit<Lazyfier_Options, "t">;
1681
+ eager_images?: boolean;
1682
+ dist_to_hide_left?: number;
1683
+ dist_to_hide_right?: number;
1684
+ stepstoslide?: number;
1685
+ center_target?: boolean;
1686
+ constructor_plugins?: ((arg0: Slider_Options) => any)[];
1687
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1688
+ button_contents?: {
1689
+ right: Node_Iterable;
1690
+ left: Node_Iterable;
1691
+ };
1692
+ button_elems?: {
1693
+ right: HTMLElement;
1694
+ left: HTMLElement;
1695
+ };
1696
+ override_vertical_spacing?: string;
1697
+ }
1698
+ export type RecommendationSliderSurface<T extends Display> = Record<string, never> | {
1699
+ elements: Node_Array;
1700
+ slider: Amazing_Slider | Amazing_Lazy_Slider;
1701
+ displays: T[];
1702
+ };
1703
+ /**
1704
+ *
1705
+ * The most epic RecommendationSlider todate
1706
+ * @param t Instance of tenant class
1707
+ * @param recommendation_renderer_options Options for Recommendation Renderer
1708
+ * @param RecommendationGrid_options Similar options object to RecommendationGrid except that it also contains options to Amazing_Slider
1709
+ * @return a Surface (object) that contains displays, elements and the instance of the slider class (as `slider`)
1710
+ */
1711
+ export function RecommendationSlider<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, {
1712
+ container_elements,
1713
+ container_selector,
1714
+ override_rec_renderer,
1715
+ lazyfier_options,
1716
+ eager_images,
1717
+ grid_spacing,
1718
+ cols_at_size,
1719
+ override_vertical_spacing,
1720
+ rows,
1721
+ ...slider_options
1722
+ }: EasySliderOptions<T>): Promise<RecommendationSliderSurface<T> | RecRendererResult<T> | Surface<T>>;
1723
+ export function slider_autoscroll_factory(interval?: number): {
1724
+ constructor_plugin(this: Amazing_Slider): void;
1725
+ mutation_plugin: (this: Amazing_Slider, _intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1726
+ };
1727
+ export function make_button1(): {
1728
+ left: [HTMLImageElement];
1729
+ right: [HTMLImageElement];
1730
+ };
1731
+ /**
1732
+ * Returns an object to put into `button_contents` for `Pro_Slider` containing the icon arrow images
1733
+ * @return An object with left and right being an array containing one image
1734
+ */
1735
+ export function make_button2(): {
1736
+ left: HTMLImageElement[];
1737
+ right: HTMLImageElement[];
1738
+ };
1739
+ export function slider_dots_factory({
1740
+ t,
1741
+ navcont_insertion_fn,
1742
+ navdot,
1743
+ dontshowonedot,
1744
+ bitesize
1745
+ }: {
1746
+ t: Tenant;
1747
+ navcont_insertion_fn?: (slider: Amazing_Slider, navcont: HTMLDivElement) => any;
1748
+ navdot: (unique_name: number, index: number) => Element;
1749
+ dontshowonedot?: boolean;
1750
+ bitesize?: number;
1751
+ }): {
1752
+ constructor_plugin: () => void;
1753
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1754
+ };
1755
+ export function navdot(unique_name: string | number): HTMLElement;
1756
+ export function slider_draggable_factory(t: Tenant): {
1757
+ constructor_plugin: (slider_options: any) => void;
1758
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1759
+ post_pro_plugin: {
1760
+ instant: (items: HTMLCollection) => void;
1761
+ };
1762
+ };
1763
+ export function slider_fading_factory({
1764
+ fade_in_duration_,
1765
+ fade_out_duration_,
1766
+ visible_opacity_,
1767
+ faded_opacity_,
1768
+ easing_,
1769
+ threshold_
1770
+ }?: {
1771
+ fade_in_duration_?: number;
1772
+ fade_out_duration_?: number;
1773
+ visible_opacity_?: number;
1774
+ faded_opacity_?: number;
1775
+ easing_?: string;
1776
+ threshold_?: number;
1777
+ }): {
1778
+ readonly mutation_plugin_: (this: Amazing_Slider, entries: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1779
+ };
1780
+ export function slider_fractional_factory(_t?: any, fraction?: number, max_steps?: number, dont_enable_correct_bs_targets?: boolean, min_steps?: number): {
1781
+ constructor_plugin: (slider_options: Slider_Options) => void;
1782
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1783
+ };
1784
+ /**
1785
+ * * Plugin for rendering a scrollbar below the slider that follow the slider position.
1786
+ * * Scroll container class: `depict_slider_scroll`
1787
+ * * Scroll bar class: `depict_slider_scroll_bar`
1788
+ * @param options Options for the scrollbar. Add position styling and additional classes.
1789
+ */
1790
+ export function slider_show_scroll(options: {
1791
+ add_position_styling: boolean;
1792
+ scroll_bar_classes?: string[];
1793
+ scroll_container_classes?: string[];
1794
+ }): {
1795
+ constructor_plugin: (_slider_options: Slider_Options) => void;
1796
+ mutation_plugin: (_intersections: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1797
+ };
1798
+ export function slider_snap_css(_t?: any, {
1799
+ snapEvery,
1800
+ align
1801
+ }?: {
1802
+ snapEvery?: number;
1803
+ align?: "center" | "start" | "end";
1804
+ }): {
1805
+ constructor_plugin: (_slider_options: Slider_Options) => void;
1806
+ mutation_plugin: (_intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1807
+ };
1808
+ export function can_use_snapping_and_still_scroll(): Promise<boolean>;
1809
+ export function slider_snapping_factory(options?: {
1810
+ stepsize?: number;
1811
+ threshold?: number;
1812
+ }): {
1813
+ constructor_plugin: (slider_options: any) => void | undefined;
1814
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void | undefined;
1815
+ };
1816
+ export function slider_wraparound_factory({
1817
+ clones_per_side
1818
+ }?: {
1819
+ clones_per_side?: number | undefined;
1820
+ }): {
1821
+ constructor_plugin: (this: Amazing_Slider) => void;
1822
+ mutation_plugin: (this: Amazing_Slider, intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1823
+ post_processor: <T extends Display>(elements: Node_Array | NodeListOf<ChildNode>, _display: Display, info: InfoForProcessing<T>) => Promise<NodeListOf<ChildNode> | Node_Array>;
1824
+ };
1825
+ export type ReactiveTemplateValueContents = string | number | Node_Array[number] | undefined | (string | number | Node_Array[number])[];
1826
+ export function reactive_template(initial_value?: ReactiveTemplateValueContents): readonly [Node_Array, () => ReactiveTemplateValueContents, (arg0: ReactiveTemplateValueContents) => void];
1827
+ /**
1828
+ * A wrapper around window.matchMedia, basically cross browser compatibly adds an event listener to a media query that triggers when it changes
1829
+ * @param query The media query (without `@media`)
1830
+ * @param catchified_handler The function to execute
1831
+ * @param initial_call If the handler should be called instantly with the current state of the media query
1832
+ * @return An object containing `remove`, a function which removes the event listener again
1833
+ */
1834
+ export function javascript_media_query(
1835
+ // inspired by code in houdinisportswear modify script
1836
+ query: string, handler: (e: MediaQueryListEvent | MediaQueryList | {
1837
+ matches: false;
1838
+ }) => void, initial_call?: boolean): {
1839
+ remove(): void;
1840
+ };
1841
+ type RenderingFunction<T extends Display> = (...args: any[]) => Promise<{
1842
+ surface_: Surface<T> | void;
1843
+ cache_until_?: Promise<any>;
1844
+ }>;
1845
+ /**
1846
+ * Makes it possible to have "multiple surfaces" in one surface. So you provide multiple functions that return a `Surface` and get one `Surface` which will switch between the `Surface`s returned by the different functions depending on which one is selected by an IPNS.
1847
+ * @param surface_rendering_functions_ An array of functions returning an object that contains a Surface and a Promise until which's resolvement the Surface will be cached and re-used without calling the rendering function again.
1848
+ * @param current_surface_ An IPNS representing which Surface should currently be chosen. It has to resolve with a number corresponding with the index of a function in surface_rendering_functions_.
1849
+ * @return a `Surface` object which, utilising a `reactive_template` always represents the currently chosen surface
1850
+ */
1851
+ export function surface_mixer<T extends Display>({
1852
+ surface_rendering_functions_,
1853
+ current_surface_
1854
+ }: {
1855
+ surface_rendering_functions_: RenderingFunction<T>[];
1856
+ current_surface_: IPNS<number>;
1857
+ }): Promise<Surface<T>>;
1858
+ /**
1859
+ * To be used in conjunction with surface_mixer. Makes it possible to switch Surface depending on screen size
1860
+ * @param surface_per_size An array of arrays which represent which surface to show at which screen width. The arrays in the array can have up to three entries, the first one being: an index in the surface_rendering_functions_ array passed to `surface_mixer`, the second one: min screen width to switch to this surface, the third one: max screen width at which this surface should still be shown.
1861
+ * @param cleanup_promise Optional. A promise after which sizes_to_surface stops listening for media query changes. If none is provided we automatically stop listening on navigation away (if the href changes).
1862
+ * @return An IPNS resolving with the number of the surface that should currently be shown
1863
+ */
1864
+ export function sizes_to_surface(surface_per_size: [surface_index: number, min: string | null, max?: string][], cleanup_promise?: Promise<any>): IPNS<number>;
1865
+ /**
1866
+ * Returns a promise that resolve the next time the href is changed
1867
+ */
1868
+ export function promise_until_next_navigation(): Promise<string | undefined>;
1869
+ export function orderpage_transaction_id_extractor(t: Tenant, selector: string, filter?: (text: string) => string | undefined): void;
1870
+ /**
1871
+ * Looks at all entries in window.dataLayer, past present and future, and attempts to find transaction IDs in them.
1872
+ * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1873
+ * @param tenant The tenant we are tracking.
1874
+ * @param id_extractor Maps an entry to a transaction ID string, or something falsy if no transaction ID is found.
1875
+ * For example: entry => entry?.event?.purchase?.orderId
1876
+ */
1877
+ export function datalayer_transaction_id_extractor(tenant: Tenant, id_extractor: (layer_entry: any) => any): void;
1878
+ /**
1879
+ * Looks at all URL changes, including the current URL, and attempts to find transaction IDs in them.
1880
+ * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1881
+ * @param tenant The tenant we are tracking.
1882
+ * @param id_extractor Maps an URL to a transaction ID string, or something falsy if no transaction ID is found.
1883
+ * For example: url => url.searchParams.get("orderId")
1884
+ */
1885
+ export function url_transaction_id_extractor(tenant: Tenant, id_extractor: (url: URL) => unknown): void;
1886
+ export function send_transaction_id_to_depict(t: Tenant, input_id: string, dsid?: string, filter?: (text: string) => string | undefined): void;
1887
+ /**
1888
+ * Intercepts google analytics events for transactions (e.g when payment is made) and also sends it to depict.
1889
+ * */
1890
+ export function ga_to_transaction_api(t: Tenant, filter?: (text: string) => string | undefined): void;
1891
+ export function send_product_unavailable_to_depict(t: Tenant, unavailability_type: EUnavailabilityType): Promise<void>;
1892
+ export interface ListenableSetEvent<T> extends CustomEvent {
1893
+ detail: T;
1894
+ }
1895
+ /**
1896
+ * Set but you can listen for values being added or removed
1897
+ * i.e. my_set.addEventListener("add", ({detail}) => console.log(detail, "was added to", my_set));
1898
+ */
1899
+ export class ListenableSet<T> extends Set<T> {
1900
+ #private;
1901
+ addEventListener(event: "add" | "delete", callback: (ev: ListenableSetEvent<T>) => unknown, options?: Parameters<(typeof EventTarget.prototype)["addEventListener"]>[2]): void;
1902
+ removeEventListener(event: "add" | "delete", callback: (ev: Event) => unknown): void;
1903
+ add(property: T): this;
1904
+ delete(property: T): any;
1905
+ }
1906
+ /**
1907
+ * This does what you'd think Element.closest does. It finds the closest node in the DOM tree matching a selector. So it starts out with the siblings and then goes upwards in the DOM and checks the siblings and their children of the parent until there's no parent anymore.
1908
+ * @param element Element to start out at
1909
+ * @param selector Selector to search for
1910
+ * @param start_right=true In what direction to start: true = right, false = left
1911
+ * @return The found element or undefined
1912
+ */
1913
+ export function chaotic_closest(element: Element, selector: string, start_right?: boolean): Element | undefined;
1914
+ type CompareMethod<T> = (i1: T, i2: T) => boolean;
1915
+ export const deduplicate: <T>(arr1: T[], arr2: T[], compareFunc: CompareMethod<T>) => T[];
1916
+ export const dedup_products: <T extends LegacyDisplay>(arr1: T[], arr2: T[] | undefined) => T[];
1917
+ /**
1918
+ * Attempt to navigate using nextjs's spa router.
1919
+ * Falls back to default browser navigation.
1920
+ * Docs: https://nextjs.org/docs/api-reference/next/router
1921
+ */
1922
+ export function navigate_with_next_router(e: MouseEvent, url: string): false | undefined;
1923
+ /**
1924
+ * proxies window.fetch:
1925
+ * 1. Instead of window.fetch fetch_apply is called, target being the original fetch function
1926
+ * 2. fetch_proxy_handler is called and may read the request and return a (fake) response
1927
+ * 3. if fetch_proxy_handler fails the original target is called with the same this and arguments
1928
+ * We are meticulously preserving this, target and its arguments in case that someone replaces fetch with a function that does something else
1929
+ * I recognise that I could hardcode window and fetch but I DO NOT want any cases where this may break anything if I can avoid it
1930
+ * Remember to return response, else it will make another request
1931
+ * @param fetch_proxy_handler Called instead of the original fetch function everytime someone does fetch. Has to return a response.
1932
+ * @param unsafe_throw_up Whether to ignore above described safety features and just pass on precisely what the fetch_proxy_handler does. If you do this, make sure to CATCH ALL ERRORS of your logic in the fetch_proxy_handler and only throw if the original fetch throws
1933
+ * @return Nothing
1934
+ */
1935
+ export function fetch_replacer(fetch_proxy_handler: (target: typeof window.fetch, this_arg: typeof window, arguments_list: Parameters<typeof window.fetch>) => Promise<Response | FakeResponse>, unsafe_throw_up?: boolean): Promise<void>;
1936
+ /**
1937
+ * This class extends and models the `Response` class as close as possible. Basically the only thing not being identical would be `instance_of_fake_response.constructor` and some other stuff, but nothing connected to how you're usually using a `Response` object.
1938
+ * Useful when wanting to change the result of a `fetch request`
1939
+ * Please see repo for usage examples
1940
+ * @param response_string String to base Response object on
1941
+ * @param url URL to claim that the Response is from
1942
+ * @param headers Response headers
1943
+ * @param override_options More options to pass to the `Response` constructor
1944
+ */
1945
+ export class FakeResponse extends Response {
1946
+ constructor(response_string: string, url: string, headers?: HeadersInit, override_options?: ResponseInit);
1947
+ }
1948
+ export type ShopifyItem = {
1949
+ id: number;
1950
+ handle: string;
1951
+ quantity: number;
1952
+ url: string;
1953
+ };
1954
+ export type ShopifyError = {
1955
+ status: number;
1956
+ message: string;
1957
+ description: string;
1958
+ };
1959
+ /**
1960
+ * Represents a Shopify cart "event", i.e. Whenever a Shopify API request is sucessfull.
1961
+ * - `type` represent the type of event
1962
+ * - `response` resolves to a shopify response
1963
+ */
1964
+ export type ShopifyEvent = {
1965
+ type: "get_items";
1966
+ response: Promise<ShopifyItem[] | ShopifyError>;
1967
+ body?: object;
1968
+ } | {
1969
+ type: "add_items";
1970
+ response: Promise<ShopifyItem[] | ShopifyError>;
1971
+ body?: object;
1972
+ } | {
1973
+ type: "update_items";
1974
+ response: Promise<ShopifyItem[] | ShopifyError>;
1975
+ body?: object;
1976
+ } | {
1977
+ type: "change_items";
1978
+ response: Promise<ShopifyItem[] | ShopifyError>;
1979
+ body?: object;
1980
+ } | {
1981
+ type: "clear_items";
1982
+ response: Promise<[] | ShopifyError>;
1983
+ body?: object;
1984
+ };
1985
+ /**
1986
+ * Whenever any request to the shopify cart endpoint (this includes requests made by merchant code) is made {@link on_response} is called.
1987
+ *
1988
+ * ### Caveats
1989
+ * - This currently doesn't intercept XHR requests, only `fetch`. Interpecpting XHR should be implemented at some point!
1990
+ *
1991
+ * - Under the hood, this function works by proxying `window.fetch`. This isn't guaranted to work, and could even break merchant code.
1992
+ * Call this function early on in the execution for the best possibillity of success.
1993
+ *
1994
+ * - If the merchant performs a `window.fetch` to Shopify before `intercept` then that response wont be intercepted.
1995
+ * If you know that the merchant will make a request to Shopify early on then it might make sense to do something like:
1996
+ * ```
1997
+ * const handle = setTimeout(catchify(() => get_items_in_cart()), 2000)
1998
+ * intercept(evt => {
1999
+ * canel_timeout(handle)
2000
+ * ...
2001
+ * })
2002
+ * ```
2003
+ * In order to get the cart contents at some point even if you miss the merchants innitialt Shopify request.
2004
+ *
2005
+ * - `intercept` intercepts all requests to Shopify, including requests made by you.
2006
+ */
2007
+ export function intercept(on_request: (event: ShopifyEvent) => any): void;
2008
+ export type AddToCartOptions = {
2009
+ quantity?: number;
2010
+ };
2011
+ /**
2012
+ * Add an item to the Shopify cart.
2013
+ *
2014
+ * ### Caveats
2015
+ * Keep in mind that adding to the shopify cart wont neccesarily update the merchants UI,
2016
+ * it only means that when the merchant fetches the cart again then they'll get the item added by you.
2017
+ * Usually the merchant has it's own global add-to-cart function that can be used. While doing that can
2018
+ * take more developer time it means that you usually get the merchant UI to update correctly.
2019
+ *
2020
+ * @param shopify_id
2021
+ * @param options.quantity How many of an item to add, defaults to `1`.
2022
+ * @throws If the response JSON is in an unexpected format.
2023
+ */
2024
+ export function add_item(shopify_id: string, options?: AddToCartOptions): Promise<ShopifyItem[] | ShopifyError>;
2025
+ /**
2026
+ * Fetch the items in the shoppify cart.
2027
+ *
2028
+ * This is probably not the right function for mose use-cases.
2029
+ * Want to get notified when merchant code adds new items to the cart through Shopify?
2030
+ * Use {@link intercept} to intercept all calls to Shopify (even ones made by merchant code).
2031
+ *
2032
+ * @returns All items currently in the cart.
2033
+ * @throws If the response JSON is in an unexpected format.
2034
+ */
2035
+ export function get_items_in_cart(): Promise<ShopifyItem[] | ShopifyError>;
2036
+ declare global {
2037
+ interface Window {
2038
+ ShopifyAnalytics: {
2039
+ meta?: {
2040
+ product?: ShopifyMetaProduct;
2041
+ };
2042
+ };
2043
+ }
2044
+ }
2045
+ interface ShopifyMetaProduct {
2046
+ id?: string;
2047
+ vendor?: string;
2048
+ variants?: {
2049
+ id?: string;
2050
+ sku?: string;
2051
+ }[];
2052
+ }
2053
+ /** Shopify sites often has an interesting meta object defined on window.ShopifyAnalytics.meta
2054
+ * The SKU that backend requires might only be found in the meta object.
2055
+ * This function gives you that object in a safe way that won't break Shopify.
2056
+ */
2057
+ export const get_shopify_analytics_meta_product: () => Promise<ShopifyMetaProduct | undefined>;
2058
+ /**
2059
+ * Waits for google optimize and then gets the variant of a specified experiment id from it. Try not to use this when setting up A/B tests as it causes huge delays. Consider doing a server side optimize A/B test instead and use `get_and_track_variant` to get the same variant as the backend, or, if backend is not involved, use `client_side_server_side_a_b_test`
2060
+ * @param t Instance of `Tenant class`
2061
+ * @param experiment_id Optimize experiment id of running A/B test
2062
+ * @param functions_to_variants An array having a function to execute for each variant. The index of the function in the array specifies its variant.
2063
+ * @param functions_to_variants [description]
2064
+ * @return The return value of the called function
2065
+ */
2066
+ export function get_optimize_variant({
2067
+ t,
2068
+ experiment_id,
2069
+ functions_to_variants
2070
+ }: {
2071
+ t: Tenant;
2072
+ experiment_id: string;
2073
+ functions_to_variants: Function[];
2074
+ }): Promise<any>;
2075
+ /**
2076
+ * Ensures that the attribute value of an element is what an AsyncIterable resolves with
2077
+ * @param el Element to set attribute on
2078
+ * @param attribute_name Name of the attribute to set
2079
+ * @param async_iterable AsyncIterable to loop over
2080
+ * @param quit_after_navigation=true Whether to stop awaiting the AsyncIterable if the page navigates
2081
+ * @return [description]
2082
+ */
2083
+ export function iterable_to_attribute(el: Element, attribute_name: string, async_iterable: AsyncIterable<string>, quit_after_navigation?: boolean): Element;
2084
+ /**
2085
+ * Merges an IPNS with `reactive_template` - if the IPNS updates the reactive template's state is updated to what the IPNS returns
2086
+ * @param async_iterable The async iterable to use
2087
+ * @param quit_after_navigation Whether to stop listening for the IPNS when navigating away
2088
+ * @return An array of elements. Keep a reference to this since its content will update. This is because it's possible that the nodes are not yet in the DOM, meaning replaceWith won't work.
2089
+ */
2090
+ export function iterable_to_elems(async_iterable: AsyncIterable<ReactiveTemplateValueContents>, quit_after_navigation?: boolean): Node_Array;
2091
+ /**
2092
+ * Creates a context for every a function that could cause an `insert_surface` infinite loop (by restoring to old els on no recs which then again triggers an insertion) and hinders any further execution of the function of that "context" if the `insert_surface` call it contains fails
2093
+ * @param ...args Any arguments that will also be passed on to the wrapped function. If the wrapped function takes an ElementObserverEvent the disconnector on it will also be called if a context should be "stopped";
2094
+ * @return A wrapped function that now executes in a context
2095
+ */
2096
+ export const prevent_infinite_loop: <A extends any[], B>(cb: (...args: A) => void | B) => (...args: A) => void | B;
2097
+ /**
2098
+ * Inserts one or multiple surfaces into the DOM.
2099
+ * Will also revert (if verb is `replaceWith`) or remove the inserted elements again if placeholder rendering fails. This happens by a promise inside of the `Surface`s
2100
+ * @param surfaces Array with surfaces to insert
2101
+ * @param verb Verb on how to insert
2102
+ * @param target Selector for `observer.onexists` to find element to insert VERBto, alternatively an element
2103
+ * @param remove_after_navigation Whether to remove the elements from the DOM again if a navigation away occurs, defaults to true
2104
+ * @param try_forever Whether to try to insert the same surface even after the page has navigated away, defaults to false
2105
+ * @param preserve_elements Whether to reinsert elements into it's container if they are removed, useful for sites using VDOM diffing such as react where nodes that aren't in the VDOM are removed when rerendering
2106
+ * @return An array of promises, corresponding to the provided surfaces, where each promise will resolve with an object containing the surface and whether it failed or succeded
2107
+ */
2108
+ export function insert_surfaces<T extends Display>({
2109
+ surfaces: input_surfaces,
2110
+ verb,
2111
+ target,
2112
+ remove_after_navigation,
2113
+ try_forever,
2114
+ preserve_elements
2115
+ }: {
2116
+ verb: InsertionVerb;
2117
+ target: string | HTMLElement;
2118
+ remove_after_navigation?: boolean;
2119
+ try_forever?: boolean;
2120
+ surfaces: (Promise<Surface<T> | void> | Surface<T> | void)[];
2121
+ preserve_elements?: boolean;
2122
+ }): Promise<{
2123
+ surface: Surface<T>;
2124
+ succeeded: boolean;
2125
+ }>[];
2126
+ export const revertable_remove: (target: string | Element | Node_Array, should_stay_inserted: Promise<boolean>) => Promise<void | undefined>;
2127
+ type MakePlaceholderRROption<T extends Display> = {
2128
+ override_rec_renderer?: (t: Tenant | null, rendering_options: Extended_RR_Options<T>) => Promise<RecRendererResult<T>>;
2129
+ image_width?: number;
2130
+ image_height?: number;
2131
+ color?: string;
2132
+ num_items?: number;
2133
+ on_no_rendering_result?: (result?: RecRendererResult<T>) => any;
2134
+ post_rendering?: (surface?: RecRendererResult<T>) => Promise<void> | void;
2135
+ };
2136
+ /**
2137
+ * We want to deprecate this
2138
+ */
2139
+ export type PlaceholderRenderingDisplay = {
2140
+ sale_price: number;
2141
+ page_url: "#" | string;
2142
+ image_url: string;
2143
+ original_price: number;
2144
+ product_id: "placeholder" | string;
2145
+ recommendation_id: "placeholder" | string;
2146
+ title: string;
2147
+ brand: string;
2148
+ };
2149
+ export const random_text_placeholder: () => string;
2150
+ export const placeholder_svg: (image_width: number, image_height: number, color?: string) => string;
2151
+ /**
2152
+ * Wraps default_rr or provided override_rec_renderer in two rendering passes where the first one will render placeholders and the second one what actually is asked for. As soon as the second pass completes the result of the first one is replaced with it.
2153
+ * @param [override_rec_renderer=default_rr] The recommendation renderer to use
2154
+ * @param [image_width=2000] Width of placeholder image svg (use to set aspect ratio)
2155
+ * @param [image_height=2000] Height of placeholder image svg (use to set aspect ratio)
2156
+ * @param [num_items=10] Number of placeholders to render
2157
+ * @param [color="#d9d9d9"] Color of placeholder image svg
2158
+ * @param [on_no_rendering_result] If rendering of actual recommendations fails (doesn't yield any `elements`) this function will be called with the rendering result as first argument
2159
+ * @param [post_rendering] Will be called and awaited after rendering of actual recommendations, has a chance to change them before they get inserted into the DOM
2160
+ * @return It returns the same as a normal recommenation renderer would, meaning an object that might contain `displays` and `elements`
2161
+ */
2162
+ export function make_placeholder_rr<T extends Display>({
2163
+ override_rec_renderer,
2164
+ image_width,
2165
+ image_height,
2166
+ num_items,
2167
+ color,
2168
+ on_no_rendering_result,
2169
+ post_rendering
2170
+ }?: MakePlaceholderRROption<T>): Promise<(t: Tenant | null, rendering_options: Extended_RR_Options<T | PlaceholderRenderingDisplay>) => Promise<Record<string, never> | {
2171
+ elements: Node_Array;
2172
+ displays: T[];
2173
+ }>>;
2174
+ /**
2175
+ * Makes Node.prototype.removeChild not throw and emulate correct removal when a node is being removed by React's VDOM diffing that we have already removed before
2176
+ * @return a WeakSet to add nodes to which you remove and want to ignore removal errors for
2177
+ */
2178
+ export function removeChild_error_swallowing_factory(): WeakSet<Node>;
2179
+ /**
2180
+ * restore (if no allSettled and prototype.finally) native Promise and cement Promise - some customers force polyfill promise with flawed implementations of .all and .allSettled that randomly throw (see usage examples)
2181
+ * @return void
2182
+ */
2183
+ export function replace_promise_with_native_if_exists_and_enforce(): void;
2184
+ /**
2185
+ * Creates a blank iframe inside <head> and returns window.Promise out of it
2186
+ * @return a pristine, unpolyfilled window.Promise
2187
+ */
2188
+ export function get_iframe_promise(): PromiseConstructor;
2189
+ /**
2190
+ * Proxies XMLHttpRequest.prototype.open to an open function which also calls the provided `fetch_handler` with useful information as parameter
2191
+ * @param fetch_handler A function which is catchified and which's return value is ignored. It gets called every time an XHR request gets opened
2192
+ * @return void
2193
+ */
2194
+ export function xhr_replace(fetch_handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, arg_array: Parameters<typeof XMLHttpRequest.prototype.open>) => void): void;
2195
+ /**
2196
+ * xhr_load uses xhr_replace but adds the provided handler as a "load" event listener to every XHR request instead of calling it on open
2197
+ * @param handler The function called on load of every XHR request.
2198
+ * @return void
2199
+ */
2200
+ export function xhr_load(handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, event: ProgressEvent<XMLHttpRequestEventTarget>) => any): void;
2201
+ export function xhr_send_interceptor(send_callback: (request: XMLHttpRequest, open_args: Parameters<typeof XMLHttpRequest.prototype.open>, send_args: Parameters<typeof XMLHttpRequest.prototype.send>) => any): Promise<void>;
2202
+ /**
2203
+ * Intercepts someone reading `response`, `responseText` and `responseXML` on an XMLHttpRequest
2204
+ * @param read_callback Called everytime a response is read from an XMLHttpRequest which has been opened and sent - it doesn't have to have received a response yet so please keep in mind that you might have to pass through `undefined` if `orig_result` is `undefined`.
2205
+ */
2206
+ export function xhr_read_interceptor(read_callback: (request: XMLHttpRequest, open_args: Parameters<typeof XMLHttpRequest.prototype.open>, send_args: Parameters<typeof XMLHttpRequest.prototype.send>, orig_result: string | undefined, property_name: "responseText" | "response" | "responseXML") => string): Promise<void>;
2207
+ export function default_rp_fixes(orig_url?: string | undefined): Promise<void>;
2208
+ export function rp_relativify_history(orig_url_with_trailing_slash: string): void;
2209
+ export function rp_relativify_fetch(orig_url_with_trailing_slash: string): void;
2210
+ export function rp_relativify_xhr(orig_url_with_trailing_slash: string): void;
2211
+ /**
2212
+ * Recursively sorts the keys in an object (NOT in-place, returns a new object). Do not provide objects containing anything other than primitives or other objects. Do not provide objects that have cyclical values.
2213
+ */
2214
+ export function sort_obj<T>(maybe_obj: T): any;
2215
+ /**
2216
+ * Tries to figure out the tenant's market (`TwoLetterMarket` for new integrations) through various means.
2217
+ *
2218
+ * 1. Checks if there is a market in one of the url segments (www.tentant.se/foo/se/bar)
2219
+ * 2. Checks if the market is specified in the tenant's domain name (www.tenant-se.com)
2220
+ * 3. Checks the toplevel domain (www.tenant.se/foo/bar)
2221
+ *
2222
+ * @param allowed_markets An array the possible markets for the tenant.
2223
+ * Dont forget to specify the allowed market as const (`["se", "en"] as const`) to get the best typing
2224
+ * @param url Specify this to overide the url to check, defaults to the current url
2225
+ * @param tenant The tenant's name
2226
+ * @returns If a market specified in `allowed_markets`was found that is returned, `undefined` otherwise
2227
+ */
2228
+ export function standard_get_market<T extends readonly string[]>(allowed_markets: T, url?: string, tenant?: string): T[number] | undefined;
2229
+ /**
2230
+ * Listens to localstorage changes with `setItem` and direct assignment.
2231
+ * @param listener a function to invoke every time something in the localStorage changes. It gets two arguments: key and value, key being the key of the item set and value being the value of the item set.
2232
+ */
2233
+ export function listenToLocalStorage(listener: (key: string, value: string) => void): void;
2234
+ /**
2235
+ * Timeout a promise after `ms` milliseconds.
2236
+ * If the promise is timed out this function will return `undefined` and not throw.
2237
+ */
2238
+ export function timeout_promise<T>(promise: Promise<T>, ms: number): Promise<Awaited<T> | undefined>;
2239
+ /**
2240
+ * Uses the default Voyado ID that is used in Voyado email recommendations.
2241
+ */
2242
+ export const use_voyado_id: () => void | undefined;
2243
+ type ButtonProps = Omit<Partial<JSX.IntrinsicElements["button"]>, "type"> & {
2244
+ class?: string;
2245
+ };
2246
+ export function DefaultViewMoreButton({
2247
+ children,
2248
+ ...attributes
2249
+ }: ButtonProps): HTMLButtonElement;
2250
+ export function GeneralSideSlidein({
2251
+ title_,
2252
+ children,
2253
+ CloseIcon
2254
+ }: {
2255
+ title_: IPNS<string>;
2256
+ children: HTMLElement | HTMLElement[];
2257
+ CloseIcon: () => HTMLElement | SVGElement;
2258
+ }): Promise<{
2259
+ close_: VoidFunction;
2260
+ on_close_: (fn: VoidFunction) => number;
2261
+ }>;
2262
+ export function GeneralSizeSelector({
2263
+ title_,
2264
+ items_,
2265
+ out_of_stock_text_,
2266
+ CloseIcon
2267
+ }: {
2268
+ title_: IPNS<string>;
2269
+ out_of_stock_text_: IPNS<string>;
2270
+ items_: {
2271
+ id_: string;
2272
+ size_name_: string;
2273
+ is_available_: boolean;
2274
+ }[];
2275
+ CloseIcon: () => HTMLElement | SVGElement;
2276
+ }): Promise<string | void>;
2277
+ type PlaceholderProps = Omit<Partial<JSX.IntrinsicElements["div"]>, "style"> & {
2278
+ /** Any extra classes togheter with the default `depict-placeholder` class */
2279
+ class?: string;
2280
+ /** Convinence prop for setting element width */
2281
+ width?: string;
2282
+ /** Convinence prop for setting element height */
2283
+ height?: string;
2284
+ /** Will override the usage of width & height */
2285
+ style?: string;
2286
+ };
2287
+ type PlaceholderImageProps = Omit<PlaceholderProps, "width" | "height" | "style"> & {
2288
+ aspect_ratio: number;
2289
+ };
2290
+ /**
2291
+ * A Placeholder with shimmering animation.
2292
+ * For text you can use `height="1em"`.
2293
+ * For specific number of characters use `ch`, ex: `width="7ch"`
2294
+ */
2295
+ export const Placeholder: ({
2296
+ width,
2297
+ height,
2298
+ class: extra_classes,
2299
+ style,
2300
+ ...attributes
2301
+ }: PlaceholderProps) => HTMLElement;
2302
+ /**
2303
+ * A wrapper of Placeholder with full width and maintained aspect ratio.
2304
+ * @see {@link Placeholder}
2305
+ */
2306
+ export const ContainedPlaceholderImage: ({
2307
+ aspect_ratio,
2308
+ ...attributes
2309
+ }: PlaceholderImageProps) => HTMLElement;
2310
+ export const RecommendationContainer: (title?: string | HTMLElement, surface_classes?: string[]) => HTMLElement;
2311
+ export const RightChevron: () => HTMLElement;
2312
+ export const LeftChevron: () => HTMLElement;
2313
+ export type ColorObj = {
2314
+ /** the value passed as a css color */
2315
+ value: string;
2316
+ /** if specified, it's used as a title on hover */
2317
+ label?: string;
2318
+ /** Allow for arbitrary data to be passed */
2319
+ [key: string]: any;
2320
+ };
2321
+ interface ColorPickerProps {
2322
+ /** An array of colors that can be selected */
2323
+ colors: ColorObj[];
2324
+ onSelect: (color: ColorObj) => unknown;
2325
+ /**
2326
+ * Called everytime a color is hovered
2327
+ */
2328
+ onHoverUpdate?: (color: ColorObj, hovering: boolean) => unknown;
2329
+ /**
2330
+ * The color value to be initially selected. Can be omitted for no color to be selected.
2331
+ * If multiple colors use the same hex value, the label can also be specified (using a ColorObj)
2332
+ */
2333
+ initialColor?: string | ColorObj;
2334
+ /**
2335
+ * Enabled hovering preview. When true `onSelect` will be called with a new color when it's hovered,
2336
+ * then reverts back to the last clicked color when hovering is stopped
2337
+ * */
2338
+ selectOnHover?: boolean;
2339
+ /**
2340
+ * If set to true only `onSelect` will be called when an item is clicked
2341
+ */
2342
+ dontSetActiveOnClick?: boolean;
2343
+ /**
2344
+ * If only circles should be returned and not the container element
2345
+ */
2346
+ onlyCircles?: boolean;
2347
+ }
2348
+ /**
2349
+ * A color selector, that calls onSelect when a color is clicked and optionally on hover as well.
2350
+ */
2351
+ export function createColorPicker({
2352
+ colors,
2353
+ initialColor,
2354
+ onSelect,
2355
+ selectOnHover,
2356
+ onHoverUpdate,
2357
+ dontSetActiveOnClick,
2358
+ onlyCircles
2359
+ }: ColorPickerProps): {
2360
+ setActiveIndex: (index: number) => void | undefined;
2361
+ ColorPicker(): HTMLElement;
2362
+ };
2363
+ /**
2364
+ * For example how to use, check /src/glitter/main.tsx
2365
+ * Warning: Don't use margins for the element you want to expand, since the animation will look janky
2366
+ * EDIT: above no longer applies if you only have one element that you want to expand
2367
+ */
2368
+ export const useExpandingContainer: ({
2369
+ duration,
2370
+ delay
2371
+ }?: {
2372
+ duration?: number;
2373
+ delay?: number;
2374
+ }) => {
2375
+ ExpandingContainer: ({
2376
+ children
2377
+ }: {
2378
+ children?: Elem | Elem[] | undefined;
2379
+ }) => HTMLElement;
2380
+ expand: (expanding_delay?: any, time_to_expand?: any) => Promise<Animation | undefined>;
2381
+ collapse: (collapsing_delay?: any, time_to_collapse?: any) => Promise<Animation | undefined>;
2382
+ };
2383
+ export const resize_base_url: string;
2384
+ export const is_safari: boolean;
2385
+ /**
2386
+ * make_sizes_setter attaches a ResizeObserver to what_to_watch and returns a function to call to set the `sizes` attribute of the provided el_to_resize attribute to the width of `what_to_watch` on every ResizeObserver callback
2387
+ * @param what_to_watch Element to watch resizing of
2388
+ * @param sizes_communicator the IPNS which communicates the sizes. You can provide your own to get access to the watched sizes. This is usable i.e.to set "width" and "height" attributes to satisfy lighthouse flawed anti layout shift suggestions
2389
+ * @param resolution_factor a factor to multiply the target-to-display resolution with
2390
+ * @return A function that will set the `sizes` atribute of the provided element to the size of `what_to_watch`, continuously
2391
+ */
2392
+ export function make_sizes_setter(what_to_watch: HTMLElement, sizes_communicator?: IPNS<number>, resolution_factor?: number): (el_to_resize: HTMLSourceElement | HTMLImageElement) => Promise<void>;
2393
+ /**
2394
+ * This function returns a function that can be used as JSX component.
2395
+ * It builds upon `make_sizes_setter` and uses it to set the `sizes` attribute of <source> and a fallback <img> tag that it creates.
2396
+ * @param what_to_watch The Element representative of all other images which size will be used to determine the required image sizes for the other images.
2397
+ * @param set_dataset Whether to set `img.src` or `img.dataset.src`. If you're using Lazyfier (builtin to Pro_Slider) the latter is better. Defaults to true.
2398
+ * @param formats An array of formats supported by the backends "ResizeImage" to allow the browser to use
2399
+ * @param resolutions An array of resolutions to generate a srcset for
2400
+ * @param sizes_communicator IPNS of which the resolution sets the `sizes` attribute on the images
2401
+ * @param sizes_setter_ a sizes setter returned by make_sizes_setter, you can provide one if you created it before creating the images
2402
+ * @param resolution_factor a factor to multiply the target-to-display resolution with
2403
+ * @param market_ market to append to ResizeImage proxy, see discussion here: https://depictaiworkspace.slack.com/archives/C02KVDZ8YHZ/p1649162060750759?thread_ts=1649152089.815529&cid=C02KVDZ8YHZ. It's opt-in but should always be set for integrations that have very many images (like a million+)
2404
+ *
2405
+ * @example Per surface:
2406
+ * `const SourcesetComponent = make_sourceset_component(first_canvas, true, ["webp", "png", "tiff"]);`
2407
+ * and then instead of your <img> tags: `<SourcesetComponent data-src={d.image_url} class="image" />`
2408
+ */
2409
+ export function make_sourceset_component({
2410
+ what_to_watch,
2411
+ set_dataset,
2412
+ formats,
2413
+ resolutions,
2414
+ sizes_communicator,
2415
+ resolution_factor,
2416
+ market_,
2417
+ sizes_setter_
2418
+ }?: {
2419
+ what_to_watch?: HTMLElement;
2420
+ set_dataset?: boolean;
2421
+ formats?: string[];
2422
+ resolutions?: number[];
2423
+ sizes_communicator?: IPNS<number>;
2424
+ resolution_factor?: number;
2425
+ market_?: string;
2426
+ sizes_setter_?: ReturnType<typeof make_sizes_setter>;
2427
+ }): (image_options: Partial<JSX.IntrinsicElements["img"]> & {
2428
+ class?: string;
2429
+ }) => HTMLElement;
2430
+ /**
2431
+ * Adds query parameters from the `params` parameter to the `base` url.
2432
+ * Guaranteed to be correctly escaped and not doubled and perfectly formatted
2433
+ * @param base base url, can be relative
2434
+ * @param params an object like `{'param1': 'value'}` that will lead to `?param1=value` on the url
2435
+ * @return an absolute URL with the added query parameters
2436
+ */
2437
+ export function make_url_with_query_params(base: string, params: {
2438
+ [key: string]: any;
2439
+ }): string;
2440
+ export interface ImageOptions extends Partial<HTMLImageElement> {
2441
+ aspect_ratio: number;
2442
+ class?: string;
2443
+ rendering_options?: RR_Options<any>;
2444
+ srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2445
+ alt: string;
2446
+ remove_on_error?: boolean;
2447
+ /**
2448
+ * If true, inserts grey placeholder svg's before the image lazyloader and the sourceset component add the real source
2449
+ */
2450
+ init_with_placeholder?: boolean;
2451
+ }
2452
+ /**
2453
+ * Contained image gives an image (a container with) intrinsic size of the given aspect ratio, filling out available space.
2454
+ * It means that images with different aspect ratios will all take the same amount of space
2455
+ * and the sides where it doesn't fit the aspect ratio will be filled with transparent.
2456
+ * It makes sure the images doesn't get squished like setting `width` and `height` would do.
2457
+ * @param aspect_ratio The aspect ratio of the image, i.e. 4/3 = 1,3̅
2458
+ * @param alt Alt text of the image
2459
+ * @param remove_on_error Whether to remove the image if loading fails
2460
+ * @param rendering_options The rendering options. Please always provide this, it's only optional for compatibility reasons.
2461
+ * You should provide the `rendering_options` to the second argument, InfoForProcessing, provided to a template or preprocessor.
2462
+ * When provided to a postprocessor of a recommendation-renderer it will be the third argument
2463
+ * If you provide this, ContainedImage will automatically use `make_sourceset_component`
2464
+ * and the image resizing proxy to get you responsive images in a modern format (webp).
2465
+ * @param srcset_opts The options passed to `make_sourceset_component`, only used if `rendering_options` is set.
2466
+ * @param Everything else: attributes on the <img> tag
2467
+ * @returns It depends on options and build target. But it's always one HTMLElement.
2468
+ */
2469
+ export const ContainedImage: ({
2470
+ init_with_placeholder,
2471
+ ...options
2472
+ }: ImageOptions) => HTMLElement;
2473
+ type HoverImageOptions = ImageOptions & {
2474
+ mobile_touch_hover?: boolean;
2475
+ extra_container_class?: string;
2476
+ main_extra_classes?: string;
2477
+ second_src?: string;
2478
+ second_srcset?: string;
2479
+ second_srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2480
+ fade_length_seconds?: number;
2481
+ /** The minimum amount of time for a touch to be considered a link click */
2482
+ navigation_minimum_ms?: number;
2483
+ };
2484
+ export const ContainedHoverImage: ({
2485
+ second_src,
2486
+ second_srcset,
2487
+ second_srcset_opts,
2488
+ fade_length_seconds,
2489
+ mobile_touch_hover,
2490
+ navigation_minimum_ms,
2491
+ ...options
2492
+ }: HoverImageOptions) => HTMLElement;
2493
+ /**
2494
+ * Shallowly converts all keys in an object from snake_case to camelCase.
2495
+ * Does not support symbol keys.
2496
+ *
2497
+ * @param obj the object. It will be cloned and not modified in-place.
2498
+ */
2499
+ export function camelCasifyObject<T extends {
2500
+ [key: string]: any;
2501
+ }, X extends T = T>(obj: T): X;
2502
+ /**
2503
+ * Shallowly converts all keys in an object from camelCase to snake_case.
2504
+ * Does not support symbol keys.
2505
+ * @param obj the object. It will be cloned and not modified in-place.
2506
+ */
2507
+ export function snakeCasifyObject<T extends {
2508
+ [key: string]: any;
2509
+ }, X extends T = T>(obj: T): X;
2510
+ /**
2511
+ * Converts RGB to HSL
2512
+ * Source of function: https://www.30secondsofcode.org/js/s/rgb-to-hsl
2513
+ */
2514
+ export function rgb_to_hsl(r: number, g: number, b: number): readonly [number, number, number];
2515
+ /**
2516
+ * Converts HSL to RGB
2517
+ * Source of function: https://www.30secondsofcode.org/js/s/hsl-to-rgb
2518
+ */
2519
+ export function hsl_to_rgb(h: number, s: number, l: number): readonly [number, number, number];
2520
+ /**
2521
+ * Converts HSV (or HSB, it's the same) to RGB.
2522
+ * Source of function: https://www.30secondsofcode.org/js/s/hsb-to-rgb/
2523
+ */
2524
+ export function hsb_to_rgb(h: number, s: number, b: number): readonly [number, number, number];
2525
+ /**
2526
+ * Calculates the relative luminance of a RGB color
2527
+ * Source: https://gist.github.com/jfsiii/5641126
2528
+ */
2529
+ export function relative_luminance_from_rgb(R8bit: number, G8bit: number, B8bit: number): number;
2530
+ /**
2531
+ * Converts a hex string to an RGB array
2532
+ * Source: https://stackoverflow.com/a/39077686
2533
+ */
2534
+ export function hex_to_rgb(hex: string): [number, number, number] | null;