@depict-ai/utilishared 1.0.12 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +130 -130
  2. package/dist/index.d.ts +2423 -2429
  3. package/dist/main.js +147 -336
  4. package/dist/module.js +148 -325
  5. package/package.json +9 -3
package/dist/index.d.ts CHANGED
@@ -1,2430 +1,2424 @@
1
1
  /// <reference path="../jsx.d.ts" />
2
- import { EUnavailabilityType } from "@depict-ai/types/api/TrackV2Request";
3
- export const version = "1.0.12";
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: [
212
- url: ConstructorParameters<typeof AutoReconnectingWS>[0],
213
- protocols?: ConstructorParameters<typeof AutoReconnectingWS>[1],
214
- options?: ConstructorParameters<typeof AutoReconnectingWS>[2] & Partial<{
215
- initial_retry_ms: number;
216
- }>
217
- ]);
218
- }
219
- /**
220
- * Returns a random string
221
- * @return A random string, containing a-z, 0-9 and occasionally a dot (`.`)
222
- */
223
- export function random_string(): string;
224
- export function make_random_classname(): string;
225
- export const base_url: string;
226
- export type event_types = "page_view" | "click" | "add_to_cart" | "purchase" | "element_visible";
227
- 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"];
228
- export type depict_body = Partial<{
229
- [K in (typeof allowed_keys)[number]]: any;
230
- }>;
231
- export type depict_payload = depict_body[];
232
- type any_properties = {
233
- [key: string]: any;
234
- };
235
- export type noisy_depict_payload = (depict_body & any_properties)[];
236
- export const filter_depict_payload: (payload: noisy_depict_payload) => depict_payload | undefined;
237
- export const send_websocket: (bodies: depict_payload) => Promise<void | undefined>;
238
- export const send_depict_unfiltered: (payload: depict_payload, use_ws?: any) => boolean | Promise<void | undefined> | undefined;
239
- export const foolproof_send_beacon: (url: string, payload: {
240
- [key: string]: any;
241
- }) => boolean | undefined;
242
- export const send_depict: (payload: noisy_depict_payload, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
243
- export let get_depict_id: () => string;
244
- export let get_user_id: () => string;
245
- export let get_session_id: () => string | undefined;
246
- export const set_depict_id_fn: (newfn: () => string) => (() => string) | undefined;
247
- export const set_user_id_fn: (newfn: () => string) => (() => string) | undefined;
248
- export const set_session_id_fn: (newfn: () => string) => (() => string) | undefined;
249
- export type TrackingEventContextData = {
250
- user_id: string;
251
- dsid: string;
252
- session_id?: string;
253
- url: string;
254
- document_width: number;
255
- document_referrer: string;
256
- };
257
- export const get_tracking_event_context_data: () => TrackingEventContextData;
258
- /**
259
- * Sends a depict tracking event with prefilled data
260
- */
261
- export const depict_prefilled: (vars: Partial<{
262
- type: any;
263
- detail: any;
264
- url: any;
265
- currency: any;
266
- tenant: any;
267
- market: any;
268
- user_id: any;
269
- session_id: any;
270
- product_id: any;
271
- entity_identifiers: any;
272
- entity_price: any;
273
- document_referrer: any;
274
- document_width: any;
275
- attribution_id: any;
276
- recommendation_id: any;
277
- click_location: any;
278
- ab_test_group: any;
279
- variant_ids: any;
280
- dsid: any;
281
- transaction_id: any;
282
- error_type: any;
283
- recommendation_type: any;
284
- search_result_id: any;
285
- product_listing_result_id: any;
286
- }> & {
287
- [key: string]: any;
288
- }, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
289
- export const depict_click: (vars: Partial<{
290
- type: any;
291
- detail: any;
292
- url: any;
293
- currency: any;
294
- tenant: any;
295
- market: any;
296
- user_id: any;
297
- session_id: any;
298
- product_id: any;
299
- entity_identifiers: any;
300
- entity_price: any;
301
- document_referrer: any;
302
- document_width: any;
303
- attribution_id: any;
304
- recommendation_id: any;
305
- click_location: any;
306
- ab_test_group: any;
307
- variant_ids: any;
308
- dsid: any;
309
- transaction_id: any;
310
- error_type: any;
311
- recommendation_type: any;
312
- search_result_id: any;
313
- product_listing_result_id: any;
314
- }> & {
315
- [key: string]: any;
316
- }) => boolean | Promise<void | undefined> | undefined;
317
- export const depict_add_to_cart: (vars: Partial<{
318
- type: any;
319
- detail: any;
320
- url: any;
321
- currency: any;
322
- tenant: any;
323
- market: any;
324
- user_id: any;
325
- session_id: any;
326
- product_id: any;
327
- entity_identifiers: any;
328
- entity_price: any;
329
- document_referrer: any;
330
- document_width: any;
331
- attribution_id: any;
332
- recommendation_id: any;
333
- click_location: any;
334
- ab_test_group: any;
335
- variant_ids: any;
336
- dsid: any;
337
- transaction_id: any;
338
- error_type: any;
339
- recommendation_type: any;
340
- search_result_id: any;
341
- product_listing_result_id: any;
342
- }> & {
343
- [key: string]: any;
344
- }) => boolean | Promise<void | undefined> | undefined;
345
- export type ConsentObj = {
346
- marketing: boolean;
347
- necessary: boolean;
348
- preferences: boolean;
349
- statistics: boolean;
350
- };
351
- export function get_cookie(cookie_name: string): string | undefined;
352
- export function Promise_Any<T>(promises: (T | PromiseLike<T>)[] | Iterable<T | PromiseLike<T>>): Promise<T>;
353
- /**
354
- * Broadcasts the product id of the current page to a BroadcastChannel `right_click_attribution`.
355
- * 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.
356
- */
357
- export function broadcast_product_id(product_id: string): Promise<void>;
358
- /**
359
- * 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)
360
- * @param elements Elements that event listeners will be added on
361
- * @param display The display to take the product_id from
362
- * @param info InfoForProcessing to get Tenant instance out of
363
- * @return `elements` 1:1
364
- */
365
- 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;
366
- /**
367
- * This is the event handler for the new tab tracking function (add_new_tab_listener)
368
- * @param e Click event
369
- * @param product_id product_id of clicked product
370
- * @return A promise resolving to void after 60s or when the product id was broadcasted
371
- */
372
- export function contextmenu_callback(e: Event, product_id: string): Promise<void>;
373
- /**
374
- * Make parts of a type optional
375
- *
376
- * From: https://github.com/Microsoft/TypeScript/issues/25760#issuecomment-614417742
377
- */
378
- type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>;
379
- export class ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
380
- constructor(opts: {
381
- element_: ElemType;
382
- selector_: SelectorType;
383
- disconnector_: Disconnector;
384
- mutation_record_?: MutationRecord;
385
- event_?: ListenerNames;
386
- });
387
- }
388
- export interface ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
389
- element: ElemType;
390
- selector: SelectorType;
391
- disconnector: Disconnector;
392
- mutation_record?: MutationRecord;
393
- event?: ListenerNames;
394
- }
395
- /**
396
- * Element.querySelectorAll is broken in Chrome 37-latest, use this instead.
397
- * Related bug: https://bugs.chromium.org/p/chromium/issues/detail?id=1286047
398
- * @param element Quite broadly anything you'd normaly call querySelectorAll on, including "null"
399
- * @param selector The selector to search for
400
- * @return Stock return value
401
- */
402
- export function patched_querySelectorAll<T extends Element>(element: Element | Document | DocumentFragment | null, selector: string): NodeListOf<T> | T[] | undefined;
403
- export interface ElementObserver {
404
- /**
405
- * Immediately calls the callback with an ElementObserverEvent for nodes existing in the DOM that match the provided selector OR are the selector,
406
- * also calls the callback with an ElementObserverEvent whenever ANYTHING in the DOM occurs that makes an element match the provided selector.
407
- * @param selector Selector string or element to listen for
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
- onexists: EO_listener_also_taking_els;
411
- /**
412
- * Dispatches an ElementObserverEvent whenever a node is added to 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
- oncreation: EO_listener_also_taking_els;
417
- /**
418
- * Dispatches an ElementObserverEvent whenever a node is removed from the DOM that matches the specified selector OR is the selector.
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
- onremoved: EO_listener_also_taking_els;
423
- /**
424
- * Dispatches an ElementObserverEvent whenever a node that matches the specified selector or its children change in the DOM.
425
- * @param selector CSS selector or element to observe
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
- onchange: EO_listener;
429
- /**
430
- * Immediately calls the callback with an ElementObserverEvent on nodes that match the provided selector OR are the selector.
431
- * @param selector Selector string or element to look for in the DOM
432
- * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
433
- */
434
- ifexists: EO_listener_also_taking_els;
435
- /**
436
- * See docs for observer.onexists. Will return a Promise that resolves to the element out of the first call of an observer.onexists callback.
437
- * @param selector Selector string or element to wait for
438
- * @param timeout timeout to stop listening and resolve the Promise with `undefined`
439
- */
440
- wait_for_element: <ElemType extends HTMLElement = HTMLElement>(selector: string | ElemType, timeout?: number) => Promise<ElemType>;
441
- /**
442
- * 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
443
- * @param listener one of the possible functions on ElementObserver that start with "on", without the "on". So "creation", "change", "exists" or "removed"
444
- * @param selector String containing CSS selector
445
- * @param timeout timeout to stop listening and resolve the Promise with `undefined`
446
- */
447
- 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>;
448
- }
449
- export class ElementObserver {
450
- #private;
451
- constructor(options?: {
452
- territory?: HTMLElement | Document | DocumentFragment;
453
- });
454
- }
455
- type EO_listener = <ElemType extends HTMLElement = HTMLElement>(selector: string, callback: ObserverCallbackFunction<ElemType>) => Disconnector;
456
- type EO_listener_also_taking_els = <ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode>(selector: SelectorType, callback: ObserverCallbackFunction<ElemType, SelectorType>) => Disconnector;
457
- type ListenerNames = "exists" | "creation" | "removed" | "change";
458
- type ObserverCallbackFunction<ElemType extends CallbackableNode, SelectorType extends string | CallbackableNode = string | CallbackableNode> = (event: ElementObserverEvent<ElemType, SelectorType>) => any;
459
- export type Disconnector = () => unknown;
460
- type CallbackableNode = Element | Text | Comment;
461
- /**
462
- * 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.
463
- */
464
- export const observer: ElementObserver;
465
- /**
466
- * 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
467
- * @param numSteps How many steps (notifications) there should be between 0 and 100% intersection
468
- * @return Stuff to give to IntersectionObserver
469
- */
470
- export function buildThresholdList(numSteps: number): number[];
471
- /**
472
- * A Post processor for Recommendation renderer to add impression tracking to all displays
473
- */
474
- export const impression_tracking_post_processor: RR_PostProcessor<any>;
475
- interface ImpressionTrackingOptions {
476
- /** The element to observe for impressions. */
477
- element: HTMLElement;
478
- /** The impression data to send to the api (this is combined with context data) */
479
- data: ExplicitImpressionEventData;
480
- /** When true the element will be observed by the IntersectionObserver only after it's inserted into the DOM.
481
- * Sometimes with a pollyfilled IntersectionObserver it ignores elements that are not in the DOM yet.
482
- * Defaults to true.
483
- * */
484
- wait_for_dom_insertion?: boolean;
485
- }
486
- /**
487
- * Registers the passed element for impression tracking.
488
- * The element will be observed for intersection with the viewport.
489
- * Also handles sending the impression event.
490
- *
491
- * @return A function to stop observing the element for impressions
492
- */
493
- export const impression_track_element: ({ element, data, wait_for_dom_insertion, }: ImpressionTrackingOptions) => () => void;
494
- /** The start and end visibility threshold for an intersection to count as an impression */
495
- export let impression_threshold: number[];
496
- export const set_impression_threshold: (start: number, end: number) => number[];
497
- /** The minimum duration the element has to be visible above the thresholds before it counts as an impression */
498
- export const has_to_be_intersecting_for = 500;
499
- /** What explicit information is needed to form an ImpressionEvent */
500
- export type ExplicitImpressionEventData = {
501
- recommendation_type?: string;
502
- entity_price?: number;
503
- market?: string;
504
- tenant?: string;
505
- product_id?: string;
506
- } & ({
507
- recommendation_id: string;
508
- } | {
509
- search_result_id: string;
510
- } | {
511
- product_listing_result_id: string;
512
- } | {
513
- suggestions_result_id: string;
514
- });
515
- /** What an impression event looks like when sent to the api */
516
- export type ImpressionEvent = {
517
- /** The type for impression events should be element_visible */
518
- type: "element_visible";
519
- } & (ExplicitImpressionEventData | TrackingEventContextData);
520
- /**
521
- * Sends an impression event to the api.
522
- *
523
- * Impression events always use websockets.
524
- */
525
- export const send_impression_event: (data: Optional<ImpressionEvent, "type">) => void;
526
- /**
527
- * 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
528
- * @param {HTMLElement} a_element - The element to listen on the "click event"
529
- * @param {string} product_id - A unique identifier for the product which can be used to rerecognize it on the product page
530
- * @param {string} recommendation_id - The recommendation ID of the recommendation
531
- * @param {Function} additional_listener - An additional function to execute onclick
532
- */
533
- export function bind_tracking_to_link(a_element: Element, product_id: string, recommendation_id: string, additional_listener?: Function): ((e: Event) => void) | undefined;
534
- export type A2CTrackingFunction = (product_id: string, recommendation_id: string, was_unmatching: boolean, event: Event) => any;
535
- /**
536
- * 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
537
- * @param {HTMLElement} button - The element to listen on the "click event"
538
- * @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
539
- * @param {A2CTrackingFunction} tracking_fn - A function which gets executed on click of button
540
- * @param {Boolean} [unmatching_tracking] - also call tracking_fn on products not found in localStorage.
541
- */
542
- 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>;
543
- type after_navig_fn = (arg0: Parameters<typeof history.replaceState | typeof history.pushState>, what_happened: "replaceState" | "pushState") => any;
544
- /**
545
- * AsyncIterable which resolves with the new href every time location.href changes
546
- */
547
- export const stateless_href_change_ipns: IPNS<string>;
548
- /**
549
- * AsyncIterable which resolves when you await it with the current href and then once every time it changes
550
- */
551
- export const href_change_ipns: IPNS<string>;
552
- /**
553
- * Functions to instantly (synchronously) call when a "popstate" event occurs, before the href_change_ipns' resolve
554
- * 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.
555
- */
556
- 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>;
557
- export function on_next_navigation(callback: (new_href: string) => void): Promise<void>;
558
- /**
559
- * 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.
560
- * Please also consider adding a listener to the `popstate` event (`window.addEventListener("popstate", handler)`) to cover ALL navigation possibilities.
561
- * @param after_navigation Function to call after history.replaceState and history.pushState
562
- * @param replace_replaceState=true Whether to call the function also on history.replaceState.
563
- * @return Void
564
- */
565
- export function history_replacer(after_navigation: after_navig_fn, replace_replaceState?: boolean): Promise<void>;
566
- interface TrackingData {
567
- /** The active market, if any */
568
- market?: string;
569
- /** The merchant id */
570
- tenant: string;
571
- }
572
- export interface PageViewEventData extends TrackingData {
573
- /** If the page is a pdp, include the product_id */
574
- product_id?: string;
575
- }
576
- export interface PageViewTrackingData extends TrackingData {
577
- /** A function that returns the product_id of the product being displayed on href,
578
- * if the href points to a PDP */
579
- get_product_id: (href: string) => string | undefined | Promise<string | undefined>;
580
- }
581
- /**
582
- * Sends a page_view event to Depict tracking if it hasn't been sent yet for the current page url
583
- * 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
584
- * @return A promise resolving to void
585
- */
586
- export function send_page_view_if_needed(data: PageViewEventData): Promise<void>;
587
- /**
588
- * Sends a page_view event to Depict tracking, and another one any time the page URL changes
589
- */
590
- export function send_page_view_on_navigation(data: PageViewTrackingData): Promise<void>;
591
- export function make_tracker_send_to_depict(ga_tracker: any, append_to_url?: string): void;
592
- export function create_ga_queue(): void;
593
- /**
594
- * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
595
- * @return Current consent status, whether selected or not
596
- */
597
- export const cookiebot_get_consent: () => any;
598
- /**
599
- * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
600
- * @return Consent status, once selected
601
- */
602
- export function cookiebot_wait_for_consent(): Promise<boolean>;
603
- /**
604
- * Returns an IPNS that resolves with initial consent when Cookiebot has loaded, or immediately if a consent cookie already exists.
605
- * As well as a new consent object every time the consent status has changed
606
- * @return An IPNS resolving to the consent object
607
- */
608
- export function cookiebot_get_cookie_ipns(): IPNS<ConsentObj>;
609
- /**
610
- * Anonymize Depict id until required consent level has been given through Cookiebot.
611
- *
612
- * This can be used for tenants using Cookiebot for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
613
- * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
614
- * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
615
- *
616
- * 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}.
617
- */
618
- export const init_cookiebot_tracking: (anon_id?: any) => Promise<void | undefined>;
619
- declare global {
620
- interface Window {
621
- Cookiebot?: {
622
- name: string;
623
- consented: boolean;
624
- declined: boolean;
625
- changed: boolean;
626
- hasResponse: boolean;
627
- consentID: string;
628
- consent: Consent;
629
- isOutsideEU: boolean;
630
- isOutOfRegion: boolean;
631
- host: string;
632
- domain: string;
633
- currentPath: string;
634
- doNotTrack: boolean;
635
- consentLevel: string;
636
- isRenewal: boolean;
637
- forceShow: boolean;
638
- dialog: null;
639
- responseMode: string;
640
- serial: string;
641
- scriptId: string;
642
- scriptElement: ScriptElement;
643
- whitelist: any[];
644
- cookieList: CookieList;
645
- pathlist: any[];
646
- userIsInPath: boolean;
647
- cookieEnabled: boolean;
648
- versionChecked: boolean;
649
- versionRequested: boolean;
650
- version: number;
651
- latestVersion: number;
652
- isNewVersion: boolean;
653
- CDN: string;
654
- source: string;
655
- retryCounter: number;
656
- frameRetryCounter: number;
657
- bulkConsentFrameRetryCounter: number;
658
- setOnloadFrameRetryCounter: number;
659
- optOutLifetime: number;
660
- consentLifetime: null;
661
- framework: string;
662
- hasFramework: boolean;
663
- frameworkBlocked: boolean;
664
- frameworkLoaded: boolean;
665
- iframeReady: boolean;
666
- iframe: Iframe;
667
- bulkconsent: null;
668
- bulkresetdomains: any[];
669
- bulkconsentsubmitted: boolean;
670
- isbulkrenewal: boolean;
671
- wipe: Wipe;
672
- consentUTC: Date;
673
- IABConsentString: string;
674
- GACMConsentString: string;
675
- dataLayerName: string;
676
- loaded: boolean;
677
- autoblock: boolean;
678
- mutationObserver: null;
679
- mutationCounter: number;
680
- mutationFallback: boolean;
681
- mutationFallbackDocAttributes: any[];
682
- mutationHandlerFallbackCharsetLoaded: boolean;
683
- mutationAppName: string;
684
- mutationEventListeners: any[];
685
- mutationOnloadEventListeners: any[];
686
- mutateEventListeners: boolean;
687
- mutationHandlerFirstScript: null;
688
- postPonedMutations: any[];
689
- nonAsyncMutations: any[];
690
- deferMutations: any[];
691
- geoRegions: any[];
692
- userCountry: string;
693
- userCulture: string;
694
- windowOnloadTriggered: boolean;
695
- botDetectionDisabled: boolean;
696
- regulations: Regulations;
697
- regulationRegions: RegulationRegions;
698
- commonTrackers: CommonTrackers;
699
- configuration: Configuration;
700
- inlineConfiguration: null;
701
- processLinkClickCounter: number;
702
- performanceEntriesCounter: number;
703
- OverrideEventListenersOnloadFired: any[];
704
- OverrideEventListenersOnloadToFire: any[];
705
- fallbackScriptNodes: any[];
706
- fallbackDeferNodes: any[];
707
- };
708
- }
709
- }
710
- export interface CommonTrackers {
711
- domains: Domain[];
712
- }
713
- export interface Domain {
714
- d: string;
715
- c: number[];
716
- }
717
- export interface Configuration {
718
- loaded: boolean;
719
- loadRetry: number;
720
- tags: any[];
721
- trackingDomains: any[];
722
- }
723
- export interface Consent {
724
- stamp: string;
725
- necessary: boolean;
726
- preferences: boolean;
727
- statistics: boolean;
728
- marketing: boolean;
729
- }
730
- export interface CookieList {
731
- cookieTablePreference: any[];
732
- cookieTableStatistics: any[];
733
- cookieTableAdvertising: any[];
734
- cookieTableUnclassified: any[];
735
- }
736
- export interface Iframe {
737
- cookieconsentDataStyleDisplay: string;
738
- mtjQuery171028673205955022363: number;
739
- }
740
- export interface RegulationRegions {
741
- gdpr: string[];
742
- ccpa: string[];
743
- lgpd: string[];
744
- }
745
- export interface Regulations {
746
- gdprApplies: boolean;
747
- ccpaApplies: boolean;
748
- lgpdApplies: boolean;
749
- }
750
- export interface ScriptElement {
751
- }
752
- export interface Wipe {
753
- preferences: boolean;
754
- statistics: boolean;
755
- marketing: boolean;
756
- }
757
- /**
758
- * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
759
- * @return Current consent status, whether selected or not
760
- */
761
- export const optanon_get_consent: () => any;
762
- /**
763
- * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
764
- * @return Consent status
765
- */
766
- export function optanon_wait_for_consent(): Promise<boolean>;
767
- /**
768
- * Returns an IPNS that resolves with initial consent when Optanon has loaded, or immediately if a consent cookie already exists.
769
- * As well as a new consent object every time the consent status has changed
770
- * @return An IPNS resolving to the consent object
771
- */
772
- export function optanon_get_cookie_ipns(): IPNS<ConsentObj>;
773
- /**
774
- * Anonymize Depict id until required consent level has been given through OneTrust's Optanon.
775
- *
776
- * This can be used for tenants using OneTrust for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
777
- * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
778
- * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
779
- *
780
- * 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}.
781
- */
782
- export const init_optanon_tracking: (anon_id?: any) => Promise<void | undefined>;
783
- export const load_gtag: (GA_ID: string, strict?: boolean | undefined) => Promise<void | undefined>;
784
- export const setup_gtag: (GA_ID: string) => void | undefined;
785
- export const gtag_view: <T extends Display>(raw_displays: T[], get_product_id: (url?: string | T | undefined) => string | Promise<string>, more?: {
786
- [key: string]: any;
787
- list_name?: string | undefined;
788
- } | ((display: T) => {
789
- [key: string]: any;
790
- }) | undefined) => Promise<void | undefined>;
791
- export const gtag_click: (product_id: string | number, index: number, more?: object | undefined) => Promise<any>;
792
- export const send_ga: (action: string) => any;
793
- export const setup_ga: (GAID: string) => void | undefined;
794
- export const ga_rec_click: () => any;
795
- export const ga_purchase_click: () => any;
796
- export const insert_styling: (css: string) => Promise<void | undefined>;
797
- /**
798
- * A function meant to use to track the main add to cart button on the product page of an integration.
799
- * * @param tenant instance of `Tenant` class
800
- * @param selector The selector to use to find the button
801
- * @param validator A function that can invalidate the click event before tracking is sent
802
- * @return A `Disconnector` to stop looking for more add to cart buttons to track
803
- */
804
- export const track_a2c: (tenant: Tenant, selector: string, validator?: ((e: Event) => boolean) | undefined) => Disconnector;
805
- /**
806
- * Basically a RecRendererResult with less strict typing
807
- */
808
- export interface Surface<T extends Display> {
809
- elements?: Node_Array;
810
- displays?: T[];
811
- should_stay_inserted?: Promise<boolean>;
812
- }
813
- /**
814
- * Functions existing on ChildNode that are commonly used to insert recommendations into the DOM
815
- */
816
- export type InsertionVerb = "after" | "before" | "replaceWith" | "append" | "prepend" | "replaceChildren";
817
- /**
818
- * Tries to extract a product id from an url.
819
- * The method used to retrive product id used here is very narrow, probably better to use something else instead?
820
- *
821
- * @example normal_get_product_id("www.foo.com/bar/baz.html") // "baz"
822
- *
823
- * @param url The url to check, defaults to `window.location`
824
- * @returns
825
- */
826
- export const normal_get_product_id: (url?: string) => string;
827
- declare global {
828
- interface Document {
829
- depictwashere: boolean;
830
- }
831
- }
832
- /**
833
- * If you need custom market logic that {@link depict_init_with_market_logic} doesn't support then use this function.
834
- *
835
- * Used to initialize an integration-script, this should always be the entrypoint of an integration.
836
- *
837
- * Makes sure that your script doesn't run twice
838
- */
839
- export const depict_init: (callback: () => Promise<void>) => void;
840
- /**
841
- * Initialize an integration-script like {@link depict_init}, but with automatic handling of unsupported and unknown markets.
842
- *
843
- * @param options.extract_market A function that extracts the current market, and if the market is supported, unsupported or unknown
844
- * @param options.callback If `extract_market` returned a supported market, calls `depict_init` with this callback.
845
- * @param options.supported_markets Markets where our script should run, in order to get the best typechecking you should add a `as const`
846
- * modifier to this type like so `["foo", "bar"] as const`.
847
- * @param options.unsupported_markets Markets we are aware of and where our script shouldn't run.
848
- * @param options.preferred_demo_market Market to use on .demo.depict.ai, if an override is needed for all users.
849
- * depict-override-market query parameter will override this behaviour.
850
- *
851
- * ### Behaviour
852
- *
853
- * - market is unsupported - log to console and exit
854
- * - market is unknown - report to sentry and exit
855
- *
856
- * ### Override market
857
- *
858
- * When running in debug mode the market can be overridden by setting a `depict-override-market` query param.
859
- * For example http://tenant.domain?depict-override-market=ez
860
- */
861
- 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;
862
- type IdType = string | undefined | Promise<string | undefined>;
863
- export interface Tenant<ProductId extends IdType> {
864
- TENANT: string;
865
- tenant: string;
866
- MARKET: TwoLetterMarket;
867
- market: TwoLetterMarket;
868
- TYPE: string;
869
- type: string;
870
- GA_ID: string;
871
- gaid: string;
872
- get_product_id: (url?: string) => ProductId extends string | undefined ? string : Promise<string>;
873
- product_id: (url?: string) => string | Promise<string>;
874
- dataset: DOMStringMap;
875
- modify: boolean;
876
- is_debug: boolean;
877
- debug: boolean;
878
- dlog: typeof dlog;
879
- Sentry: typeof Sentry;
880
- catchify: typeof catchify;
881
- err: (...errors: any[]) => undefined;
882
- }
883
- /**
884
- * 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"`
885
- * @param options A object with constructor options
886
- */
887
- export class Tenant<ProductId extends IdType = IdType> {
888
- constructor(options: {
889
- TENANT?: string;
890
- TYPE?: string;
891
- MARKET: TwoLetterMarket;
892
- GA_ID: string;
893
- get_product_id: (url?: string) => ProductId;
894
- current_script_override?: HTMLScriptElement;
895
- pageview_tracking?: boolean;
896
- });
897
- }
898
- /**
899
- * This is a list of alpha-2 country codes plus some two letter combinations commonly used to describe markets
900
- */
901
- 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";
902
- type ImpressionTrackOptions = {
903
- t?: Tenant;
904
- impression_tracking?: false;
905
- } | {
906
- impression_tracking: true;
907
- t: Tenant;
908
- };
909
- type TenantSpecificationOptions = {
910
- t?: Tenant;
911
- tenant: string;
912
- market: string;
913
- get_product_id: (url?: string) => string | Promise<string>;
914
- } | {
915
- t: Tenant;
916
- tenant?: string;
917
- market?: string;
918
- get_product_id?: (url?: string) => string | Promise<string>;
919
- };
920
- type ElementDiscoveryOptions = {
921
- product_selector: string;
922
- product_elements?: null | void | undefined;
923
- } | {
924
- product_selector?: null | void | undefined;
925
- product_elements: HTMLElement[];
926
- };
927
- type A2CButtonDiscoveryOptions = {
928
- a2c_selector: string;
929
- a2c_elements?: null | void | undefined;
930
- } | {
931
- a2c_selector?: null | void | undefined;
932
- a2c_elements: HTMLElement[];
933
- };
934
- /**
935
- * @deprecated Please use DPC instead.
936
- * Does not support ModernDisplays.
937
- */
938
- export const AIO: (options: {
939
- attempt_gtag_view_tracking?: boolean | undefined;
940
- no_gtag?: boolean | undefined;
941
- shade?: boolean | undefined;
942
- always_track_a2c?: boolean | undefined;
943
- get_rec_id?: ((elem: HTMLElement) => string | undefined) | undefined;
944
- get_prod_id?: ((elem: HTMLElement) => (string | undefined) | Promise<string | undefined>) | undefined;
945
- get_ga_prod_id?: ((elem: HTMLElement) => string | undefined | Promise<string | undefined>) | undefined;
946
- click_location_prefix?: ((elem: HTMLElement) => string | undefined) | undefined;
947
- rec_a2c_selector?: string | undefined;
948
- rec_a2c_unbubbled?: boolean | undefined;
949
- get_display?: ((elem: HTMLElement) => Partial<LegacyDisplay> | undefined) | undefined;
950
- } & ImpressionTrackOptions & TenantSpecificationOptions & ElementDiscoveryOptions & A2CButtonDiscoveryOptions, gtag_options?: {
951
- [key: string]: any;
952
- list_name?: string | undefined;
953
- } | undefined) => Promise<{
954
- add_a2c_element: (element: HTMLElement) => void;
955
- add_product_element: (element: HTMLElement) => Promise<void | undefined>;
956
- } | undefined>;
957
- export const paint_red: (element: HTMLElement) => void | undefined;
958
- /**
959
- * A function that attempts to "serialize" an object to a text representation that helps with debugging when using sentry
960
- * @param anything Something to try to serialize - this function is crappy and your mileage may vary
961
- * @param depth How deep to go when recursing
962
- * @return An object that is somehow closer to text (better serializable by sentry) or text
963
- */
964
- export function serialize_object(anything: Object, depth?: number): Object;
965
- export const wait: (delay: number) => Promise<unknown>;
966
- /**
967
- * Fetch with retry and exponetial back off. This is the 2.0 version of the previous Windows proof fetch.
968
- *
969
- * 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
970
- * @param url Url to perform fetch towards
971
- * @param options Fetch options
972
- * @param max_retries Max number of retries, defaults to 10
973
- * @returns The fetch response
974
- */
975
- export function fetch_retry(url: RequestInfo, options?: RequestInit, max_retries?: number): Promise<false | Response>;
976
- type PossibleEndpoint = "general" | "product" | "products" | "category";
977
- type ExclusiveId = {
978
- category_id: string;
979
- product_id?: undefined;
980
- product_ids?: undefined;
981
- } | {
982
- category_id?: undefined;
983
- product_id: string;
984
- product_ids?: undefined;
985
- } | {
986
- category_id?: undefined;
987
- product_id?: undefined;
988
- product_ids: string[];
989
- } | {
990
- category_id?: undefined;
991
- product_id?: undefined;
992
- product_ids?: undefined;
993
- };
994
- type FetchRecsOptions = {
995
- type: string;
996
- user_id?: string;
997
- session_id?: string;
998
- } & ExclusiveId;
999
- /**
1000
- * Fetches recommendations from the depict v2 recommendation api.
1001
- * Will select the endpoint after which id property is given.
1002
- *
1003
- * API Docs: https://api.depict.ai/docs
1004
- *
1005
- * Formerly called get_displays
1006
- */
1007
- export function fetch_recs<T extends Display = Display>(t: Tenant | {
1008
- market: string;
1009
- tenant: string;
1010
- }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<T[]>;
1011
- export function fetch_recs_whole_response<R extends {
1012
- displays: any[];
1013
- }>(t: Tenant | {
1014
- market: string;
1015
- tenant: string;
1016
- }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<R>;
1017
- declare function default_get_fetch_url(type: PossibleEndpoint): string;
1018
- export function ensure_parameter_in_url(url: any, param: any, value: any): string;
1019
- export function querySelectorUpwards(element: Element | HTMLElement, selector: string): Element | null;
1020
- export function html2elems(html: string): NodeListOf<ChildNode>;
1021
- export function html2elem(html: string): Element | null;
1022
- /** On demo domain: make all urls relative */
1023
- export function relativify(url: string | RegExp, also_onchange?: boolean, override_dev_url?: string, stfu?: boolean, also_in_all_shadow_roots?: boolean): void;
1024
- export function querySelectorAllElements<T extends Element>(elements: Node_Iterable, selector: string): T[];
1025
- export function standard_price_format(price: number, places_after_comma?: number | "auto", decimal_delimiter?: string, thousands_delimiter?: string): string;
1026
- export function intl_number_format_with_fallback(bcp47_country_code: string, number: number, numberformat_options?: Parameters<typeof Intl.NumberFormat>[1]): string;
1027
- export function ensure_object_path(obj: object, step1: string, ...path: string[]): any;
1028
- export function Rec_Renderer<T extends Display>(t: Tenant | null, rendering_options: RR_Options<T>): Promise<RecRendererResult<T>>;
1029
- export function regex_templating(template: string, display?: Display | {
1030
- [key: string]: any;
1031
- }): string;
1032
- export function clone_deep<T>(obj: T): T;
1033
- export class InfoForProcessing<T extends Display> {
1034
- constructor(t: Tenant | null, rendering_options: RR_Options<T>, displays: T[], index?: number, remove_display?: () => void, event_listeners?: [
1035
- type: keyof HTMLElementEventMap,
1036
- listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any,
1037
- options?: boolean | AddEventListenerOptions
1038
- ][]);
1039
- }
1040
- type RegisterEventListener = (type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions) => void;
1041
- export interface InfoForProcessing<T extends Display> {
1042
- t: Tenant;
1043
- rendering_options: RR_Options<T>;
1044
- displays: T[];
1045
- index: number;
1046
- remove_display?: () => void;
1047
- register_event_listener: RegisterEventListener;
1048
- event_listeners?: [
1049
- type: keyof HTMLElementEventMap,
1050
- listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any,
1051
- options?: boolean | AddEventListenerOptions
1052
- ][];
1053
- extras?: {
1054
- [key: string]: any;
1055
- };
1056
- }
1057
- export type RR_PreProcessor<T extends Display> = (display: T, info: InfoForProcessing<T>) => Promise<T> | T;
1058
- 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;
1059
- export type RR_Options<T extends Display> = {
1060
- template: string | ((arg0: T, info: InfoForProcessing<T>) => Promise<string | Node_Array> | string | Node_Array);
1061
- recs?: T[] | undefined | Promise<T[] | undefined>;
1062
- type: string;
1063
- min_items_to_report?: number;
1064
- min_items_to_run?: number;
1065
- max_items?: number;
1066
- extra_api_options?: {
1067
- [key: string]: any;
1068
- };
1069
- pre_processors?: RR_PreProcessor<T>[];
1070
- post_processors?: RR_PostProcessor<T>[];
1071
- headers?: HeadersInit;
1072
- } & FetchRecsOptions;
1073
- /**
1074
- * Product properties that are used to render the product cards. Used until early 2023
1075
- */
1076
- export interface LegacyDisplay {
1077
- /**
1078
- * The URL of the product page.
1079
- */
1080
- page_url: any;
1081
- /**
1082
- * The URL of the product image.
1083
- */
1084
- image_url: string;
1085
- /** The price of the product. */
1086
- sale_price: number;
1087
- /** The original price of the product. */
1088
- original_price: number;
1089
- /** The product ID of the product. */
1090
- product_id: string;
1091
- /** The Google Analytics product ID */
1092
- ga_product_id?: string;
1093
- /** The Google Analytics product IDs */
1094
- ga_product_ids?: string[];
1095
- /** The variation IDs */
1096
- variant_ids?: string[];
1097
- /** The title */
1098
- title: string;
1099
- /** Unique recommendation result ID used by Depict */
1100
- recommendation_id?: string;
1101
- /** Unique search result ID used by Depict */
1102
- search_result_id?: string;
1103
- /** Unique product listing result ID used by Depict */
1104
- product_listing_result_id?: string;
1105
- [key: string]: any;
1106
- }
1107
- interface ModernDisplay {
1108
- /**
1109
- * The index of the variant to be displayed.
1110
- */
1111
- variant_index: number;
1112
- /**
1113
- * All variant displays (eg. different colors, sizes) of the product.
1114
- */
1115
- variant_displays: any[];
1116
- /** SKUs of the different variants */
1117
- variant_skus: string[];
1118
- /** Product of the different variants */
1119
- variant_product_ids: 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
- }
1129
- interface BasicDisplay {
1130
- product_id: string;
1131
- /** Unique recommendation result ID used by Depict */
1132
- recommendation_id?: string;
1133
- /** Unique search result ID used by Depict */
1134
- search_result_id?: string;
1135
- /** Unique product listing result ID used by Depict */
1136
- product_listing_result_id?: string;
1137
- /** Recommendation type logic used by Depict */
1138
- logic?: string;
1139
- [key: string]: any;
1140
- }
1141
- export type Display = LegacyDisplay | ModernDisplay | BasicDisplay;
1142
- export type Node_Iterable = HTMLCollection | NodeListOf<ChildNode> | Node_Array;
1143
- export type Node_Array = (Element | Text | Comment)[];
1144
- export type RecRendererResult<T extends Display> = Record<string, never> | {
1145
- elements: Node_Array;
1146
- displays: T[];
1147
- };
1148
- /**
1149
- * Queues a task in the event queue without a timeout like setTimeout does, see https://www.youtube.com/watch?v=cCOL7MC4Pl0
1150
- * @param callback callback function that gets queued as a task
1151
- */
1152
- export function queueMacroTask(callback: VoidFunction): void;
1153
- interface SDKRenderingInfo {
1154
- set_on_index_change: (fn: (index: number) => void) => void;
1155
- merchant: string;
1156
- market: string;
1157
- }
1158
- /**
1159
- * Creates a handler for sending the "recommendations_inserted" event on new results.
1160
- * Usage: call make_plp_recommendations_inserted_handler with options and then call the returned functions in your productCardTemplate
1161
- */
1162
- export function make_plp_recommendations_inserted_handler(tenant: string, market: string, type: "search" | "category"): <T extends Display>(display: T | null, info?: SDKRenderingInfo) => void;
1163
- /**
1164
- * @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
1165
- */
1166
- export function cache_args(fn: any, ...args: any[]): (...unimportant_args: any[]) => any;
1167
- export const check_displays: (args_0: {
1168
- recs: Display[] | {
1169
- displays: Display[];
1170
- } | Promise<Display[] | {
1171
- displays: Display[];
1172
- }>;
1173
- min_recs?: number | undefined;
1174
- market: string;
1175
- type: string;
1176
- product_id: string | string[] | Promise<string> | Promise<string[]> | ((arg0?: string) => string | string[] | Promise<string> | Promise<string[]>) | undefined;
1177
- tenant: string;
1178
- }) => Promise<boolean | undefined>;
1179
- /**
1180
- * @deprecated You should no longer need to use this. Use observer.onexists to add an event listener to an element once it exists.
1181
- */
1182
- export function require_event_listener(element: Node, event: string, track_id: any, func: EventListenerOrEventListenerObject): void;
1183
- export const default_view_tracking: (RR_PostProcessor<any> | typeof depict_page_view)[];
1184
- export const default_click_tracking: (typeof depict_click_tracking_post_processor | typeof add_new_tab_listener)[];
1185
- export function recs_inserted_tracking<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1186
- export function gtag_view_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1187
- export function depict_page_view<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1188
- export function gtag_click_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1189
- export function depict_click_tracking_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1190
- export function add_to_localstorage<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1191
- export function ga_click<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1192
- export const should_colorizeLogics: boolean;
1193
- export function colorize_elements(elements: NodeListOf<ChildNode> | Node_Array, display: Display): NodeListOf<ChildNode> | Node_Array;
1194
- type Extended_RR_Options<T extends Display> = {
1195
- view_tracking?: RR_PostProcessor<T>[];
1196
- click_tracking?: RR_PostProcessor<T>[];
1197
- } & RR_Options<T>;
1198
- export function default_rr<T extends Display>(t: Tenant | null, rendering_options: Extended_RR_Options<T>): Promise<RecRendererResult<T>>;
1199
- type GWVM_Options = {
1200
- container_selector?: string;
1201
- start_rows?: number;
1202
- rows_per_click?: number;
1203
- recs_per_row?: number | ((showing: number) => number);
1204
- button?: string | HTMLElement;
1205
- override_rec_renderer?: typeof Rec_Renderer;
1206
- title_selector?: string;
1207
- title?: string | HTMLElement;
1208
- container_template: string | Node_Array;
1209
- only_full_rows?: boolean;
1210
- should_preload?: boolean;
1211
- };
1212
- interface GWVM_InfoForProcessing<T extends Display> extends InfoForProcessing<T> {
1213
- extras: {
1214
- [key: string]: any;
1215
- load_more_currently_showing: number;
1216
- load_more: (num?: number | Event) => void;
1217
- load_more_ipo: {
1218
- promise: Promise<number>;
1219
- resolve: (argument?: number) => void;
1220
- };
1221
- };
1222
- }
1223
- type GWVM_RR_Post_Pro = (elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: GWVM_InfoForProcessing) => Promise<NodeListOf<ChildNode> | Node_Array> | NodeListOf<ChildNode> | Node_Array;
1224
- type GWVM_RR_Options = Extended_RR_Options & {
1225
- post_processors?: GWVM_RR_Post_Pro[];
1226
- };
1227
- /**
1228
- * @deprecated please use RecommendationGrid instead
1229
- */
1230
- export function GWVM_Renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: GWVM_Options): Promise<{
1231
- elements?: ChildNode[] | undefined;
1232
- load_more?: ((num?: number | Event) => void) | undefined;
1233
- displays?: Display[] | undefined;
1234
- }>;
1235
- /**
1236
- * Used auto generate recommendations with view more button.
1237
- * @param t The tenant used for recommendations
1238
- * @param options Rendering options for recommendations such as total number of recommendations and template.
1239
- * `GWVM_RR_Options` extends the same typing used for options in `default_rr and` `recommendation-renderer`
1240
- * @param GWVM_opts Grid options, starting row, rows per view more click, container templates
1241
- * @param rec_selector The selector used to find the rendered recs (by recommendation renderer
1242
- * for which the first options object was used) for the width calculation. Default: ".rec_outer".
1243
- * @deprecated please use RecommendationGrid instead
1244
- */
1245
- export function Auto_GWVM(t: Tenant, options: GWVM_RR_Options, GWVM_opts: Omit<GWVM_Options, "recs_per_row">, { rec_selector }?: {
1246
- rec_selector?: string;
1247
- }): Promise<{
1248
- elements?: Node_Array | undefined;
1249
- load_more?: ((num?: number | Event) => void) | undefined;
1250
- displays?: Display[] | undefined;
1251
- }>;
1252
- /**
1253
- * @deprecated use async_iterable_ipns instead. This can skip values which yields unexpected results.
1254
- */
1255
- export function infinite_promise_creator(): {
1256
- promise: Promise<unknown>;
1257
- internal_resolve: ((value: any) => void) | undefined;
1258
- resolve: (argument?: any) => void;
1259
- };
1260
- interface trimmed_GWVM_opts extends Omit<GWVM_Options, "start_rows" | "rows_per_click" | "recs_per_row"> {
1261
- }
1262
- /**
1263
- * @deprecated please rewrite this, basing on RecommendationGrid and its `rows.ipns` option, next time you need infinite scroll
1264
- */
1265
- export function infinite_renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: trimmed_GWVM_opts, { rec_selector }?: {
1266
- rec_selector?: string;
1267
- }): Promise<{
1268
- elements?: Node_Array | undefined;
1269
- load_more?: ((num?: number | Event | undefined) => void) | undefined;
1270
- displays?: Display[] | undefined;
1271
- }>;
1272
- /**
1273
- * @deprecated Emil's utility in integration.ts is better because it doesn't cause multiply <style> tags and doesn't require a tenant class
1274
- */
1275
- export function deprecated_insert_styling(t: Tenant, css: string, extra_html?: string): Promise<void>;
1276
- export type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;
1277
- /**
1278
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1279
- */
1280
- enum Market {
1281
- dk = "dk",
1282
- uk = "uk",
1283
- com = "com",
1284
- fi = "fi",
1285
- no = "no",
1286
- de = "de",
1287
- nl = "nl",
1288
- fr = "fr",
1289
- se = "se",
1290
- ch = "ch",
1291
- za = "za",
1292
- us = "us",
1293
- ee = "ee",
1294
- default = "default"
1295
- }
1296
- /**
1297
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1298
- */
1299
- enum Locale {
1300
- sv_SE = "sv-SE",
1301
- no_NO = "no-NO",
1302
- fi_FI = "fi-FI",
1303
- da_DK = "da-DK",
1304
- en_UK = "en-UK",
1305
- de_DE = "de-DE",
1306
- nl_NL = "nl-NL",
1307
- fr_FR = "fr-FR",
1308
- de_CH = "de-CH"
1309
- }
1310
- type CurrencyInfo = {
1311
- name: string;
1312
- pre: string;
1313
- post: string;
1314
- };
1315
- /**
1316
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1317
- */
1318
- type MarketDetails = {
1319
- currency: CurrencyInfo;
1320
- locale_bcp47: Locale;
1321
- };
1322
- /**
1323
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1324
- */
1325
- type MarketConfig = MarketDetails & {
1326
- analytics_id: string;
1327
- };
1328
- /**
1329
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1330
- */
1331
- export const MARKET_MAP: Record<Market, MarketDetails>;
1332
- /**
1333
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1334
- */
1335
- export function get_market_locale(market: Market): Locale;
1336
- /**
1337
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1338
- */
1339
- export function get_market_currency(market: Market): CurrencyInfo;
1340
- /**
1341
- * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1342
- */
1343
- export type TenantMarketConfig<M extends Market> = Record<M, MarketConfig>;
1344
- /**
1345
- * @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.
1346
- */
1347
- export function placeholder(...args: Parameters<typeof placeholder_worker>): accepted_input_that_resolves_to_elements;
1348
- type accepted_element_types = Node_Array[0] | Node_Array;
1349
- type accepted_input_that_resolves_to_elements = accepted_element_types | Promise<accepted_element_types> | (() => accepted_element_types) | (() => Promise<accepted_element_types>);
1350
- 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>;
1351
- declare global {
1352
- interface HTMLImageElementWithLoaded extends HTMLImageElement {
1353
- loaded?: boolean;
1354
- }
1355
- interface HTMLSourceElementWithLoaded extends HTMLSourceElement {
1356
- loaded?: boolean;
1357
- }
1358
- }
1359
- export interface Lazyfier {
1360
- t: Tenant;
1361
- container: HTMLElement;
1362
- selector: string;
1363
- lazyfinder: lazyfinder;
1364
- only_load_intersecting: boolean;
1365
- ignore_data_urls?: boolean;
1366
- }
1367
- interface Lazyfier_Options {
1368
- container?: HTMLElement;
1369
- lazyfinder?: lazyfinder;
1370
- selector?: string;
1371
- wait_for_dominsertion?: boolean | Promise<any>;
1372
- only_load_intersecting?: boolean;
1373
- verbose?: boolean;
1374
- ignore_data_urls?: boolean;
1375
- }
1376
- export class Lazyfier {
1377
- #private;
1378
- intersection_observer: IntersectionObserver;
1379
- start_observing_for_new_children_(override_container?: HTMLElement): void;
1380
- constructor({ container, lazyfinder, selector, wait_for_dominsertion, only_load_intersecting, ignore_data_urls, verbose, }: Lazyfier_Options);
1381
- }
1382
- interface lazyfinder {
1383
- elements?: HTMLImageElementWithLoaded[];
1384
- unload?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1385
- load?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1386
- }
1387
- export function test_array_proxy_support(): boolean;
1388
- export interface Slider_Options {
1389
- /**
1390
- * Controls within what distance to hide the left slider button.
1391
- * The distance is in pixels to the leftmost part of the slider container from the first element in the slider
1392
- *
1393
- * Defaults to `10`
1394
- */
1395
- dist_to_hide_left?: number;
1396
- /**
1397
- * Controls within what distance to hide the right slider button.
1398
- * The distance is in pixels to the rightmost part of the slider container from the last element in the slider
1399
- *
1400
- * Defaults to `10`
1401
- */
1402
- dist_to_hide_right?: number;
1403
- stepstoslide?: number;
1404
- center_target?: boolean;
1405
- constructor_plugins?: ((arg0: Slider_Options) => any)[];
1406
- mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1407
- correct_bs_targets?: boolean;
1408
- button_contents?: {
1409
- right: Node_Iterable;
1410
- left: Node_Iterable;
1411
- };
1412
- button_elems?: {
1413
- right: HTMLElement;
1414
- left: HTMLElement;
1415
- };
1416
- autoinvalidate_cache?: boolean;
1417
- }
1418
- export class Amazing_Slider {
1419
- #private;
1420
- container: HTMLElement;
1421
- insert_here: HTMLElement;
1422
- intersecting_items_object: {
1423
- [key: string]: IntersectionObserverEntry;
1424
- [key: number]: IntersectionObserverEntry;
1425
- };
1426
- stepstoslide: number;
1427
- dist_to_hide_left: number;
1428
- dist_to_hide_right: number;
1429
- center_target: boolean;
1430
- correct_bs_targets: boolean;
1431
- snap_style?: HTMLStyleElement;
1432
- on_elements_changed: ((records: MutationRecord[]) => any)[];
1433
- observer: IntersectionObserver;
1434
- observe: any;
1435
- get_index_of_element(target: Element | HTMLElement): number | undefined;
1436
- first_intersecting_index(min_ratio?: number): number;
1437
- get first_intersecting(): IntersectionObserverEntry;
1438
- get index_of_last_element(): number;
1439
- get currently_selected(): number | undefined;
1440
- get visible_sizes(): Map<Element, {
1441
- total_visible: number;
1442
- ratio_visible: number;
1443
- margin_left: number;
1444
- margin_right: number;
1445
- rect: DOMRect;
1446
- }>;
1447
- get cards_fitting_in_viewport(): number;
1448
- element_by_index(index: number): Element;
1449
- invalidate_cache(): void;
1450
- scroll_to_rel(offset: number, harsh?: boolean): void;
1451
- scroll_to_abs(offset: number, harsh?: boolean): void;
1452
- constructor({ dist_to_hide_left, dist_to_hide_right, stepstoslide, center_target, mutation_plugins, constructor_plugins, correct_bs_targets, button_contents, button_elems, autoinvalidate_cache, }: Slider_Options);
1453
- }
1454
- export interface Amazing_Lazy_Slider {
1455
- lazyfier: Lazyfier;
1456
- }
1457
- export class Amazing_Lazy_Slider extends Amazing_Slider {
1458
- constructor(options: Slider_Options, lazyfier_options?: Optional<ConstructorParameters<typeof Lazyfier>[0], "container">);
1459
- }
1460
- interface Pro_Slider_Options {
1461
- container?: string | Node_Iterable;
1462
- root_selector?: string;
1463
- override_rec_renderer?: typeof Rec_Renderer;
1464
- insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1465
- lazyfier_options?: ConstructorParameters<typeof Amazing_Lazy_Slider>[1];
1466
- }
1467
- /**
1468
- * @deprecated please use RecommendationSlider instead
1469
- */
1470
- 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>>;
1471
- /**
1472
- * @deprecated Please use recommendation renderer instead
1473
- */
1474
- export class Depict {
1475
- #private;
1476
- settings: any;
1477
- data: any;
1478
- tracker: void;
1479
- constructor(settings: any);
1480
- init(callback: Function, existingDisplays?: object[]): void;
1481
- loadRecommendations(callback: any): void;
1482
- trackGAEvent(action: any, index: any, product_id: any, ga_product_ids?: string[]): void;
1483
- trackPageView(): void;
1484
- trackClick(index: any): boolean | Promise<void | undefined> | undefined;
1485
- trackAddToCart(pId: any): boolean | Promise<void | undefined> | undefined;
1486
- createContainer(root: any, container: any, prepend?: boolean): void;
1487
- renderTemplate({ prep, root, template, itemPreprocessor, itemPostprocessor }?: any): void;
1488
- }
1489
- declare global {
1490
- interface Document {
1491
- _depict_modify: boolean | undefined;
1492
- }
1493
- }
1494
- interface TemplateToolOptions {
1495
- max_items?: number;
1496
- min_items?: number;
1497
- DNT?: boolean;
1498
- debug?: boolean;
1499
- type?: string;
1500
- product_id?: Function | ((url?: string) => string);
1501
- sendGa?: boolean;
1502
- loadHack?: boolean;
1503
- shade?: boolean;
1504
- gaid?: string;
1505
- tenant?: string;
1506
- market?: string;
1507
- }
1508
- /**
1509
- * @deprecated Please use RecommendationRenderer instead
1510
- */
1511
- export const simplified_template_tool: (options: {
1512
- options: TemplateToolOptions;
1513
- recs?: object[] | undefined;
1514
- root: Element;
1515
- template: string;
1516
- postProcessor?: Function | undefined;
1517
- preProcessor?: Function | undefined;
1518
- }) => Promise<Depict>;
1519
- interface special_lazyfier_options extends Omit<Lazyfier_Options, "t"> {
1520
- }
1521
- interface Deprecated_Slider_Options {
1522
- dlog?: Function;
1523
- catchify?: Function;
1524
- dist_to_hide_left?: number;
1525
- dist_to_hide_right?: number;
1526
- stepstoslide?: number;
1527
- arrow_image?: string;
1528
- center_target?: boolean;
1529
- constructor_plugins?: ((arg0: Deprecated_Slider_Options) => any)[];
1530
- mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1531
- correct_bs_targets?: boolean;
1532
- }
1533
- /**
1534
- * @deprecated Please use Pro_Slider instead
1535
- */
1536
- declare class Deprecated_Amazing_Slider extends Amazing_Lazy_Slider {
1537
- constructor(static_options: Deprecated_Slider_Options, override_lazyfier_options?: special_lazyfier_options);
1538
- }
1539
- export function insert_styling_into_slider(slider: Deprecated_Amazing_Slider): void;
1540
- interface RR_Slider_Options {
1541
- container?: string | Node_Iterable;
1542
- root_selector?: string;
1543
- Rec_Renderer?: typeof Rec_Renderer;
1544
- insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1545
- }
1546
- /**
1547
- * @deprecated please use Pro_Slider instead
1548
- */
1549
- 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>;
1550
- type PreProcessor = (tenant: Tenant, display: any, i?: number, with_loadmore?: boolean, with_slider?: boolean, infinite_scroll?: boolean) => any;
1551
- type PostProcessor = (tenant: Tenant, items: HTMLCollection, display: any, slider?: Deprecated_Amazing_Slider) => HTMLCollection;
1552
- /**
1553
- * @deprecated this uses template-tool-v1 which is long surpassed, please use RecommendationGrid or Pro_Slider (based on Recommendation-Renderer) instead
1554
- */
1555
- export function get_recs_with_template({ t, recs, title, infinite_scroll, with_slider, with_loadmore, template_tool_options, slider_options, pre_processors, post_processors, container_template, // container template
1556
- template, // recommendation template
1557
- chunk_size_for_load_more, insertion_promise, }: {
1558
- t: Tenant;
1559
- recs?: any[];
1560
- with_loadmore?: boolean;
1561
- title?: string | Node[] | NodeList;
1562
- infinite_scroll?: boolean;
1563
- template_tool_options?: TemplateToolOptions;
1564
- with_slider?: boolean;
1565
- slider_options?: Deprecated_Slider_Options;
1566
- pre_processors?: PreProcessor[];
1567
- post_processors?: PostProcessor[];
1568
- container_template: string;
1569
- template: string;
1570
- chunk_size_for_load_more?: number;
1571
- insertion_promise?: Promise<void | unknown>;
1572
- }): Promise<ChildNode[] | void>;
1573
- export function default_pre_processor(_t: any, d: any, i: number, with_loadmore: boolean, with_slider: boolean, infinite_scroll: boolean): any;
1574
- export function default_post_processor(_t: any, itms: HTMLCollection, d: any, slider: Deprecated_Amazing_Slider | null): HTMLCollection;
1575
- /**
1576
- * @deprecated please use `fetch_retry()` instead
1577
- *
1578
- * 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
1579
- * (Note: this thing really should be rewritten with exponential backoff and a better API)
1580
- * @param dlog logging function to use
1581
- * @param error_log an array to which errors will be pushed
1582
- * @return a windows proof fetch function
1583
- */
1584
- export const wpff: (dlog: any, error_log?: any[]) => (url: RequestInfo, body: BodyInit, headers?: HeadersInit, decode_json?: boolean, fetch_options?: RequestInit, attempt?: number) => any;
1585
- export const use_element: <E extends HTMLOrSVGElement = HTMLElement>(callback: (element: E) => void, element: E) => E;
1586
- export function use_listener<K extends keyof GlobalEventHandlersEventMap, E extends HTMLElement = HTMLElement>(event: K, handler: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, element: E): E;
1587
- export const classlist: (classes: (string | undefined)[]) => string;
1588
- type Props = {
1589
- children: Elem[] | Elem;
1590
- onClick: (e: MouseEvent) => void;
1591
- [key: string]: any;
1592
- };
1593
- type Elem = Node | string;
1594
- type Component = (props: Props, _unknown: unknown) => HTMLElement;
1595
- export const jsx: (tag: string | Component, { children, ...props }: Props, _unknown: unknown) => JSX.Element;
1596
- export const jsxs: (tag: string | Component, { children, ...props }: Props, _unknown: unknown) => JSX.Element;
1597
- export const chevronRight: HTMLElement;
1598
- export const chevronLeft: HTMLElement;
1599
- export const expandingContainer: ({ duration }?: {
1600
- duration?: number;
1601
- }) => {
1602
- expand: () => void;
1603
- content: HTMLDivElement;
1604
- container: HTMLDivElement;
1605
- };
1606
- /**
1607
- * 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.
1608
- * @param iterables Array of IPNS
1609
- * @return IPNS that resolves with an array of the values of all provided IPNS when one of them resolves
1610
- */
1611
- export function zip_async_iterables<T extends any[]>(iterables: IPNS<T[keyof T]>[]): IPNS<T>;
1612
- /** Overrides that can specify a different amount of columns for certain rows
1613
- * @param key The row (starts at 1) that you're "selecting" to override
1614
- * @param value The amount of columns that your selected row should have
1615
- */
1616
- type Override = {
1617
- overrides: Record</* Row: */ number, /* Column: */ number>;
1618
- };
1619
- 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];
1620
- type ColsAtSize = readonly ColAtSize[];
1621
- type LayoutOptions = {
1622
- container_element: Element;
1623
- cols_at_size: ColsAtSize;
1624
- grid_spacing: string;
1625
- rows: {
1626
- start_rows?: number;
1627
- rows_per_click?: number;
1628
- ipns?: IPNS<number>;
1629
- max_rows?: number;
1630
- button?: HTMLElement;
1631
- } | "all";
1632
- layout: "slider" | "grid";
1633
- disable_partial_rows?: boolean;
1634
- override_vertical_spacing?: string;
1635
- };
1636
- /**
1637
- * Grid: Calculates CSS for a grid with a certain spacing and certain number of columns at certain screen sizes, including a view more button.
1638
- * @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
1639
- * @param container_element container element of the elements that you want to style and hide
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 grid_spacing spacing to use if none is specified for the specific size in `cols_at_size`
1642
- * @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".
1643
- * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1644
- */
1645
- export function Layout({ rows, container_element, cols_at_size, grid_spacing, layout, disable_partial_rows, override_vertical_spacing, }: LayoutOptions): Promise<void>;
1646
- /**
1647
- * basically equivalent of n_col_styling css mixin - generates distances for a flex grid with margins
1648
- * @param selector_beginning Main selector targeting container classname to use in generated css
1649
- * @param default_grid_spacing_text Spacing to use if not specified in cols_at_size for a specific size
1650
- * @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
1651
- * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1652
- * @return String of generated CSS
1653
- */
1654
- 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;
1655
- export interface RecommendationGridOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "layout"> {
1656
- container_elements: Node_Array;
1657
- container_selector?: string;
1658
- override_rec_renderer?: typeof default_rr<T>;
1659
- lazyfier_options?: Omit<Lazyfier_Options, "t">;
1660
- eager_images?: boolean;
1661
- }
1662
- /**
1663
- * 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.
1664
- * @param t Instance of Tenant
1665
- * @param recommendation_renderer_options Options for default_rr or override_rec_renderer
1666
- * @param container_elements The elements from your container template.
1667
- * @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"
1668
- * @param override_rec_renderer Other recommendation renderer to use apart from default_rr (i.e. placeholder_rr)
1669
- * @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.
1670
- * @param eager_images Don't lazyload images
1671
- * @param ...options_for_grid Options for Grid. See documentation of Grid.
1672
- * @constructor
1673
- */
1674
- export function RecommendationGrid<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, { container_elements, container_selector, override_rec_renderer, lazyfier_options, eager_images, ...options_for_grid }: RecommendationGridOptions<T>): Promise<RecRendererResult<T>>;
1675
- export interface EasySliderOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "rows" | "layout"> {
1676
- rows?: {
1677
- start_rows?: number;
1678
- ipns?: IPNS<number>;
1679
- } | "all";
1680
- container_elements: Node_Array;
1681
- container_selector?: string;
1682
- override_rec_renderer?: typeof default_rr<T>;
1683
- lazyfier_options?: Omit<Lazyfier_Options, "t">;
1684
- eager_images?: boolean;
1685
- dist_to_hide_left?: number;
1686
- dist_to_hide_right?: number;
1687
- stepstoslide?: number;
1688
- center_target?: boolean;
1689
- constructor_plugins?: ((arg0: Slider_Options) => any)[];
1690
- mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1691
- button_contents?: {
1692
- right: Node_Iterable;
1693
- left: Node_Iterable;
1694
- };
1695
- button_elems?: {
1696
- right: HTMLElement;
1697
- left: HTMLElement;
1698
- };
1699
- override_vertical_spacing?: string;
1700
- }
1701
- export type RecommendationSliderSurface<T extends Display> = Record<string, never> | {
1702
- elements: Node_Array;
1703
- slider: Amazing_Slider | Amazing_Lazy_Slider;
1704
- displays: T[];
1705
- };
1706
- /**
1707
- *
1708
- * The most epic RecommendationSlider todate
1709
- * @param t Instance of tenant class
1710
- * @param recommendation_renderer_options Options for Recommendation Renderer
1711
- * @param RecommendationGrid_options Similar options object to RecommendationGrid except that it also contains options to Amazing_Slider
1712
- * @return a Surface (object) that contains displays, elements and the instance of the slider class (as `slider`)
1713
- */
1714
- export function RecommendationSlider<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, { container_elements, container_selector, override_rec_renderer, lazyfier_options, eager_images, grid_spacing, cols_at_size, override_vertical_spacing, rows, ...slider_options }: EasySliderOptions<T>): Promise<RecommendationSliderSurface<T> | RecRendererResult<T> | Surface<T>>;
1715
- export function slider_autoscroll_factory(interval?: number): {
1716
- constructor_plugin(this: Amazing_Slider): void;
1717
- mutation_plugin: (this: Amazing_Slider, _intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1718
- };
1719
- export function make_button1(): {
1720
- left: [HTMLImageElement];
1721
- right: [HTMLImageElement];
1722
- };
1723
- /**
1724
- * Returns an object to put into `button_contents` for `Pro_Slider` containing the icon arrow images
1725
- * @return An object with left and right being an array containing one image
1726
- */
1727
- export function make_button2(): {
1728
- left: HTMLImageElement[];
1729
- right: HTMLImageElement[];
1730
- };
1731
- export function slider_dots_factory({ t, navcont_insertion_fn, navdot, dontshowonedot, bitesize, }: {
1732
- t: Tenant;
1733
- navcont_insertion_fn?: (slider: Amazing_Slider, navcont: HTMLDivElement) => any;
1734
- navdot: (unique_name: number, index: number) => Element;
1735
- dontshowonedot?: boolean;
1736
- bitesize?: number;
1737
- }): {
1738
- constructor_plugin: () => void;
1739
- mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1740
- };
1741
- export function navdot(unique_name: string | number): HTMLElement;
1742
- export function slider_draggable_factory(t: Tenant): {
1743
- constructor_plugin: (slider_options: any) => void;
1744
- mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1745
- post_pro_plugin: {
1746
- instant: (items: HTMLCollection) => void;
1747
- };
1748
- };
1749
- export function slider_fading_factory({ fade_in_duration_, fade_out_duration_, visible_opacity_, faded_opacity_, easing_, threshold_, }?: {
1750
- fade_in_duration_?: number;
1751
- fade_out_duration_?: number;
1752
- visible_opacity_?: number;
1753
- faded_opacity_?: number;
1754
- easing_?: string;
1755
- threshold_?: number;
1756
- }): {
1757
- readonly mutation_plugin_: (this: Amazing_Slider, entries: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1758
- };
1759
- export function slider_fractional_factory(_t?: any, fraction?: number, max_steps?: number, dont_enable_correct_bs_targets?: boolean, min_steps?: number): {
1760
- constructor_plugin: (slider_options: Slider_Options) => void;
1761
- mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1762
- };
1763
- /**
1764
- * * Plugin for rendering a scrollbar below the slider that follow the slider position.
1765
- * * Scroll container class: `depict_slider_scroll`
1766
- * * Scroll bar class: `depict_slider_scroll_bar`
1767
- * @param options Options for the scrollbar. Add position styling and additional classes.
1768
- */
1769
- export function slider_show_scroll(options: {
1770
- add_position_styling: boolean;
1771
- scroll_bar_classes?: string[];
1772
- scroll_container_classes?: string[];
1773
- }): {
1774
- constructor_plugin: (_slider_options: Slider_Options) => void;
1775
- mutation_plugin: (_intersections: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1776
- };
1777
- export function slider_snap_css(_t?: any, { snapEvery, align }?: {
1778
- snapEvery?: number;
1779
- align?: "center" | "start" | "end";
1780
- }): {
1781
- constructor_plugin: (_slider_options: Slider_Options) => void;
1782
- mutation_plugin: (_intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1783
- };
1784
- export function can_use_snapping_and_still_scroll(): Promise<boolean>;
1785
- export function slider_snapping_factory(options?: {
1786
- stepsize?: number;
1787
- threshold?: number;
1788
- }): {
1789
- constructor_plugin: (slider_options: any) => void | undefined;
1790
- mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void | undefined;
1791
- };
1792
- export function slider_wraparound_factory({ clones_per_side }?: {
1793
- clones_per_side?: number | undefined;
1794
- }): {
1795
- constructor_plugin: (this: Amazing_Slider) => void;
1796
- mutation_plugin: (this: Amazing_Slider, intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1797
- post_processor: <T extends Display>(elements: Node_Array | NodeListOf<ChildNode>, _display: Display, info: InfoForProcessing<T>) => Promise<NodeListOf<ChildNode> | Node_Array>;
1798
- };
1799
- export type ReactiveTemplateValueContents = string | number | Node_Array[number] | undefined | (string | number | Node_Array[number])[];
1800
- export function reactive_template(initial_value?: ReactiveTemplateValueContents): readonly [Node_Array, () => ReactiveTemplateValueContents, (arg0: ReactiveTemplateValueContents) => void];
1801
- export function javascript_media_query(// inspired by code in houdinisportswear modify script
1802
- query: string, handler: (e: MediaQueryListEvent | MediaQueryList) => void, initial_call?: boolean): {
1803
- remove(): void;
1804
- };
1805
- type RenderingFunction<T extends Display> = (...args: any[]) => Promise<{
1806
- surface_: Surface<T> | void;
1807
- cache_until_?: Promise<any>;
1808
- }>;
1809
- /**
1810
- * 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.
1811
- * @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.
1812
- * @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_.
1813
- * @return a `Surface` object which, utilising a `reactive_template` always represents the currently chosen surface
1814
- */
1815
- export function surface_mixer<T extends Display>({ surface_rendering_functions_, current_surface_, }: {
1816
- surface_rendering_functions_: RenderingFunction<T>[];
1817
- current_surface_: IPNS<number>;
1818
- }): Promise<Surface<T>>;
1819
- /**
1820
- * To be used in conjunction with surface_mixer. Makes it possible to switch Surface depending on screen size
1821
- * @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.
1822
- * @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).
1823
- * @return An IPNS resolving with the number of the surface that should currently be shown
1824
- */
1825
- export function sizes_to_surface(surface_per_size: [surface_index: number, min: string | null, max?: string][], cleanup_promise?: Promise<any>): IPNS<number>;
1826
- /**
1827
- * Returns a promise that resolve the next time the href is changed
1828
- */
1829
- export function promise_until_next_navigation(): Promise<string | undefined>;
1830
- export function orderpage_transaction_id_extractor(t: Tenant, selector: string, filter?: (text: string) => string | undefined): void;
1831
- /**
1832
- * Looks at all entries in window.dataLayer, past present and future, and attempts to find transaction IDs in them.
1833
- * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1834
- * @param tenant The tenant we are tracking.
1835
- * @param id_extractor Maps an entry to a transaction ID string, or something falsy if no transaction ID is found.
1836
- * For example: entry => entry?.event?.purchase?.orderId
1837
- */
1838
- export function datalayer_transaction_id_extractor(tenant: Tenant, id_extractor: (layer_entry: any) => any): void;
1839
- /**
1840
- * Looks at all URL changes, including the current URL, and attempts to find transaction IDs in them.
1841
- * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1842
- * @param tenant The tenant we are tracking.
1843
- * @param id_extractor Maps an URL to a transaction ID string, or something falsy if no transaction ID is found.
1844
- * For example: url => url.searchParams.get("orderId")
1845
- */
1846
- export function url_transaction_id_extractor(tenant: Tenant, id_extractor: (url: URL) => unknown): void;
1847
- export function send_transaction_id_to_depict(t: Tenant, input_id: string, dsid?: string, filter?: (text: string) => string | undefined): void;
1848
- /**
1849
- * Intercepts google analytics events for transactions (e.g when payment is made) and also sends it to depict.
1850
- * */
1851
- export function ga_to_transaction_api(t: Tenant, filter?: (text: string) => string | undefined): void;
1852
- export function send_product_unavailable_to_depict(t: Tenant, unavailability_type: EUnavailabilityType): Promise<void>;
1853
- export interface ListenableSetEvent<T> extends CustomEvent {
1854
- detail: T;
1855
- }
1856
- /**
1857
- * Set but you can listen for values being added or removed
1858
- * i.e. my_set.addEventListener("add", ({detail}) => console.log(detail, "was added to", my_set));
1859
- */
1860
- export class ListenableSet<T> extends Set<T> {
1861
- #private;
1862
- addEventListener(event: "add" | "delete", callback: (ev: ListenableSetEvent<T>) => unknown, options?: Parameters<(typeof EventTarget.prototype)["addEventListener"]>[2]): void;
1863
- removeEventListener(event: "add" | "delete", callback: (ev: Event) => unknown): void;
1864
- add(property: T): this;
1865
- delete(property: T): any;
1866
- }
1867
- /**
1868
- * 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.
1869
- * @param element Element to start out at
1870
- * @param selector Selector to search for
1871
- * @param start_right=true In what direction to start: true = right, false = left
1872
- * @return The found element or undefined
1873
- */
1874
- export function chaotic_closest(element: Element, selector: string, start_right?: boolean): Element | undefined;
1875
- type CompareMethod<T> = (i1: T, i2: T) => boolean;
1876
- export const deduplicate: <T>(arr1: T[], arr2: T[], compareFunc: CompareMethod<T>) => T[];
1877
- export const dedup_products: <T extends LegacyDisplay>(arr1: T[], arr2: T[] | undefined) => T[];
1878
- /**
1879
- * Attempt to navigate using nextjs's spa router.
1880
- * Falls back to default browser navigation.
1881
- * Docs: https://nextjs.org/docs/api-reference/next/router
1882
- */
1883
- export function navigate_with_next_router(e: MouseEvent, url: string): false | undefined;
1884
- /**
1885
- * proxies window.fetch:
1886
- * 1. Instead of window.fetch fetch_apply is called, target being the original fetch function
1887
- * 2. fetch_proxy_handler is called and may read the request and return a (fake) response
1888
- * 3. if fetch_proxy_handler fails the original target is called with the same this and arguments
1889
- * We are meticulously preserving this, target and its arguments in case that someone replaces fetch with a function that does something else
1890
- * 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
1891
- * Remember to return response, else it will make another request
1892
- * @param fetch_proxy_handler Called instead of the original fetch function everytime someone does fetch. Has to return a response.
1893
- * @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
1894
- * @return Nothing
1895
- */
1896
- 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>;
1897
- /**
1898
- * 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.
1899
- * Useful when wanting to change the result of a `fetch request`
1900
- * Please see repo for usage examples
1901
- * @param response_string String to base Response object on
1902
- * @param url URL to claim that the Response is from
1903
- * @param headers Response headers
1904
- * @param override_options More options to pass to the `Response` constructor
1905
- */
1906
- export class FakeResponse extends Response {
1907
- constructor(response_string: string, url: string, headers?: HeadersInit, override_options?: ResponseInit);
1908
- }
1909
- export type ShopifyItem = {
1910
- id: number;
1911
- handle: string;
1912
- quantity: number;
1913
- url: string;
1914
- };
1915
- export type ShopifyError = {
1916
- status: number;
1917
- message: string;
1918
- description: string;
1919
- };
1920
- /**
1921
- * Represents a Shopify cart "event", i.e. Whenever a Shopify API request is sucessfull.
1922
- * - `type` represent the type of event
1923
- * - `response` resolves to a shopify response
1924
- */
1925
- export type ShopifyEvent = {
1926
- type: "get_items";
1927
- response: Promise<ShopifyItem[] | ShopifyError>;
1928
- body?: object;
1929
- } | {
1930
- type: "add_items";
1931
- response: Promise<ShopifyItem[] | ShopifyError>;
1932
- body?: object;
1933
- } | {
1934
- type: "update_items";
1935
- response: Promise<ShopifyItem[] | ShopifyError>;
1936
- body?: object;
1937
- } | {
1938
- type: "change_items";
1939
- response: Promise<ShopifyItem[] | ShopifyError>;
1940
- body?: object;
1941
- } | {
1942
- type: "clear_items";
1943
- response: Promise<[] | ShopifyError>;
1944
- body?: object;
1945
- };
1946
- /**
1947
- * Whenever any request to the shopify cart endpoint (this includes requests made by merchant code) is made {@link on_response} is called.
1948
- *
1949
- * ### Caveats
1950
- * - This currently doesn't intercept XHR requests, only `fetch`. Interpecpting XHR should be implemented at some point!
1951
- *
1952
- * - Under the hood, this function works by proxying `window.fetch`. This isn't guaranted to work, and could even break merchant code.
1953
- * Call this function early on in the execution for the best possibillity of success.
1954
- *
1955
- * - If the merchant performs a `window.fetch` to Shopify before `intercept` then that response wont be intercepted.
1956
- * If you know that the merchant will make a request to Shopify early on then it might make sense to do something like:
1957
- * ```
1958
- * const handle = setTimeout(catchify(() => get_items_in_cart()), 2000)
1959
- * intercept(evt => {
1960
- * canel_timeout(handle)
1961
- * ...
1962
- * })
1963
- * ```
1964
- * In order to get the cart contents at some point even if you miss the merchants innitialt Shopify request.
1965
- *
1966
- * - `intercept` intercepts all requests to Shopify, including requests made by you.
1967
- */
1968
- export function intercept(on_request: (event: ShopifyEvent) => any): void;
1969
- export type AddToCartOptions = {
1970
- quantity?: number;
1971
- };
1972
- /**
1973
- * Add an item to the Shopify cart.
1974
- *
1975
- * ### Caveats
1976
- * Keep in mind that adding to the shopify cart wont neccesarily update the merchants UI,
1977
- * it only means that when the merchant fetches the cart again then they'll get the item added by you.
1978
- * Usually the merchant has it's own global add-to-cart function that can be used. While doing that can
1979
- * take more developer time it means that you usually get the merchant UI to update correctly.
1980
- *
1981
- * @param shopify_id
1982
- * @param options.quantity How many of an item to add, defaults to `1`.
1983
- * @throws If the response JSON is in an unexpected format.
1984
- */
1985
- export function add_item(shopify_id: string, options?: AddToCartOptions): Promise<ShopifyItem[] | ShopifyError>;
1986
- /**
1987
- * Fetch the items in the shoppify cart.
1988
- *
1989
- * This is probably not the right function for mose use-cases.
1990
- * Want to get notified when merchant code adds new items to the cart through Shopify?
1991
- * Use {@link intercept} to intercept all calls to Shopify (even ones made by merchant code).
1992
- *
1993
- * @returns All items currently in the cart.
1994
- * @throws If the response JSON is in an unexpected format.
1995
- */
1996
- export function get_items_in_cart(): Promise<ShopifyItem[] | ShopifyError>;
1997
- declare global {
1998
- interface Window {
1999
- ShopifyAnalytics: {
2000
- meta?: {
2001
- product?: ShopifyMetaProduct;
2002
- };
2003
- };
2004
- }
2005
- }
2006
- interface ShopifyMetaProduct {
2007
- id?: string;
2008
- vendor?: string;
2009
- variants?: {
2010
- id?: string;
2011
- sku?: string;
2012
- }[];
2013
- }
2014
- /** Shopify sites often has an interesting meta object defined on window.ShopifyAnalytics.meta
2015
- * The SKU that backend requires might only be found in the meta object.
2016
- * This function gives you that object in a safe way that won't break Shopify.
2017
- */
2018
- export const get_shopify_analytics_meta_product: () => Promise<ShopifyMetaProduct | undefined>;
2019
- /**
2020
- * 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`
2021
- * @param t Instance of `Tenant class`
2022
- * @param experiment_id Optimize experiment id of running A/B test
2023
- * @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.
2024
- * @param functions_to_variants [description]
2025
- * @return The return value of the called function
2026
- */
2027
- export function get_optimize_variant({ t, experiment_id, functions_to_variants, }: {
2028
- t: Tenant;
2029
- experiment_id: string;
2030
- functions_to_variants: Function[];
2031
- }): Promise<any>;
2032
- /**
2033
- * Ensures that the attribute value of an element is what an AsyncIterable resolves with
2034
- * @param el Element to set attribute on
2035
- * @param attribute_name Name of the attribute to set
2036
- * @param async_iterable AsyncIterable to loop over
2037
- * @param quit_after_navigation=true Whether to stop awaiting the AsyncIterable if the page navigates
2038
- * @return [description]
2039
- */
2040
- export function iterable_to_attribute(el: Element, attribute_name: string, async_iterable: AsyncIterable<string>, quit_after_navigation?: boolean): Element;
2041
- /**
2042
- * Merges an IPNS with `reactive_template` - if the IPNS updates the reactive template's state is updated to what the IPNS returns
2043
- * @param async_iterable The async iterable to use
2044
- * @param quit_after_navigation Whether to stop listening for the IPNS when navigating away
2045
- * @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.
2046
- */
2047
- export function iterable_to_elems(async_iterable: AsyncIterable<ReactiveTemplateValueContents>, quit_after_navigation?: boolean): Node_Array;
2048
- /**
2049
- * 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
2050
- * @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";
2051
- * @return A wrapped function that now executes in a context
2052
- */
2053
- export const prevent_infinite_loop: <A extends any[], B>(cb: (...args: A) => void | B) => (...args: A) => void | B;
2054
- /**
2055
- * Inserts one or multiple surfaces into the DOM.
2056
- * 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
2057
- * @param surfaces Array with surfaces to insert
2058
- * @param verb Verb on how to insert
2059
- * @param target Selector for `observer.onexists` to find element to insert VERBto, alternatively an element
2060
- * @param remove_after_navigation Whether to remove the elements from the DOM again if a navigation away occurs, defaults to true
2061
- * @param try_forever Whether to try to insert the same surface even after the page has navigated away, defaults to false
2062
- * @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
2063
- * @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
2064
- */
2065
- export function insert_surfaces<T extends Display>({ surfaces: input_surfaces, verb, target, remove_after_navigation, try_forever, preserve_elements, }: {
2066
- verb: InsertionVerb;
2067
- target: string | HTMLElement;
2068
- remove_after_navigation?: boolean;
2069
- try_forever?: boolean;
2070
- surfaces: (Promise<Surface<T> | void> | Surface<T> | void)[];
2071
- preserve_elements?: boolean;
2072
- }): Promise<{
2073
- surface: Surface<T>;
2074
- succeeded: boolean;
2075
- }>[];
2076
- export const revertable_remove: (target: string | Element | Node_Array, should_stay_inserted: Promise<boolean>) => Promise<void | undefined>;
2077
- type MakePlaceholderRROption<T extends Display> = {
2078
- override_rec_renderer?: (t: Tenant | null, rendering_options: Extended_RR_Options<T>) => Promise<RecRendererResult<T>>;
2079
- image_width?: number;
2080
- image_height?: number;
2081
- color?: string;
2082
- num_items?: number;
2083
- on_no_rendering_result?: (result?: RecRendererResult<T>) => any;
2084
- post_rendering?: (surface?: RecRendererResult<T>) => Promise<void> | void;
2085
- };
2086
- /**
2087
- * We want to deprecate this
2088
- */
2089
- export type PlaceholderRenderingDisplay = {
2090
- sale_price: number;
2091
- page_url: "#" | string;
2092
- image_url: string;
2093
- original_price: number;
2094
- product_id: "placeholder" | string;
2095
- recommendation_id: "placeholder" | string;
2096
- title: string;
2097
- brand: string;
2098
- };
2099
- export const random_text_placeholder: () => string;
2100
- export const placeholder_svg: (image_width: number, image_height: number, color?: string) => string;
2101
- /**
2102
- * 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.
2103
- * @param [override_rec_renderer=default_rr] The recommendation renderer to use
2104
- * @param [image_width=2000] Width of placeholder image svg (use to set aspect ratio)
2105
- * @param [image_height=2000] Height of placeholder image svg (use to set aspect ratio)
2106
- * @param [num_items=10] Number of placeholders to render
2107
- * @param [color="#d9d9d9"] Color of placeholder image svg
2108
- * @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
2109
- * @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
2110
- * @return It returns the same as a normal recommenation renderer would, meaning an object that might contain `displays` and `elements`
2111
- */
2112
- export function make_placeholder_rr<T extends Display>({ override_rec_renderer, image_width, image_height, num_items, color, on_no_rendering_result, post_rendering, }?: MakePlaceholderRROption<T>): Promise<(t: Tenant | null, rendering_options: Extended_RR_Options<T | PlaceholderRenderingDisplay>) => Promise<Record<string, never> | {
2113
- elements: Node_Array;
2114
- displays: T[];
2115
- }>>;
2116
- /**
2117
- * 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
2118
- * @return a WeakSet to add nodes to which you remove and want to ignore removal errors for
2119
- */
2120
- export function removeChild_error_swallowing_factory(): WeakSet<Node>;
2121
- /**
2122
- * 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)
2123
- * @return void
2124
- */
2125
- export function replace_promise_with_native_if_exists_and_enforce(): void;
2126
- /**
2127
- * Creates a blank iframe inside <head> and returns window.Promise out of it
2128
- * @return a pristine, unpolyfilled window.Promise
2129
- */
2130
- export function get_iframe_promise(): PromiseConstructor;
2131
- /**
2132
- * Proxies XMLHttpRequest.prototype.open to an open function which also calls the provided `fetch_handler` with useful information as parameter
2133
- * @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
2134
- * @return void
2135
- */
2136
- export function xhr_replace(fetch_handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, arg_array: Parameters<typeof XMLHttpRequest.prototype.open>) => void): void;
2137
- /**
2138
- * 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
2139
- * @param handler The function called on load of every XHR request.
2140
- * @return void
2141
- */
2142
- export function xhr_load(handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, event: ProgressEvent<XMLHttpRequestEventTarget>) => any): void;
2143
- 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>;
2144
- /**
2145
- * Intercepts someone reading `response`, `responseText` and `responseXML` on an XMLHttpRequest
2146
- * @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`.
2147
- */
2148
- 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>;
2149
- export function default_rp_fixes(orig_url?: string | undefined): Promise<void>;
2150
- export function rp_relativify_history(orig_url_with_trailing_slash: string): void;
2151
- export function rp_relativify_fetch(orig_url_with_trailing_slash: string): void;
2152
- export function rp_relativify_xhr(orig_url_with_trailing_slash: string): void;
2153
- /**
2154
- * 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.
2155
- */
2156
- export function sort_obj<T>(maybe_obj: T): any;
2157
- /**
2158
- * Tries to figure out the tenant's market (`TwoLetterMarket` for new integrations) through various means.
2159
- *
2160
- * 1. Checks if there is a market in one of the url segments (www.tentant.se/foo/se/bar)
2161
- * 2. Checks if the market is specified in the tenant's domain name (www.tenant-se.com)
2162
- * 3. Checks the toplevel domain (www.tenant.se/foo/bar)
2163
- *
2164
- * @param allowed_markets An array the possible markets for the tenant.
2165
- * Dont forget to specify the allowed market as const (`["se", "en"] as const`) to get the best typing
2166
- * @param url Specify this to overide the url to check, defaults to the current url
2167
- * @param tenant The tenant's name
2168
- * @returns If a market specified in `allowed_markets`was found that is returned, `undefined` otherwise
2169
- */
2170
- export function standard_get_market<T extends readonly string[]>(allowed_markets: T, url?: string, tenant?: string): T[number] | undefined;
2171
- /**
2172
- * Listens to localstorage changes with `setItem` and direct assignment.
2173
- * @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.
2174
- */
2175
- export function listenToLocalStorage(listener: (key: string, value: string) => void): void;
2176
- /**
2177
- * Timeout a promise after `ms` milliseconds.
2178
- * If the promise is timed out this function will return `undefined` and not throw.
2179
- */
2180
- export function timeout_promise<T>(promise: Promise<T>, ms: number): Promise<Awaited<T> | undefined>;
2181
- /**
2182
- * Uses the default Voyado ID that is used in Voyado email recommendations.
2183
- */
2184
- export const use_voyado_id: () => void | undefined;
2185
- type ButtonProps = Omit<Partial<JSX.IntrinsicElements["button"]>, "type"> & {
2186
- class?: string;
2187
- };
2188
- export function DefaultViewMoreButton({ children, ...attributes }: ButtonProps): HTMLButtonElement;
2189
- export function CrossIcon(props?: JSX.SvgSVGAttributes<SVGSVGElement>): HTMLElement;
2190
- export function GeneralSideSlidein({ title_, children, }: {
2191
- title_: IPNS<string>;
2192
- children: HTMLElement | HTMLElement[];
2193
- }): Promise<{
2194
- close_: VoidFunction;
2195
- on_close_: (fn: VoidFunction) => number;
2196
- }>;
2197
- export function GeneralSizeSelector({ title_, items_, out_of_stock_text_, }: {
2198
- title_: IPNS<string>;
2199
- out_of_stock_text_: IPNS<string>;
2200
- items_: {
2201
- id_: string;
2202
- size_name_: string;
2203
- is_available_: boolean;
2204
- }[];
2205
- }): Promise<string | void>;
2206
- type PlaceholderProps = Omit<Partial<JSX.IntrinsicElements["div"]>, "style"> & {
2207
- /** Any extra classes togheter with the default `depict-placeholder` class */
2208
- class?: string;
2209
- /** Convinence prop for setting element width */
2210
- width?: string;
2211
- /** Convinence prop for setting element height */
2212
- height?: string;
2213
- /** Will override the usage of width & height */
2214
- style?: string;
2215
- };
2216
- type PlaceholderImageProps = Omit<PlaceholderProps, "width" | "height" | "style"> & {
2217
- aspect_ratio: number;
2218
- };
2219
- /**
2220
- * A Placeholder with shimering animation.
2221
- * For text you can use `height="1em"`.
2222
- * For specific number of characters use `ch`, ex: `width="7ch"`
2223
- */
2224
- export const Placeholder: ({ width, height, class: extra_classes, style, ...attributes }: PlaceholderProps) => HTMLElement;
2225
- /**
2226
- * A wrapper of Placeholder with full width and maintained aspect ratio.
2227
- * @see {@link Placeholder}
2228
- */
2229
- export const ContainedPlaceholderImage: ({ aspect_ratio, ...attributes }: PlaceholderImageProps) => HTMLElement;
2230
- export const RecommendationContainer: (title?: string | HTMLElement, surface_classes?: string[]) => HTMLElement;
2231
- export const RightChevron: () => HTMLElement;
2232
- export const LeftChevron: () => HTMLElement;
2233
- export type ColorObj = {
2234
- /** the value passed as a css color */
2235
- value: string;
2236
- /** if specified, it's used as a title on hover */
2237
- label?: string;
2238
- /** Allow for arbitrary data to be passed */
2239
- [key: string]: any;
2240
- };
2241
- interface ColorPickerProps {
2242
- /** An array of colors that can be selected */
2243
- colors: ColorObj[];
2244
- onSelect: (color: ColorObj) => unknown;
2245
- /**
2246
- * Called everytime a color is hovered
2247
- */
2248
- onHoverUpdate?: (color: ColorObj, hovering: boolean) => unknown;
2249
- /**
2250
- * The color value to be initially selected. Can be omitted for no color to be selected.
2251
- * If multiple colors use the same hex value, the label can also be specified (using a ColorObj)
2252
- */
2253
- initialColor?: string | ColorObj;
2254
- /**
2255
- * Enabled hovering preview. When true `onSelect` will be called with a new color when it's hovered,
2256
- * then reverts back to the last clicked color when hovering is stopped
2257
- * */
2258
- selectOnHover?: boolean;
2259
- /**
2260
- * If set to true only `onSelect` will be called when an item is clicked
2261
- */
2262
- dontSetActiveOnClick?: boolean;
2263
- /**
2264
- * If only circles should be returned and not the container element
2265
- */
2266
- onlyCircles?: boolean;
2267
- }
2268
- /**
2269
- * A color selector, that calls onSelect when a color is clicked and optionally on hover as well.
2270
- */
2271
- export function createColorPicker({ colors, initialColor, onSelect, selectOnHover, onHoverUpdate, dontSetActiveOnClick, onlyCircles, }: ColorPickerProps): {
2272
- setActiveIndex: (index: number) => void | undefined;
2273
- ColorPicker(): HTMLElement;
2274
- };
2275
- /**
2276
- * For example how to use, check /src/glitter/main.tsx
2277
- * Warning: Don't use margins for the element you want to expand, since the animation will look janky
2278
- * EDIT: above no longer applies if you only have one element that you want to expand
2279
- */
2280
- export const useExpandingContainer: ({ duration, delay }?: {
2281
- duration?: number;
2282
- delay?: number;
2283
- }) => {
2284
- ExpandingContainer: ({ children }: {
2285
- children?: Elem | Elem[] | undefined;
2286
- }) => HTMLElement;
2287
- expand: (expanding_delay?: any, time_to_expand?: any) => Promise<Animation | undefined>;
2288
- collapse: (collapsing_delay?: any, time_to_collapse?: any) => Promise<Animation | undefined>;
2289
- };
2290
- export const resize_base_url: string;
2291
- export const is_safari: boolean;
2292
- /**
2293
- * 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
2294
- * @param what_to_watch Element to watch resizing of
2295
- * @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
2296
- * @param resolution_factor a factor to multiply the target-to-display resolution with
2297
- * @return A function that will set the `sizes` atribute of the provided element to the size of `what_to_watch`, continuously
2298
- */
2299
- export function make_sizes_setter(what_to_watch: HTMLElement, sizes_communicator?: IPNS<number>, resolution_factor?: number): (el_to_resize: HTMLSourceElement | HTMLImageElement) => Promise<void>;
2300
- /**
2301
- * This function returns a function that can be used as JSX component.
2302
- * It builds upon `make_sizes_setter` and uses it to set the `sizes` attribute of <source> and a fallback <img> tag that it creates.
2303
- * @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.
2304
- * @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.
2305
- * @param formats An array of formats supported by the backends "ResizeImage" to allow the browser to use
2306
- * @param resolutions An array of resolutions to generate a srcset for
2307
- * @param sizes_communicator IPNS of which the resolution sets the `sizes` attribute on the images
2308
- * @param sizes_setter_ a sizes setter returned by make_sizes_setter, you can provide one if you created it before creating the images
2309
- * @param resolution_factor a factor to multiply the target-to-display resolution with
2310
- * @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+)
2311
- *
2312
- * @example Per surface:
2313
- * `const SourcesetComponent = make_sourceset_component(first_canvas, true, ["webp", "png", "tiff"]);`
2314
- * and then instead of your <img> tags: `<SourcesetComponent data-src={d.image_url} class="image" />`
2315
- */
2316
- export function make_sourceset_component({ what_to_watch, set_dataset, formats, resolutions, sizes_communicator, resolution_factor, market_, sizes_setter_, }?: {
2317
- what_to_watch?: HTMLElement;
2318
- set_dataset?: boolean;
2319
- formats?: string[];
2320
- resolutions?: number[];
2321
- sizes_communicator?: IPNS<number>;
2322
- resolution_factor?: number;
2323
- market_?: string;
2324
- sizes_setter_?: ReturnType<typeof make_sizes_setter>;
2325
- }): (image_options: Partial<JSX.IntrinsicElements["img"]> & {
2326
- class?: string;
2327
- }) => HTMLElement;
2328
- /**
2329
- * Adds query parameters from the `params` parameter to the `base` url.
2330
- * Guaranteed to be correctly escaped and not doubled and perfectly formatted
2331
- * @param base base url, can be relative
2332
- * @param params an object like `{'param1': 'value'}` that will lead to `?param1=value` on the url
2333
- * @return an absolute URL with the added query parameters
2334
- */
2335
- export function make_url_with_query_params(base: string, params: {
2336
- [key: string]: any;
2337
- }): string;
2338
- export interface ImageOptions extends Partial<HTMLImageElement> {
2339
- aspect_ratio: number;
2340
- class?: string;
2341
- rendering_options?: RR_Options<any>;
2342
- srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2343
- alt: string;
2344
- remove_on_error?: boolean;
2345
- /**
2346
- * If true, inserts grey placeholder svg's before the image lazyloader and the sourceset component add the real source
2347
- */
2348
- init_with_placeholder?: boolean;
2349
- }
2350
- /**
2351
- * Contained image gives an image (a container with) intrinsic size of the given aspect ratio, filling out available space.
2352
- * It means that images with different aspect ratios will all take the same amount of space
2353
- * and the sides where it doesn't fit the aspect ratio will be filled with transparent.
2354
- * It makes sure the images doesn't get squished like setting `width` and `height` would do.
2355
- * @param aspect_ratio The aspect ratio of the image, i.e. 4/3 = 1,3̅
2356
- * @param alt Alt text of the image
2357
- * @param remove_on_error Whether to remove the image if loading fails
2358
- * @param rendering_options The rendering options. Please always provide this, it's only optional for compatibility reasons.
2359
- * You should provide the `rendering_options` to the second argument, InfoForProcessing, provided to a template or preprocessor.
2360
- * When provided to a postprocessor of a recommendation-renderer it will be the third argument
2361
- * If you provide this, ContainedImage will automatically use `make_sourceset_component`
2362
- * and the image resizing proxy to get you responsive images in a modern format (webp).
2363
- * @param srcset_opts The options passed to `make_sourceset_component`, only used if `rendering_options` is set.
2364
- * @param Everything else: attributes on the <img> tag
2365
- * @returns It depends on options and build target. But it's always one HTMLElement.
2366
- */
2367
- export const ContainedImage: ({ init_with_placeholder, ...options }: ImageOptions) => HTMLElement;
2368
- type HoverImageOptions = ImageOptions & {
2369
- mobile_touch_hover?: boolean;
2370
- extra_container_class?: string;
2371
- main_extra_classes?: string;
2372
- second_src?: string;
2373
- second_srcset?: string;
2374
- second_srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2375
- fade_length_seconds?: number;
2376
- /** The minimum amount of time for a touch to be considered a link click */
2377
- navigation_minimum_ms?: number;
2378
- };
2379
- export const ContainedHoverImage: ({ second_src, second_srcset, second_srcset_opts, fade_length_seconds, mobile_touch_hover, navigation_minimum_ms, ...options }: HoverImageOptions) => HTMLElement;
2380
- export function ArrowUp(): HTMLElement;
2381
- export function BackIcon(): HTMLElement;
2382
- export function FilterIcon(): HTMLElement;
2383
- export function GenericSliderArrowButton({ width_, height_ }?: {
2384
- width_?: number;
2385
- height_?: number;
2386
- }): SVGElement;
2387
- export function MinusIcon(): HTMLElement;
2388
- export function PlusIcon(props: JSX.SvgSVGAttributes<SVGSVGElement>): HTMLElement;
2389
- export function PreviousSearchIcon(): HTMLElement;
2390
- export function SearchIcon(props?: JSX.SvgSVGAttributes<SVGSVGElement>): HTMLElement;
2391
- export function SortIconAsc(props?: JSX.SvgSVGAttributes<SVGSVGElement>): SVGElement;
2392
- export function SortIconDesc(props?: JSX.SvgSVGAttributes<SVGSVGElement>): HTMLElement;
2393
- export function TickIcon(props?: JSX.SvgSVGAttributes<SVGSVGElement>): HTMLElement;
2394
- /**
2395
- * Shallowly converts all keys in an object from snake_case to camelCase.
2396
- * Does not support symbol keys.
2397
- *
2398
- * @param obj the object. It will be cloned and not modified in-place.
2399
- */
2400
- export function camelCasifyObject<T extends {
2401
- [key: string]: any;
2402
- }, X extends T = T>(obj: T): X;
2403
- /**
2404
- * Shallowly converts all keys in an object from camelCase to snake_case.
2405
- * Does not support symbol keys.
2406
- * @param obj the object. It will be cloned and not modified in-place.
2407
- */
2408
- export function snakeCasifyObject<T extends {
2409
- [key: string]: any;
2410
- }, X extends T = T>(obj: T): X;
2411
- /**
2412
- * Converts RGB to HSL
2413
- * Source of function: https://www.30secondsofcode.org/js/s/rgb-to-hsl
2414
- */
2415
- export function rgb_to_hsl(r: number, g: number, b: number): readonly [number, number, number];
2416
- /**
2417
- * Converts HSL to RGB
2418
- * Source of function: https://www.30secondsofcode.org/js/s/hsl-to-rgb
2419
- */
2420
- export function hsl_to_rgb(h: number, s: number, l: number): readonly [number, number, number];
2421
- /**
2422
- * Converts HSV (or HSB, it's the same) to RGB.
2423
- * Source of function: https://www.30secondsofcode.org/js/s/hsb-to-rgb/
2424
- */
2425
- export function hsb_to_rgb(h: number, s: number, b: number): readonly [number, number, number];
2426
- /**
2427
- * Calculates the relative luminance of a RGB color
2428
- * Source: https://gist.github.com/jfsiii/5641126
2429
- */
2430
- export function relative_luminance_from_rgb(R8bit: number, G8bit: number, B8bit: number): number;
2
+ import { EUnavailabilityType } from "@depict-ai/types/api/TrackV2Request";
3
+ export const version = "1.0.13";
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: [
212
+ url: ConstructorParameters<typeof AutoReconnectingWS>[0],
213
+ protocols?: ConstructorParameters<typeof AutoReconnectingWS>[1],
214
+ options?: ConstructorParameters<typeof AutoReconnectingWS>[2] & Partial<{
215
+ initial_retry_ms: number;
216
+ }>
217
+ ]);
218
+ }
219
+ /**
220
+ * Returns a random string
221
+ * @return A random string, containing a-z, 0-9 and occasionally a dot (`.`)
222
+ */
223
+ export function random_string(): string;
224
+ export function make_random_classname(): string;
225
+ export const base_url: string;
226
+ export type event_types = "page_view" | "click" | "add_to_cart" | "purchase" | "element_visible";
227
+ 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"];
228
+ export type depict_body = Partial<{
229
+ [K in (typeof allowed_keys)[number]]: any;
230
+ }>;
231
+ export type depict_payload = depict_body[];
232
+ type any_properties = {
233
+ [key: string]: any;
234
+ };
235
+ export type noisy_depict_payload = (depict_body & any_properties)[];
236
+ export const filter_depict_payload: (payload: noisy_depict_payload) => depict_payload | undefined;
237
+ export const send_websocket: (bodies: depict_payload) => Promise<void | undefined>;
238
+ export const send_depict_unfiltered: (payload: depict_payload, use_ws?: any) => boolean | Promise<void | undefined> | undefined;
239
+ export const foolproof_send_beacon: (url: string, payload: {
240
+ [key: string]: any;
241
+ }) => boolean | undefined;
242
+ export const send_depict: (payload: noisy_depict_payload, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
243
+ export let get_depict_id: () => string;
244
+ export let get_user_id: () => string;
245
+ export let get_session_id: () => string | undefined;
246
+ export const set_depict_id_fn: (newfn: () => string) => (() => string) | undefined;
247
+ export const set_user_id_fn: (newfn: () => string) => (() => string) | undefined;
248
+ export const set_session_id_fn: (newfn: () => string) => (() => string) | undefined;
249
+ export type TrackingEventContextData = {
250
+ user_id: string;
251
+ dsid: string;
252
+ session_id?: string;
253
+ url: string;
254
+ document_width: number;
255
+ document_referrer: string;
256
+ };
257
+ export const get_tracking_event_context_data: () => TrackingEventContextData;
258
+ /**
259
+ * Sends a depict tracking event with prefilled data
260
+ */
261
+ export const depict_prefilled: (vars: Partial<{
262
+ type: any;
263
+ detail: any;
264
+ url: any;
265
+ currency: any;
266
+ tenant: any;
267
+ market: any;
268
+ user_id: any;
269
+ session_id: any;
270
+ product_id: any;
271
+ entity_identifiers: any;
272
+ entity_price: any;
273
+ document_referrer: any;
274
+ document_width: any;
275
+ attribution_id: any;
276
+ recommendation_id: any;
277
+ click_location: any;
278
+ ab_test_group: any;
279
+ variant_ids: any;
280
+ dsid: any;
281
+ transaction_id: any;
282
+ error_type: any;
283
+ recommendation_type: any;
284
+ search_result_id: any;
285
+ product_listing_result_id: any;
286
+ }> & {
287
+ [key: string]: any;
288
+ }, use_ws?: boolean | undefined) => boolean | Promise<void | undefined> | undefined;
289
+ export const depict_click: (vars: Partial<{
290
+ type: any;
291
+ detail: any;
292
+ url: any;
293
+ currency: any;
294
+ tenant: any;
295
+ market: any;
296
+ user_id: any;
297
+ session_id: any;
298
+ product_id: any;
299
+ entity_identifiers: any;
300
+ entity_price: any;
301
+ document_referrer: any;
302
+ document_width: any;
303
+ attribution_id: any;
304
+ recommendation_id: any;
305
+ click_location: any;
306
+ ab_test_group: any;
307
+ variant_ids: any;
308
+ dsid: any;
309
+ transaction_id: any;
310
+ error_type: any;
311
+ recommendation_type: any;
312
+ search_result_id: any;
313
+ product_listing_result_id: any;
314
+ }> & {
315
+ [key: string]: any;
316
+ }) => boolean | Promise<void | undefined> | undefined;
317
+ export const depict_add_to_cart: (vars: Partial<{
318
+ type: any;
319
+ detail: any;
320
+ url: any;
321
+ currency: any;
322
+ tenant: any;
323
+ market: any;
324
+ user_id: any;
325
+ session_id: any;
326
+ product_id: any;
327
+ entity_identifiers: any;
328
+ entity_price: any;
329
+ document_referrer: any;
330
+ document_width: any;
331
+ attribution_id: any;
332
+ recommendation_id: any;
333
+ click_location: any;
334
+ ab_test_group: any;
335
+ variant_ids: any;
336
+ dsid: any;
337
+ transaction_id: any;
338
+ error_type: any;
339
+ recommendation_type: any;
340
+ search_result_id: any;
341
+ product_listing_result_id: any;
342
+ }> & {
343
+ [key: string]: any;
344
+ }) => boolean | Promise<void | undefined> | undefined;
345
+ export type ConsentObj = {
346
+ marketing: boolean;
347
+ necessary: boolean;
348
+ preferences: boolean;
349
+ statistics: boolean;
350
+ };
351
+ export function get_cookie(cookie_name: string): string | undefined;
352
+ export function Promise_Any<T>(promises: (T | PromiseLike<T>)[] | Iterable<T | PromiseLike<T>>): Promise<T>;
353
+ /**
354
+ * Broadcasts the product id of the current page to a BroadcastChannel `right_click_attribution`.
355
+ * 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.
356
+ */
357
+ export function broadcast_product_id(product_id: string): Promise<void>;
358
+ /**
359
+ * 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)
360
+ * @param elements Elements that event listeners will be added on
361
+ * @param display The display to take the product_id from
362
+ * @param info InfoForProcessing to get Tenant instance out of
363
+ * @return `elements` 1:1
364
+ */
365
+ 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;
366
+ /**
367
+ * This is the event handler for the new tab tracking function (add_new_tab_listener)
368
+ * @param e Click event
369
+ * @param product_id product_id of clicked product
370
+ * @return A promise resolving to void after 60s or when the product id was broadcasted
371
+ */
372
+ export function contextmenu_callback(e: Event, product_id: string): Promise<void>;
373
+ /**
374
+ * Make parts of a type optional
375
+ *
376
+ * From: https://github.com/Microsoft/TypeScript/issues/25760#issuecomment-614417742
377
+ */
378
+ type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>;
379
+ export class ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
380
+ constructor(opts: {
381
+ element_: ElemType;
382
+ selector_: SelectorType;
383
+ disconnector_: Disconnector;
384
+ mutation_record_?: MutationRecord;
385
+ event_?: ListenerNames;
386
+ });
387
+ }
388
+ export interface ElementObserverEvent<ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode> {
389
+ element: ElemType;
390
+ selector: SelectorType;
391
+ disconnector: Disconnector;
392
+ mutation_record?: MutationRecord;
393
+ event?: ListenerNames;
394
+ }
395
+ /**
396
+ * Element.querySelectorAll is broken in Chrome 37-latest, use this instead.
397
+ * Related bug: https://bugs.chromium.org/p/chromium/issues/detail?id=1286047
398
+ * @param element Quite broadly anything you'd normaly call querySelectorAll on, including "null"
399
+ * @param selector The selector to search for
400
+ * @return Stock return value
401
+ */
402
+ export function patched_querySelectorAll<T extends Element>(element: Element | Document | DocumentFragment | null, selector: string): NodeListOf<T> | T[] | undefined;
403
+ export interface ElementObserver {
404
+ /**
405
+ * Immediately calls the callback with an ElementObserverEvent for nodes existing in the DOM that match the provided selector OR are the selector,
406
+ * also calls the callback with an ElementObserverEvent whenever ANYTHING in the DOM occurs that makes an element match the provided selector.
407
+ * @param selector Selector string or element to listen for
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
+ onexists: EO_listener_also_taking_els;
411
+ /**
412
+ * Dispatches an ElementObserverEvent whenever a node is added to 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
+ oncreation: EO_listener_also_taking_els;
417
+ /**
418
+ * Dispatches an ElementObserverEvent whenever a node is removed from the DOM that matches the specified selector OR is the selector.
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
+ onremoved: EO_listener_also_taking_els;
423
+ /**
424
+ * Dispatches an ElementObserverEvent whenever a node that matches the specified selector or its children change in the DOM.
425
+ * @param selector CSS selector or element to observe
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
+ onchange: EO_listener;
429
+ /**
430
+ * Immediately calls the callback with an ElementObserverEvent on nodes that match the provided selector OR are the selector.
431
+ * @param selector Selector string or element to look for in the DOM
432
+ * @param callback Function that will be called with the ElementObserverEvent. Exceptions and promise rejections of the callback will be caught and sent to sentry.
433
+ */
434
+ ifexists: EO_listener_also_taking_els;
435
+ /**
436
+ * See docs for observer.onexists. Will return a Promise that resolves to the element out of the first call of an observer.onexists callback.
437
+ * @param selector Selector string or element to wait for
438
+ * @param timeout timeout to stop listening and resolve the Promise with `undefined`
439
+ */
440
+ wait_for_element: <ElemType extends HTMLElement = HTMLElement>(selector: string | ElemType, timeout?: number) => Promise<ElemType>;
441
+ /**
442
+ * 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
443
+ * @param listener one of the possible functions on ElementObserver that start with "on", without the "on". So "creation", "change", "exists" or "removed"
444
+ * @param selector String containing CSS selector
445
+ * @param timeout timeout to stop listening and resolve the Promise with `undefined`
446
+ */
447
+ 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>;
448
+ }
449
+ export class ElementObserver {
450
+ #private;
451
+ constructor(options?: {
452
+ territory?: HTMLElement | Document | DocumentFragment;
453
+ });
454
+ }
455
+ type EO_listener = <ElemType extends HTMLElement = HTMLElement>(selector: string, callback: ObserverCallbackFunction<ElemType>) => Disconnector;
456
+ type EO_listener_also_taking_els = <ElemType extends CallbackableNode = HTMLElement, SelectorType extends string | CallbackableNode = string | CallbackableNode>(selector: SelectorType, callback: ObserverCallbackFunction<ElemType, SelectorType>) => Disconnector;
457
+ type ListenerNames = "exists" | "creation" | "removed" | "change";
458
+ type ObserverCallbackFunction<ElemType extends CallbackableNode, SelectorType extends string | CallbackableNode = string | CallbackableNode> = (event: ElementObserverEvent<ElemType, SelectorType>) => any;
459
+ export type Disconnector = () => unknown;
460
+ type CallbackableNode = Element | Text | Comment;
461
+ /**
462
+ * 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.
463
+ */
464
+ export const observer: ElementObserver;
465
+ /**
466
+ * 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
467
+ * @param numSteps How many steps (notifications) there should be between 0 and 100% intersection
468
+ * @return Stuff to give to IntersectionObserver
469
+ */
470
+ export function buildThresholdList(numSteps: number): number[];
471
+ /**
472
+ * A Post processor for Recommendation renderer to add impression tracking to all displays
473
+ */
474
+ export const impression_tracking_post_processor: RR_PostProcessor<any>;
475
+ interface ImpressionTrackingOptions {
476
+ /** The element to observe for impressions. */
477
+ element: HTMLElement;
478
+ /** The impression data to send to the api (this is combined with context data) */
479
+ data: ExplicitImpressionEventData;
480
+ /** When true the element will be observed by the IntersectionObserver only after it's inserted into the DOM.
481
+ * Sometimes with a pollyfilled IntersectionObserver it ignores elements that are not in the DOM yet.
482
+ * Defaults to true.
483
+ * */
484
+ wait_for_dom_insertion?: boolean;
485
+ }
486
+ /**
487
+ * Registers the passed element for impression tracking.
488
+ * The element will be observed for intersection with the viewport.
489
+ * Also handles sending the impression event.
490
+ *
491
+ * @return A function to stop observing the element for impressions
492
+ */
493
+ export const impression_track_element: ({ element, data, wait_for_dom_insertion, }: ImpressionTrackingOptions) => () => void;
494
+ /** The start and end visibility threshold for an intersection to count as an impression */
495
+ export let impression_threshold: number[];
496
+ export const set_impression_threshold: (start: number, end: number) => number[];
497
+ /** The minimum duration the element has to be visible above the thresholds before it counts as an impression */
498
+ export const has_to_be_intersecting_for = 500;
499
+ /** What explicit information is needed to form an ImpressionEvent */
500
+ export type ExplicitImpressionEventData = {
501
+ recommendation_type?: string;
502
+ entity_price?: number;
503
+ market?: string;
504
+ tenant?: string;
505
+ product_id?: string;
506
+ } & ({
507
+ recommendation_id: string;
508
+ } | {
509
+ search_result_id: string;
510
+ } | {
511
+ product_listing_result_id: string;
512
+ } | {
513
+ suggestions_result_id: string;
514
+ });
515
+ /** What an impression event looks like when sent to the api */
516
+ export type ImpressionEvent = {
517
+ /** The type for impression events should be element_visible */
518
+ type: "element_visible";
519
+ } & (ExplicitImpressionEventData | TrackingEventContextData);
520
+ /**
521
+ * Sends an impression event to the api.
522
+ *
523
+ * Impression events always use websockets.
524
+ */
525
+ export const send_impression_event: (data: Optional<ImpressionEvent, "type">) => void;
526
+ /**
527
+ * 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
528
+ * @param {HTMLElement} a_element - The element to listen on the "click event"
529
+ * @param {string} product_id - A unique identifier for the product which can be used to rerecognize it on the product page
530
+ * @param {string} recommendation_id - The recommendation ID of the recommendation
531
+ * @param {Function} additional_listener - An additional function to execute onclick
532
+ */
533
+ export function bind_tracking_to_link(a_element: Element, product_id: string, recommendation_id: string, additional_listener?: Function): ((e: Event) => void) | undefined;
534
+ export type A2CTrackingFunction = (product_id: string, recommendation_id: string, was_unmatching: boolean, event: Event) => any;
535
+ /**
536
+ * 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
537
+ * @param {HTMLElement} button - The element to listen on the "click event"
538
+ * @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
539
+ * @param {A2CTrackingFunction} tracking_fn - A function which gets executed on click of button
540
+ * @param {Boolean} [unmatching_tracking] - also call tracking_fn on products not found in localStorage.
541
+ */
542
+ 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>;
543
+ type after_navig_fn = (arg0: Parameters<typeof history.replaceState | typeof history.pushState>, what_happened: "replaceState" | "pushState") => any;
544
+ /**
545
+ * AsyncIterable which resolves with the new href every time location.href changes
546
+ */
547
+ export const stateless_href_change_ipns: IPNS<string>;
548
+ /**
549
+ * AsyncIterable which resolves when you await it with the current href and then once every time it changes
550
+ */
551
+ export const href_change_ipns: IPNS<string>;
552
+ /**
553
+ * Functions to instantly (synchronously) call when a "popstate" event occurs, before the href_change_ipns' resolve
554
+ * 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.
555
+ */
556
+ 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>;
557
+ export function on_next_navigation(callback: (new_href: string) => void): Promise<void>;
558
+ /**
559
+ * 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.
560
+ * Please also consider adding a listener to the `popstate` event (`window.addEventListener("popstate", handler)`) to cover ALL navigation possibilities.
561
+ * @param after_navigation Function to call after history.replaceState and history.pushState
562
+ * @param replace_replaceState=true Whether to call the function also on history.replaceState.
563
+ * @return Void
564
+ */
565
+ export function history_replacer(after_navigation: after_navig_fn, replace_replaceState?: boolean): Promise<void>;
566
+ interface TrackingData {
567
+ /** The active market, if any */
568
+ market?: string;
569
+ /** The merchant id */
570
+ tenant: string;
571
+ }
572
+ export interface PageViewEventData extends TrackingData {
573
+ /** If the page is a pdp, include the product_id */
574
+ product_id?: string;
575
+ }
576
+ export interface PageViewTrackingData extends TrackingData {
577
+ /** A function that returns the product_id of the product being displayed on href,
578
+ * if the href points to a PDP */
579
+ get_product_id: (href: string) => string | undefined | Promise<string | undefined>;
580
+ }
581
+ /**
582
+ * Sends a page_view event to Depict tracking if it hasn't been sent yet for the current page url
583
+ * 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
584
+ * @return A promise resolving to void
585
+ */
586
+ export function send_page_view_if_needed(data: PageViewEventData): Promise<void>;
587
+ /**
588
+ * Sends a page_view event to Depict tracking, and another one any time the page URL changes
589
+ */
590
+ export function send_page_view_on_navigation(data: PageViewTrackingData): Promise<void>;
591
+ export function make_tracker_send_to_depict(ga_tracker: any, append_to_url?: string): void;
592
+ export function create_ga_queue(): void;
593
+ /**
594
+ * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
595
+ * @return Current consent status, whether selected or not
596
+ */
597
+ export const cookiebot_get_consent: () => any;
598
+ /**
599
+ * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
600
+ * @return Consent status, once selected
601
+ */
602
+ export function cookiebot_wait_for_consent(): Promise<boolean>;
603
+ /**
604
+ * Returns an IPNS that resolves with initial consent when Cookiebot has loaded, or immediately if a consent cookie already exists.
605
+ * As well as a new consent object every time the consent status has changed
606
+ * @return An IPNS resolving to the consent object
607
+ */
608
+ export function cookiebot_get_cookie_ipns(): IPNS<ConsentObj>;
609
+ /**
610
+ * Anonymize Depict id until required consent level has been given through Cookiebot.
611
+ *
612
+ * This can be used for tenants using Cookiebot for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
613
+ * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
614
+ * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
615
+ *
616
+ * 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}.
617
+ */
618
+ export const init_cookiebot_tracking: (anon_id?: any) => Promise<void | undefined>;
619
+ declare global {
620
+ interface Window {
621
+ Cookiebot?: {
622
+ name: string;
623
+ consented: boolean;
624
+ declined: boolean;
625
+ changed: boolean;
626
+ hasResponse: boolean;
627
+ consentID: string;
628
+ consent: Consent;
629
+ isOutsideEU: boolean;
630
+ isOutOfRegion: boolean;
631
+ host: string;
632
+ domain: string;
633
+ currentPath: string;
634
+ doNotTrack: boolean;
635
+ consentLevel: string;
636
+ isRenewal: boolean;
637
+ forceShow: boolean;
638
+ dialog: null;
639
+ responseMode: string;
640
+ serial: string;
641
+ scriptId: string;
642
+ scriptElement: ScriptElement;
643
+ whitelist: any[];
644
+ cookieList: CookieList;
645
+ pathlist: any[];
646
+ userIsInPath: boolean;
647
+ cookieEnabled: boolean;
648
+ versionChecked: boolean;
649
+ versionRequested: boolean;
650
+ version: number;
651
+ latestVersion: number;
652
+ isNewVersion: boolean;
653
+ CDN: string;
654
+ source: string;
655
+ retryCounter: number;
656
+ frameRetryCounter: number;
657
+ bulkConsentFrameRetryCounter: number;
658
+ setOnloadFrameRetryCounter: number;
659
+ optOutLifetime: number;
660
+ consentLifetime: null;
661
+ framework: string;
662
+ hasFramework: boolean;
663
+ frameworkBlocked: boolean;
664
+ frameworkLoaded: boolean;
665
+ iframeReady: boolean;
666
+ iframe: Iframe;
667
+ bulkconsent: null;
668
+ bulkresetdomains: any[];
669
+ bulkconsentsubmitted: boolean;
670
+ isbulkrenewal: boolean;
671
+ wipe: Wipe;
672
+ consentUTC: Date;
673
+ IABConsentString: string;
674
+ GACMConsentString: string;
675
+ dataLayerName: string;
676
+ loaded: boolean;
677
+ autoblock: boolean;
678
+ mutationObserver: null;
679
+ mutationCounter: number;
680
+ mutationFallback: boolean;
681
+ mutationFallbackDocAttributes: any[];
682
+ mutationHandlerFallbackCharsetLoaded: boolean;
683
+ mutationAppName: string;
684
+ mutationEventListeners: any[];
685
+ mutationOnloadEventListeners: any[];
686
+ mutateEventListeners: boolean;
687
+ mutationHandlerFirstScript: null;
688
+ postPonedMutations: any[];
689
+ nonAsyncMutations: any[];
690
+ deferMutations: any[];
691
+ geoRegions: any[];
692
+ userCountry: string;
693
+ userCulture: string;
694
+ windowOnloadTriggered: boolean;
695
+ botDetectionDisabled: boolean;
696
+ regulations: Regulations;
697
+ regulationRegions: RegulationRegions;
698
+ commonTrackers: CommonTrackers;
699
+ configuration: Configuration;
700
+ inlineConfiguration: null;
701
+ processLinkClickCounter: number;
702
+ performanceEntriesCounter: number;
703
+ OverrideEventListenersOnloadFired: any[];
704
+ OverrideEventListenersOnloadToFire: any[];
705
+ fallbackScriptNodes: any[];
706
+ fallbackDeferNodes: any[];
707
+ };
708
+ }
709
+ }
710
+ export interface CommonTrackers {
711
+ domains: Domain[];
712
+ }
713
+ export interface Domain {
714
+ d: string;
715
+ c: number[];
716
+ }
717
+ export interface Configuration {
718
+ loaded: boolean;
719
+ loadRetry: number;
720
+ tags: any[];
721
+ trackingDomains: any[];
722
+ }
723
+ export interface Consent {
724
+ stamp: string;
725
+ necessary: boolean;
726
+ preferences: boolean;
727
+ statistics: boolean;
728
+ marketing: boolean;
729
+ }
730
+ export interface CookieList {
731
+ cookieTablePreference: any[];
732
+ cookieTableStatistics: any[];
733
+ cookieTableAdvertising: any[];
734
+ cookieTableUnclassified: any[];
735
+ }
736
+ export interface Iframe {
737
+ cookieconsentDataStyleDisplay: string;
738
+ mtjQuery171028673205955022363: number;
739
+ }
740
+ export interface RegulationRegions {
741
+ gdpr: string[];
742
+ ccpa: string[];
743
+ lgpd: string[];
744
+ }
745
+ export interface Regulations {
746
+ gdprApplies: boolean;
747
+ ccpaApplies: boolean;
748
+ lgpdApplies: boolean;
749
+ }
750
+ export interface ScriptElement {
751
+ }
752
+ export interface Wipe {
753
+ preferences: boolean;
754
+ statistics: boolean;
755
+ marketing: boolean;
756
+ }
757
+ /**
758
+ * Returns current consent status synchronously, meaning the user might not have seen the dialog yet (in which case this will return false)
759
+ * @return Current consent status, whether selected or not
760
+ */
761
+ export const optanon_get_consent: () => any;
762
+ /**
763
+ * Returns an promise that resolves when the end user has selected to grant or withold tracking consent.
764
+ * @return Consent status
765
+ */
766
+ export function optanon_wait_for_consent(): Promise<boolean>;
767
+ /**
768
+ * Returns an IPNS that resolves with initial consent when Optanon has loaded, or immediately if a consent cookie already exists.
769
+ * As well as a new consent object every time the consent status has changed
770
+ * @return An IPNS resolving to the consent object
771
+ */
772
+ export function optanon_get_cookie_ipns(): IPNS<ConsentObj>;
773
+ /**
774
+ * Anonymize Depict id until required consent level has been given through OneTrust's Optanon.
775
+ *
776
+ * This can be used for tenants using OneTrust for privacy policy. It will set {@link get_depict_id} to return "anonymous" until
777
+ * required consent level has been given. The required consent level is defined by env.DEPICT_TRACKING_CONSENT_LEVEL.
778
+ * It will do a initial check for existing cookie with the required consent to avoid sending "anonymous" even if we have required consent.
779
+ *
780
+ * 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}.
781
+ */
782
+ export const init_optanon_tracking: (anon_id?: any) => Promise<void | undefined>;
783
+ export const load_gtag: (GA_ID: string, strict?: boolean | undefined) => Promise<void | undefined>;
784
+ export const setup_gtag: (GA_ID: string) => void | undefined;
785
+ export const gtag_view: <T extends Display>(raw_displays: T[], get_product_id: (url?: string | T | undefined) => string | Promise<string>, more?: {
786
+ [key: string]: any;
787
+ list_name?: string | undefined;
788
+ } | ((display: T) => {
789
+ [key: string]: any;
790
+ }) | undefined) => Promise<void | undefined>;
791
+ export const gtag_click: (product_id: string | number, index: number, more?: object | undefined) => Promise<any>;
792
+ export const send_ga: (action: string) => any;
793
+ export const setup_ga: (GAID: string) => void | undefined;
794
+ export const ga_rec_click: () => any;
795
+ export const ga_purchase_click: () => any;
796
+ export const insert_styling: (css: string) => Promise<void | undefined>;
797
+ /**
798
+ * A function meant to use to track the main add to cart button on the product page of an integration.
799
+ * * @param tenant instance of `Tenant` class
800
+ * @param selector The selector to use to find the button
801
+ * @param validator A function that can invalidate the click event before tracking is sent
802
+ * @return A `Disconnector` to stop looking for more add to cart buttons to track
803
+ */
804
+ export const track_a2c: (tenant: Tenant, selector: string, validator?: ((e: Event) => boolean) | undefined) => Disconnector;
805
+ /**
806
+ * Basically a RecRendererResult with less strict typing
807
+ */
808
+ export interface Surface<T extends Display> {
809
+ elements?: Node_Array;
810
+ displays?: T[];
811
+ should_stay_inserted?: Promise<boolean>;
812
+ }
813
+ /**
814
+ * Functions existing on ChildNode that are commonly used to insert recommendations into the DOM
815
+ */
816
+ export type InsertionVerb = "after" | "before" | "replaceWith" | "append" | "prepend" | "replaceChildren";
817
+ /**
818
+ * Tries to extract a product id from an url.
819
+ * The method used to retrive product id used here is very narrow, probably better to use something else instead?
820
+ *
821
+ * @example normal_get_product_id("www.foo.com/bar/baz.html") // "baz"
822
+ *
823
+ * @param url The url to check, defaults to `window.location`
824
+ * @returns
825
+ */
826
+ export const normal_get_product_id: (url?: string) => string;
827
+ declare global {
828
+ interface Document {
829
+ depictwashere: boolean;
830
+ }
831
+ }
832
+ /**
833
+ * If you need custom market logic that {@link depict_init_with_market_logic} doesn't support then use this function.
834
+ *
835
+ * Used to initialize an integration-script, this should always be the entrypoint of an integration.
836
+ *
837
+ * Makes sure that your script doesn't run twice
838
+ */
839
+ export const depict_init: (callback: () => Promise<void>) => void;
840
+ /**
841
+ * Initialize an integration-script like {@link depict_init}, but with automatic handling of unsupported and unknown markets.
842
+ *
843
+ * @param options.extract_market A function that extracts the current market, and if the market is supported, unsupported or unknown
844
+ * @param options.callback If `extract_market` returned a supported market, calls `depict_init` with this callback.
845
+ * @param options.supported_markets Markets where our script should run, in order to get the best typechecking you should add a `as const`
846
+ * modifier to this type like so `["foo", "bar"] as const`.
847
+ * @param options.unsupported_markets Markets we are aware of and where our script shouldn't run.
848
+ * @param options.preferred_demo_market Market to use on .demo.depict.ai, if an override is needed for all users.
849
+ * depict-override-market query parameter will override this behaviour.
850
+ *
851
+ * ### Behaviour
852
+ *
853
+ * - market is unsupported - log to console and exit
854
+ * - market is unknown - report to sentry and exit
855
+ *
856
+ * ### Override market
857
+ *
858
+ * When running in debug mode the market can be overridden by setting a `depict-override-market` query param.
859
+ * For example http://tenant.domain?depict-override-market=ez
860
+ */
861
+ 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;
862
+ type IdType = string | undefined | Promise<string | undefined>;
863
+ export interface Tenant<ProductId extends IdType> {
864
+ TENANT: string;
865
+ tenant: string;
866
+ MARKET: TwoLetterMarket;
867
+ market: TwoLetterMarket;
868
+ TYPE: string;
869
+ type: string;
870
+ GA_ID: string;
871
+ gaid: string;
872
+ get_product_id: (url?: string) => ProductId extends string | undefined ? string : Promise<string>;
873
+ product_id: (url?: string) => string | Promise<string>;
874
+ dataset: DOMStringMap;
875
+ modify: boolean;
876
+ is_debug: boolean;
877
+ debug: boolean;
878
+ dlog: typeof dlog;
879
+ Sentry: typeof Sentry;
880
+ catchify: typeof catchify;
881
+ err: (...errors: any[]) => undefined;
882
+ }
883
+ /**
884
+ * 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"`
885
+ * @param options A object with constructor options
886
+ */
887
+ export class Tenant<ProductId extends IdType = IdType> {
888
+ constructor(options: {
889
+ TENANT?: string;
890
+ TYPE?: string;
891
+ MARKET: TwoLetterMarket;
892
+ GA_ID: string;
893
+ get_product_id: (url?: string) => ProductId;
894
+ current_script_override?: HTMLScriptElement;
895
+ pageview_tracking?: boolean;
896
+ });
897
+ }
898
+ /**
899
+ * This is a list of alpha-2 country codes plus some two letter combinations commonly used to describe markets
900
+ */
901
+ 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";
902
+ type ImpressionTrackOptions = {
903
+ t?: Tenant;
904
+ impression_tracking?: false;
905
+ } | {
906
+ impression_tracking: true;
907
+ t: Tenant;
908
+ };
909
+ type TenantSpecificationOptions = {
910
+ t?: Tenant;
911
+ tenant: string;
912
+ market: string;
913
+ get_product_id: (url?: string) => string | Promise<string>;
914
+ } | {
915
+ t: Tenant;
916
+ tenant?: string;
917
+ market?: string;
918
+ get_product_id?: (url?: string) => string | Promise<string>;
919
+ };
920
+ type ElementDiscoveryOptions = {
921
+ product_selector: string;
922
+ product_elements?: null | void | undefined;
923
+ } | {
924
+ product_selector?: null | void | undefined;
925
+ product_elements: HTMLElement[];
926
+ };
927
+ type A2CButtonDiscoveryOptions = {
928
+ a2c_selector: string;
929
+ a2c_elements?: null | void | undefined;
930
+ } | {
931
+ a2c_selector?: null | void | undefined;
932
+ a2c_elements: HTMLElement[];
933
+ };
934
+ /**
935
+ * @deprecated Please use DPC instead.
936
+ * Does not support ModernDisplays.
937
+ */
938
+ export const AIO: (options: {
939
+ attempt_gtag_view_tracking?: boolean | undefined;
940
+ no_gtag?: boolean | undefined;
941
+ shade?: boolean | undefined;
942
+ always_track_a2c?: boolean | undefined;
943
+ get_rec_id?: ((elem: HTMLElement) => string | undefined) | undefined;
944
+ get_prod_id?: ((elem: HTMLElement) => (string | undefined) | Promise<string | undefined>) | undefined;
945
+ get_ga_prod_id?: ((elem: HTMLElement) => string | undefined | Promise<string | undefined>) | undefined;
946
+ click_location_prefix?: ((elem: HTMLElement) => string | undefined) | undefined;
947
+ rec_a2c_selector?: string | undefined;
948
+ rec_a2c_unbubbled?: boolean | undefined;
949
+ get_display?: ((elem: HTMLElement) => Partial<LegacyDisplay> | undefined) | undefined;
950
+ } & ImpressionTrackOptions & TenantSpecificationOptions & ElementDiscoveryOptions & A2CButtonDiscoveryOptions, gtag_options?: {
951
+ [key: string]: any;
952
+ list_name?: string | undefined;
953
+ } | undefined) => Promise<{
954
+ add_a2c_element: (element: HTMLElement) => void;
955
+ add_product_element: (element: HTMLElement) => Promise<void | undefined>;
956
+ } | undefined>;
957
+ export const paint_red: (element: HTMLElement) => void | undefined;
958
+ /**
959
+ * A function that attempts to "serialize" an object to a text representation that helps with debugging when using sentry
960
+ * @param anything Something to try to serialize - this function is crappy and your mileage may vary
961
+ * @param depth How deep to go when recursing
962
+ * @return An object that is somehow closer to text (better serializable by sentry) or text
963
+ */
964
+ export function serialize_object(anything: Object, depth?: number): Object;
965
+ export const wait: (delay: number) => Promise<unknown>;
966
+ /**
967
+ * Fetch with retry and exponetial back off. This is the 2.0 version of the previous Windows proof fetch.
968
+ *
969
+ * 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
970
+ * @param url Url to perform fetch towards
971
+ * @param options Fetch options
972
+ * @param max_retries Max number of retries, defaults to 10
973
+ * @returns The fetch response
974
+ */
975
+ export function fetch_retry(url: RequestInfo, options?: RequestInit, max_retries?: number): Promise<false | Response>;
976
+ type PossibleEndpoint = "general" | "product" | "products" | "category";
977
+ type ExclusiveId = {
978
+ category_id: string;
979
+ product_id?: undefined;
980
+ product_ids?: undefined;
981
+ } | {
982
+ category_id?: undefined;
983
+ product_id: string;
984
+ product_ids?: undefined;
985
+ } | {
986
+ category_id?: undefined;
987
+ product_id?: undefined;
988
+ product_ids: string[];
989
+ } | {
990
+ category_id?: undefined;
991
+ product_id?: undefined;
992
+ product_ids?: undefined;
993
+ };
994
+ type FetchRecsOptions = {
995
+ type: string;
996
+ user_id?: string;
997
+ session_id?: string;
998
+ } & ExclusiveId;
999
+ /**
1000
+ * Fetches recommendations from the depict v2 recommendation api.
1001
+ * Will select the endpoint after which id property is given.
1002
+ *
1003
+ * API Docs: https://api.depict.ai/docs
1004
+ *
1005
+ * Formerly called get_displays
1006
+ */
1007
+ export function fetch_recs<T extends Display = Display>(t: Tenant | {
1008
+ market: string;
1009
+ tenant: string;
1010
+ }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<T[]>;
1011
+ export function fetch_recs_whole_response<R extends {
1012
+ displays: any[];
1013
+ }>(t: Tenant | {
1014
+ market: string;
1015
+ tenant: string;
1016
+ }, options: FetchRecsOptions, headers?: HeadersInit, get_url?: typeof default_get_fetch_url): Promise<R>;
1017
+ declare function default_get_fetch_url(type: PossibleEndpoint): string;
1018
+ export function ensure_parameter_in_url(url: any, param: any, value: any): string;
1019
+ export function querySelectorUpwards(element: Element | HTMLElement, selector: string): Element | null;
1020
+ export function html2elems(html: string): NodeListOf<ChildNode>;
1021
+ export function html2elem(html: string): Element | null;
1022
+ /** On demo domain: make all urls relative */
1023
+ export function relativify(url: string | RegExp, also_onchange?: boolean, override_dev_url?: string, stfu?: boolean, also_in_all_shadow_roots?: boolean): void;
1024
+ export function querySelectorAllElements<T extends Element>(elements: Node_Iterable, selector: string): T[];
1025
+ export function standard_price_format(price: number, places_after_comma?: number | "auto", decimal_delimiter?: string, thousands_delimiter?: string): string;
1026
+ export function intl_number_format_with_fallback(bcp47_country_code: string, number: number, numberformat_options?: Parameters<typeof Intl.NumberFormat>[1]): string;
1027
+ export function ensure_object_path(obj: object, step1: string, ...path: string[]): any;
1028
+ export function Rec_Renderer<T extends Display>(t: Tenant | null, rendering_options: RR_Options<T>): Promise<RecRendererResult<T>>;
1029
+ export function regex_templating(template: string, display?: Display | {
1030
+ [key: string]: any;
1031
+ }): string;
1032
+ export function clone_deep<T>(obj: T): T;
1033
+ export class InfoForProcessing<T extends Display> {
1034
+ constructor(t: Tenant | null, rendering_options: RR_Options<T>, displays: T[], index?: number, remove_display?: () => void, event_listeners?: [
1035
+ type: keyof HTMLElementEventMap,
1036
+ listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any,
1037
+ options?: boolean | AddEventListenerOptions
1038
+ ][]);
1039
+ }
1040
+ type RegisterEventListener = (type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any, options?: boolean | AddEventListenerOptions) => void;
1041
+ export interface InfoForProcessing<T extends Display> {
1042
+ t: Tenant;
1043
+ rendering_options: RR_Options<T>;
1044
+ displays: T[];
1045
+ index: number;
1046
+ remove_display?: () => void;
1047
+ register_event_listener: RegisterEventListener;
1048
+ event_listeners?: [
1049
+ type: keyof HTMLElementEventMap,
1050
+ listener: (this: HTMLElement, ev: HTMLElementEventMap[keyof HTMLElementEventMap]) => any,
1051
+ options?: boolean | AddEventListenerOptions
1052
+ ][];
1053
+ extras?: {
1054
+ [key: string]: any;
1055
+ };
1056
+ }
1057
+ export type RR_PreProcessor<T extends Display> = (display: T, info: InfoForProcessing<T>) => Promise<T> | T;
1058
+ 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;
1059
+ export type RR_Options<T extends Display> = {
1060
+ template: string | ((arg0: T, info: InfoForProcessing<T>) => Promise<string | Node_Array> | string | Node_Array);
1061
+ recs?: T[] | undefined | Promise<T[] | undefined>;
1062
+ type: string;
1063
+ min_items_to_report?: number;
1064
+ min_items_to_run?: number;
1065
+ max_items?: number;
1066
+ extra_api_options?: {
1067
+ [key: string]: any;
1068
+ };
1069
+ pre_processors?: RR_PreProcessor<T>[];
1070
+ post_processors?: RR_PostProcessor<T>[];
1071
+ headers?: HeadersInit;
1072
+ } & FetchRecsOptions;
1073
+ /**
1074
+ * Product properties that are used to render the product cards. Used until early 2023
1075
+ */
1076
+ export interface LegacyDisplay {
1077
+ /**
1078
+ * The URL of the product page.
1079
+ */
1080
+ page_url: any;
1081
+ /**
1082
+ * The URL of the product image.
1083
+ */
1084
+ image_url: string;
1085
+ /** The price of the product. */
1086
+ sale_price: number;
1087
+ /** The original price of the product. */
1088
+ original_price: number;
1089
+ /** The product ID of the product. */
1090
+ product_id: string;
1091
+ /** The Google Analytics product ID */
1092
+ ga_product_id?: string;
1093
+ /** The Google Analytics product IDs */
1094
+ ga_product_ids?: string[];
1095
+ /** The variation IDs */
1096
+ variant_ids?: string[];
1097
+ /** The title */
1098
+ title: string;
1099
+ /** Unique recommendation result ID used by Depict */
1100
+ recommendation_id?: string;
1101
+ /** Unique search result ID used by Depict */
1102
+ search_result_id?: string;
1103
+ /** Unique product listing result ID used by Depict */
1104
+ product_listing_result_id?: string;
1105
+ [key: string]: any;
1106
+ }
1107
+ interface ModernDisplay {
1108
+ /**
1109
+ * The index of the variant to be displayed.
1110
+ */
1111
+ variant_index: number;
1112
+ /**
1113
+ * All variant displays (eg. different colors, sizes) of the product.
1114
+ */
1115
+ variant_displays: any[];
1116
+ /** SKUs of the different variants */
1117
+ variant_skus: string[];
1118
+ /** Product of the different variants */
1119
+ variant_product_ids: 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
+ }
1129
+ interface BasicDisplay {
1130
+ product_id: string;
1131
+ /** Unique recommendation result ID used by Depict */
1132
+ recommendation_id?: string;
1133
+ /** Unique search result ID used by Depict */
1134
+ search_result_id?: string;
1135
+ /** Unique product listing result ID used by Depict */
1136
+ product_listing_result_id?: string;
1137
+ /** Recommendation type logic used by Depict */
1138
+ logic?: string;
1139
+ [key: string]: any;
1140
+ }
1141
+ export type Display = LegacyDisplay | ModernDisplay | BasicDisplay;
1142
+ export type Node_Iterable = HTMLCollection | NodeListOf<ChildNode> | Node_Array;
1143
+ export type Node_Array = (Element | Text | Comment)[];
1144
+ export type RecRendererResult<T extends Display> = Record<string, never> | {
1145
+ elements: Node_Array;
1146
+ displays: T[];
1147
+ };
1148
+ /**
1149
+ * Queues a task in the event queue without a timeout like setTimeout does, see https://www.youtube.com/watch?v=cCOL7MC4Pl0
1150
+ * @param callback callback function that gets queued as a task
1151
+ */
1152
+ export function queueMacroTask(callback: VoidFunction): void;
1153
+ interface SDKRenderingInfo {
1154
+ set_on_index_change: (fn: (index: number) => void) => void;
1155
+ merchant: string;
1156
+ market: string;
1157
+ }
1158
+ /**
1159
+ * Creates a handler for sending the "recommendations_inserted" event on new results.
1160
+ * Usage: call make_plp_recommendations_inserted_handler with options and then call the returned functions in your productCardTemplate
1161
+ */
1162
+ export function make_plp_recommendations_inserted_handler(tenant: string, market: string, type: "search" | "category"): <T extends Display>(display: T | null, info?: SDKRenderingInfo) => void;
1163
+ /**
1164
+ * @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
1165
+ */
1166
+ export function cache_args(fn: any, ...args: any[]): (...unimportant_args: any[]) => any;
1167
+ export const check_displays: (args_0: {
1168
+ recs: Display[] | {
1169
+ displays: Display[];
1170
+ } | Promise<Display[] | {
1171
+ displays: Display[];
1172
+ }>;
1173
+ min_recs?: number | undefined;
1174
+ market: string;
1175
+ type: string;
1176
+ product_id: string | string[] | Promise<string> | Promise<string[]> | ((arg0?: string) => string | string[] | Promise<string> | Promise<string[]>) | undefined;
1177
+ tenant: string;
1178
+ }) => Promise<boolean | undefined>;
1179
+ /**
1180
+ * @deprecated You should no longer need to use this. Use observer.onexists to add an event listener to an element once it exists.
1181
+ */
1182
+ export function require_event_listener(element: Node, event: string, track_id: any, func: EventListenerOrEventListenerObject): void;
1183
+ export const default_view_tracking: (RR_PostProcessor<any> | typeof depict_page_view)[];
1184
+ export const default_click_tracking: (typeof depict_click_tracking_post_processor | typeof add_new_tab_listener)[];
1185
+ export function recs_inserted_tracking<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1186
+ export function gtag_view_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1187
+ export function depict_page_view<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, _display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1188
+ export function gtag_click_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1189
+ export function depict_click_tracking_post_processor<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1190
+ export function add_to_localstorage<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1191
+ export function ga_click<T extends Display>(elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: InfoForProcessing<T>): NodeListOf<ChildNode> | Node_Array;
1192
+ export const should_colorizeLogics: boolean;
1193
+ export function colorize_elements(elements: NodeListOf<ChildNode> | Node_Array, display: Display): NodeListOf<ChildNode> | Node_Array;
1194
+ type Extended_RR_Options<T extends Display> = {
1195
+ view_tracking?: RR_PostProcessor<T>[];
1196
+ click_tracking?: RR_PostProcessor<T>[];
1197
+ } & RR_Options<T>;
1198
+ export function default_rr<T extends Display>(t: Tenant | null, rendering_options: Extended_RR_Options<T>): Promise<RecRendererResult<T>>;
1199
+ type GWVM_Options = {
1200
+ container_selector?: string;
1201
+ start_rows?: number;
1202
+ rows_per_click?: number;
1203
+ recs_per_row?: number | ((showing: number) => number);
1204
+ button?: string | HTMLElement;
1205
+ override_rec_renderer?: typeof Rec_Renderer;
1206
+ title_selector?: string;
1207
+ title?: string | HTMLElement;
1208
+ container_template: string | Node_Array;
1209
+ only_full_rows?: boolean;
1210
+ should_preload?: boolean;
1211
+ };
1212
+ interface GWVM_InfoForProcessing<T extends Display> extends InfoForProcessing<T> {
1213
+ extras: {
1214
+ [key: string]: any;
1215
+ load_more_currently_showing: number;
1216
+ load_more: (num?: number | Event) => void;
1217
+ load_more_ipo: {
1218
+ promise: Promise<number>;
1219
+ resolve: (argument?: number) => void;
1220
+ };
1221
+ };
1222
+ }
1223
+ type GWVM_RR_Post_Pro = (elements: NodeListOf<ChildNode> | Node_Array, display: Display, info: GWVM_InfoForProcessing) => Promise<NodeListOf<ChildNode> | Node_Array> | NodeListOf<ChildNode> | Node_Array;
1224
+ type GWVM_RR_Options = Extended_RR_Options & {
1225
+ post_processors?: GWVM_RR_Post_Pro[];
1226
+ };
1227
+ /**
1228
+ * @deprecated please use RecommendationGrid instead
1229
+ */
1230
+ export function GWVM_Renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: GWVM_Options): Promise<{
1231
+ elements?: ChildNode[] | undefined;
1232
+ load_more?: ((num?: number | Event) => void) | undefined;
1233
+ displays?: Display[] | undefined;
1234
+ }>;
1235
+ /**
1236
+ * Used auto generate recommendations with view more button.
1237
+ * @param t The tenant used for recommendations
1238
+ * @param options Rendering options for recommendations such as total number of recommendations and template.
1239
+ * `GWVM_RR_Options` extends the same typing used for options in `default_rr and` `recommendation-renderer`
1240
+ * @param GWVM_opts Grid options, starting row, rows per view more click, container templates
1241
+ * @param rec_selector The selector used to find the rendered recs (by recommendation renderer
1242
+ * for which the first options object was used) for the width calculation. Default: ".rec_outer".
1243
+ * @deprecated please use RecommendationGrid instead
1244
+ */
1245
+ export function Auto_GWVM(t: Tenant, options: GWVM_RR_Options, GWVM_opts: Omit<GWVM_Options, "recs_per_row">, { rec_selector }?: {
1246
+ rec_selector?: string;
1247
+ }): Promise<{
1248
+ elements?: Node_Array | undefined;
1249
+ load_more?: ((num?: number | Event) => void) | undefined;
1250
+ displays?: Display[] | undefined;
1251
+ }>;
1252
+ /**
1253
+ * @deprecated use async_iterable_ipns instead. This can skip values which yields unexpected results.
1254
+ */
1255
+ export function infinite_promise_creator(): {
1256
+ promise: Promise<unknown>;
1257
+ internal_resolve: ((value: any) => void) | undefined;
1258
+ resolve: (argument?: any) => void;
1259
+ };
1260
+ interface trimmed_GWVM_opts extends Omit<GWVM_Options, "start_rows" | "rows_per_click" | "recs_per_row"> {
1261
+ }
1262
+ /**
1263
+ * @deprecated please rewrite this, basing on RecommendationGrid and its `rows.ipns` option, next time you need infinite scroll
1264
+ */
1265
+ export function infinite_renderer(t: Tenant, options: GWVM_RR_Options, GWVM_opts: trimmed_GWVM_opts, { rec_selector }?: {
1266
+ rec_selector?: string;
1267
+ }): Promise<{
1268
+ elements?: Node_Array | undefined;
1269
+ load_more?: ((num?: number | Event | undefined) => void) | undefined;
1270
+ displays?: Display[] | undefined;
1271
+ }>;
1272
+ /**
1273
+ * @deprecated Emil's utility in integration.ts is better because it doesn't cause multiply <style> tags and doesn't require a tenant class
1274
+ */
1275
+ export function deprecated_insert_styling(t: Tenant, css: string, extra_html?: string): Promise<void>;
1276
+ export type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;
1277
+ /**
1278
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1279
+ */
1280
+ enum Market {
1281
+ dk = "dk",
1282
+ uk = "uk",
1283
+ com = "com",
1284
+ fi = "fi",
1285
+ no = "no",
1286
+ de = "de",
1287
+ nl = "nl",
1288
+ fr = "fr",
1289
+ se = "se",
1290
+ ch = "ch",
1291
+ za = "za",
1292
+ us = "us",
1293
+ ee = "ee",
1294
+ default = "default"
1295
+ }
1296
+ /**
1297
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1298
+ */
1299
+ enum Locale {
1300
+ sv_SE = "sv-SE",
1301
+ no_NO = "no-NO",
1302
+ fi_FI = "fi-FI",
1303
+ da_DK = "da-DK",
1304
+ en_UK = "en-UK",
1305
+ de_DE = "de-DE",
1306
+ nl_NL = "nl-NL",
1307
+ fr_FR = "fr-FR",
1308
+ de_CH = "de-CH"
1309
+ }
1310
+ type CurrencyInfo = {
1311
+ name: string;
1312
+ pre: string;
1313
+ post: string;
1314
+ };
1315
+ /**
1316
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1317
+ */
1318
+ type MarketDetails = {
1319
+ currency: CurrencyInfo;
1320
+ locale_bcp47: Locale;
1321
+ };
1322
+ /**
1323
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1324
+ */
1325
+ type MarketConfig = MarketDetails & {
1326
+ analytics_id: string;
1327
+ };
1328
+ /**
1329
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1330
+ */
1331
+ export const MARKET_MAP: Record<Market, MarketDetails>;
1332
+ /**
1333
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1334
+ */
1335
+ export function get_market_locale(market: Market): Locale;
1336
+ /**
1337
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1338
+ */
1339
+ export function get_market_currency(market: Market): CurrencyInfo;
1340
+ /**
1341
+ * @deprecated please use TwoLetterMarket / readonly arrays/objects instead
1342
+ */
1343
+ export type TenantMarketConfig<M extends Market> = Record<M, MarketConfig>;
1344
+ /**
1345
+ * @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.
1346
+ */
1347
+ export function placeholder(...args: Parameters<typeof placeholder_worker>): accepted_input_that_resolves_to_elements;
1348
+ type accepted_element_types = Node_Array[0] | Node_Array;
1349
+ type accepted_input_that_resolves_to_elements = accepted_element_types | Promise<accepted_element_types> | (() => accepted_element_types) | (() => Promise<accepted_element_types>);
1350
+ 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>;
1351
+ declare global {
1352
+ interface HTMLImageElementWithLoaded extends HTMLImageElement {
1353
+ loaded?: boolean;
1354
+ }
1355
+ interface HTMLSourceElementWithLoaded extends HTMLSourceElement {
1356
+ loaded?: boolean;
1357
+ }
1358
+ }
1359
+ export interface Lazyfier {
1360
+ t: Tenant;
1361
+ container: HTMLElement;
1362
+ selector: string;
1363
+ lazyfinder: lazyfinder;
1364
+ only_load_intersecting: boolean;
1365
+ ignore_data_urls?: boolean;
1366
+ }
1367
+ interface Lazyfier_Options {
1368
+ container?: HTMLElement;
1369
+ lazyfinder?: lazyfinder;
1370
+ selector?: string;
1371
+ wait_for_dominsertion?: boolean | Promise<any>;
1372
+ only_load_intersecting?: boolean;
1373
+ verbose?: boolean;
1374
+ ignore_data_urls?: boolean;
1375
+ }
1376
+ export class Lazyfier {
1377
+ #private;
1378
+ intersection_observer: IntersectionObserver;
1379
+ start_observing_for_new_children_(override_container?: HTMLElement): void;
1380
+ constructor({ container, lazyfinder, selector, wait_for_dominsertion, only_load_intersecting, ignore_data_urls, verbose, }: Lazyfier_Options);
1381
+ }
1382
+ interface lazyfinder {
1383
+ elements?: HTMLImageElementWithLoaded[];
1384
+ unload?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1385
+ load?: (element: HTMLImageElementWithLoaded) => void | Promise<void>;
1386
+ }
1387
+ export function test_array_proxy_support(): boolean;
1388
+ export interface Slider_Options {
1389
+ /**
1390
+ * Controls within what distance to hide the left slider button.
1391
+ * The distance is in pixels to the leftmost part of the slider container from the first element in the slider
1392
+ *
1393
+ * Defaults to `10`
1394
+ */
1395
+ dist_to_hide_left?: number;
1396
+ /**
1397
+ * Controls within what distance to hide the right slider button.
1398
+ * The distance is in pixels to the rightmost part of the slider container from the last element in the slider
1399
+ *
1400
+ * Defaults to `10`
1401
+ */
1402
+ dist_to_hide_right?: number;
1403
+ stepstoslide?: number;
1404
+ center_target?: boolean;
1405
+ constructor_plugins?: ((arg0: Slider_Options) => any)[];
1406
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1407
+ correct_bs_targets?: boolean;
1408
+ button_contents?: {
1409
+ right: Node_Iterable;
1410
+ left: Node_Iterable;
1411
+ };
1412
+ button_elems?: {
1413
+ right: HTMLElement;
1414
+ left: HTMLElement;
1415
+ };
1416
+ autoinvalidate_cache?: boolean;
1417
+ }
1418
+ export class Amazing_Slider {
1419
+ #private;
1420
+ container: HTMLElement;
1421
+ insert_here: HTMLElement;
1422
+ intersecting_items_object: {
1423
+ [key: string]: IntersectionObserverEntry;
1424
+ [key: number]: IntersectionObserverEntry;
1425
+ };
1426
+ stepstoslide: number;
1427
+ dist_to_hide_left: number;
1428
+ dist_to_hide_right: number;
1429
+ center_target: boolean;
1430
+ correct_bs_targets: boolean;
1431
+ snap_style?: HTMLStyleElement;
1432
+ on_elements_changed: ((records: MutationRecord[]) => any)[];
1433
+ observer: IntersectionObserver;
1434
+ observe: any;
1435
+ get_index_of_element(target: Element | HTMLElement): number | undefined;
1436
+ first_intersecting_index(min_ratio?: number): number;
1437
+ get first_intersecting(): IntersectionObserverEntry;
1438
+ get index_of_last_element(): number;
1439
+ get currently_selected(): number | undefined;
1440
+ get visible_sizes(): Map<Element, {
1441
+ total_visible: number;
1442
+ ratio_visible: number;
1443
+ margin_left: number;
1444
+ margin_right: number;
1445
+ rect: DOMRect;
1446
+ }>;
1447
+ get cards_fitting_in_viewport(): number;
1448
+ element_by_index(index: number): Element;
1449
+ invalidate_cache(): void;
1450
+ scroll_to_rel(offset: number, harsh?: boolean): void;
1451
+ scroll_to_abs(offset: number, harsh?: boolean): void;
1452
+ constructor({ dist_to_hide_left, dist_to_hide_right, stepstoslide, center_target, mutation_plugins, constructor_plugins, correct_bs_targets, button_contents, button_elems, autoinvalidate_cache, }: Slider_Options);
1453
+ }
1454
+ export interface Amazing_Lazy_Slider {
1455
+ lazyfier: Lazyfier;
1456
+ }
1457
+ export class Amazing_Lazy_Slider extends Amazing_Slider {
1458
+ constructor(options: Slider_Options, lazyfier_options?: Optional<ConstructorParameters<typeof Lazyfier>[0], "container">);
1459
+ }
1460
+ interface Pro_Slider_Options {
1461
+ container?: string | Node_Iterable;
1462
+ root_selector?: string;
1463
+ override_rec_renderer?: typeof Rec_Renderer;
1464
+ insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1465
+ lazyfier_options?: ConstructorParameters<typeof Amazing_Lazy_Slider>[1];
1466
+ }
1467
+ /**
1468
+ * @deprecated please use RecommendationSlider instead
1469
+ */
1470
+ 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>>;
1471
+ /**
1472
+ * @deprecated Please use recommendation renderer instead
1473
+ */
1474
+ export class Depict {
1475
+ #private;
1476
+ settings: any;
1477
+ data: any;
1478
+ tracker: void;
1479
+ constructor(settings: any);
1480
+ init(callback: Function, existingDisplays?: object[]): void;
1481
+ loadRecommendations(callback: any): void;
1482
+ trackGAEvent(action: any, index: any, product_id: any, ga_product_ids?: string[]): void;
1483
+ trackPageView(): void;
1484
+ trackClick(index: any): boolean | Promise<void | undefined> | undefined;
1485
+ trackAddToCart(pId: any): boolean | Promise<void | undefined> | undefined;
1486
+ createContainer(root: any, container: any, prepend?: boolean): void;
1487
+ renderTemplate({ prep, root, template, itemPreprocessor, itemPostprocessor }?: any): void;
1488
+ }
1489
+ declare global {
1490
+ interface Document {
1491
+ _depict_modify: boolean | undefined;
1492
+ }
1493
+ }
1494
+ interface TemplateToolOptions {
1495
+ max_items?: number;
1496
+ min_items?: number;
1497
+ DNT?: boolean;
1498
+ debug?: boolean;
1499
+ type?: string;
1500
+ product_id?: Function | ((url?: string) => string);
1501
+ sendGa?: boolean;
1502
+ loadHack?: boolean;
1503
+ shade?: boolean;
1504
+ gaid?: string;
1505
+ tenant?: string;
1506
+ market?: string;
1507
+ }
1508
+ /**
1509
+ * @deprecated Please use RecommendationRenderer instead
1510
+ */
1511
+ export const simplified_template_tool: (options: {
1512
+ options: TemplateToolOptions;
1513
+ recs?: object[] | undefined;
1514
+ root: Element;
1515
+ template: string;
1516
+ postProcessor?: Function | undefined;
1517
+ preProcessor?: Function | undefined;
1518
+ }) => Promise<Depict>;
1519
+ interface special_lazyfier_options extends Omit<Lazyfier_Options, "t"> {
1520
+ }
1521
+ interface Deprecated_Slider_Options {
1522
+ dlog?: Function;
1523
+ catchify?: Function;
1524
+ dist_to_hide_left?: number;
1525
+ dist_to_hide_right?: number;
1526
+ stepstoslide?: number;
1527
+ arrow_image?: string;
1528
+ center_target?: boolean;
1529
+ constructor_plugins?: ((arg0: Deprecated_Slider_Options) => any)[];
1530
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1531
+ correct_bs_targets?: boolean;
1532
+ }
1533
+ /**
1534
+ * @deprecated Please use Pro_Slider instead
1535
+ */
1536
+ declare class Deprecated_Amazing_Slider extends Amazing_Lazy_Slider {
1537
+ constructor(static_options: Deprecated_Slider_Options, override_lazyfier_options?: special_lazyfier_options);
1538
+ }
1539
+ export function insert_styling_into_slider(slider: Deprecated_Amazing_Slider): void;
1540
+ interface RR_Slider_Options {
1541
+ container?: string | Node_Iterable;
1542
+ root_selector?: string;
1543
+ Rec_Renderer?: typeof Rec_Renderer;
1544
+ insertion_verb?: "append" | "prepend" | "before" | "after" | "replaceWith";
1545
+ }
1546
+ /**
1547
+ * @deprecated please use Pro_Slider instead
1548
+ */
1549
+ 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>;
1550
+ type PreProcessor = (tenant: Tenant, display: any, i?: number, with_loadmore?: boolean, with_slider?: boolean, infinite_scroll?: boolean) => any;
1551
+ type PostProcessor = (tenant: Tenant, items: HTMLCollection, display: any, slider?: Deprecated_Amazing_Slider) => HTMLCollection;
1552
+ /**
1553
+ * @deprecated this uses template-tool-v1 which is long surpassed, please use RecommendationGrid or Pro_Slider (based on Recommendation-Renderer) instead
1554
+ */
1555
+ export function get_recs_with_template({ t, recs, title, infinite_scroll, with_slider, with_loadmore, template_tool_options, slider_options, pre_processors, post_processors, container_template, // container template
1556
+ template, // recommendation template
1557
+ chunk_size_for_load_more, insertion_promise, }: {
1558
+ t: Tenant;
1559
+ recs?: any[];
1560
+ with_loadmore?: boolean;
1561
+ title?: string | Node[] | NodeList;
1562
+ infinite_scroll?: boolean;
1563
+ template_tool_options?: TemplateToolOptions;
1564
+ with_slider?: boolean;
1565
+ slider_options?: Deprecated_Slider_Options;
1566
+ pre_processors?: PreProcessor[];
1567
+ post_processors?: PostProcessor[];
1568
+ container_template: string;
1569
+ template: string;
1570
+ chunk_size_for_load_more?: number;
1571
+ insertion_promise?: Promise<void | unknown>;
1572
+ }): Promise<ChildNode[] | void>;
1573
+ export function default_pre_processor(_t: any, d: any, i: number, with_loadmore: boolean, with_slider: boolean, infinite_scroll: boolean): any;
1574
+ export function default_post_processor(_t: any, itms: HTMLCollection, d: any, slider: Deprecated_Amazing_Slider | null): HTMLCollection;
1575
+ /**
1576
+ * @deprecated please use `fetch_retry()` instead
1577
+ *
1578
+ * 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
1579
+ * (Note: this thing really should be rewritten with exponential backoff and a better API)
1580
+ * @param dlog logging function to use
1581
+ * @param error_log an array to which errors will be pushed
1582
+ * @return a windows proof fetch function
1583
+ */
1584
+ export const wpff: (dlog: any, error_log?: any[]) => (url: RequestInfo, body: BodyInit, headers?: HeadersInit, decode_json?: boolean, fetch_options?: RequestInit, attempt?: number) => any;
1585
+ export const use_element: <E extends HTMLOrSVGElement = HTMLElement>(callback: (element: E) => void, element: E) => E;
1586
+ export function use_listener<K extends keyof GlobalEventHandlersEventMap, E extends HTMLElement = HTMLElement>(event: K, handler: (this: GlobalEventHandlers, ev: GlobalEventHandlersEventMap[K]) => any, element: E): E;
1587
+ export const classlist: (classes: (string | undefined)[]) => string;
1588
+ type Props = {
1589
+ children: Elem[] | Elem;
1590
+ onClick: (e: MouseEvent) => void;
1591
+ [key: string]: any;
1592
+ };
1593
+ type Elem = Node | string;
1594
+ type Component = (props: Props, _unknown: unknown) => HTMLElement;
1595
+ export const jsx: (tag: string | Component, { children, ...props }: Props, _unknown: unknown) => JSX.Element;
1596
+ export const jsxs: (tag: string | Component, { children, ...props }: Props, _unknown: unknown) => JSX.Element;
1597
+ export const chevronRight: HTMLElement;
1598
+ export const chevronLeft: HTMLElement;
1599
+ export const expandingContainer: ({ duration }?: {
1600
+ duration?: number;
1601
+ }) => {
1602
+ expand: () => void;
1603
+ content: HTMLDivElement;
1604
+ container: HTMLDivElement;
1605
+ };
1606
+ /**
1607
+ * 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.
1608
+ * @param iterables Array of IPNS
1609
+ * @return IPNS that resolves with an array of the values of all provided IPNS when one of them resolves
1610
+ */
1611
+ export function zip_async_iterables<T extends any[]>(iterables: IPNS<T[keyof T]>[]): IPNS<T>;
1612
+ /** Overrides that can specify a different amount of columns for certain rows
1613
+ * @param key The row (starts at 1) that you're "selecting" to override
1614
+ * @param value The amount of columns that your selected row should have
1615
+ */
1616
+ type Override = {
1617
+ overrides: Record</* Row: */ number, /* Column: */ number>;
1618
+ };
1619
+ 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];
1620
+ type ColsAtSize = readonly ColAtSize[];
1621
+ type LayoutOptions = {
1622
+ container_element: Element;
1623
+ cols_at_size: ColsAtSize;
1624
+ grid_spacing: string;
1625
+ rows: {
1626
+ start_rows?: number;
1627
+ rows_per_click?: number;
1628
+ ipns?: IPNS<number>;
1629
+ max_rows?: number;
1630
+ button?: HTMLElement;
1631
+ } | "all";
1632
+ layout: "slider" | "grid";
1633
+ disable_partial_rows?: boolean;
1634
+ override_vertical_spacing?: string;
1635
+ };
1636
+ /**
1637
+ * Grid: Calculates CSS for a grid with a certain spacing and certain number of columns at certain screen sizes, including a view more button.
1638
+ * @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
1639
+ * @param container_element container element of the elements that you want to style and hide
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 grid_spacing spacing to use if none is specified for the specific size in `cols_at_size`
1642
+ * @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".
1643
+ * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1644
+ */
1645
+ export function Layout({ rows, container_element, cols_at_size, grid_spacing, layout, disable_partial_rows, override_vertical_spacing, }: LayoutOptions): Promise<void>;
1646
+ /**
1647
+ * basically equivalent of n_col_styling css mixin - generates distances for a flex grid with margins
1648
+ * @param selector_beginning Main selector targeting container classname to use in generated css
1649
+ * @param default_grid_spacing_text Spacing to use if not specified in cols_at_size for a specific size
1650
+ * @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
1651
+ * @param override_vertical_spacing by default, the grid_spacing is used both horizontally and vertically, with this you can specify a separate spacing
1652
+ * @return String of generated CSS
1653
+ */
1654
+ 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;
1655
+ export interface RecommendationGridOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "layout"> {
1656
+ container_elements: Node_Array;
1657
+ container_selector?: string;
1658
+ override_rec_renderer?: typeof default_rr<T>;
1659
+ lazyfier_options?: Omit<Lazyfier_Options, "t">;
1660
+ eager_images?: boolean;
1661
+ }
1662
+ /**
1663
+ * 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.
1664
+ * @param t Instance of Tenant
1665
+ * @param recommendation_renderer_options Options for default_rr or override_rec_renderer
1666
+ * @param container_elements The elements from your container template.
1667
+ * @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"
1668
+ * @param override_rec_renderer Other recommendation renderer to use apart from default_rr (i.e. placeholder_rr)
1669
+ * @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.
1670
+ * @param eager_images Don't lazyload images
1671
+ * @param ...options_for_grid Options for Grid. See documentation of Grid.
1672
+ * @constructor
1673
+ */
1674
+ export function RecommendationGrid<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, { container_elements, container_selector, override_rec_renderer, lazyfier_options, eager_images, ...options_for_grid }: RecommendationGridOptions<T>): Promise<RecRendererResult<T>>;
1675
+ export interface EasySliderOptions<T extends Display> extends Omit<LayoutOptions, "container_element" | "rows" | "layout"> {
1676
+ rows?: {
1677
+ start_rows?: number;
1678
+ ipns?: IPNS<number>;
1679
+ } | "all";
1680
+ container_elements: Node_Array;
1681
+ container_selector?: string;
1682
+ override_rec_renderer?: typeof default_rr<T>;
1683
+ lazyfier_options?: Omit<Lazyfier_Options, "t">;
1684
+ eager_images?: boolean;
1685
+ dist_to_hide_left?: number;
1686
+ dist_to_hide_right?: number;
1687
+ stepstoslide?: number;
1688
+ center_target?: boolean;
1689
+ constructor_plugins?: ((arg0: Slider_Options) => any)[];
1690
+ mutation_plugins?: ((mutations: IntersectionObserverEntry[], intersecting_items: Record<number, IntersectionObserverEntry>) => any)[];
1691
+ button_contents?: {
1692
+ right: Node_Iterable;
1693
+ left: Node_Iterable;
1694
+ };
1695
+ button_elems?: {
1696
+ right: HTMLElement;
1697
+ left: HTMLElement;
1698
+ };
1699
+ override_vertical_spacing?: string;
1700
+ }
1701
+ export type RecommendationSliderSurface<T extends Display> = Record<string, never> | {
1702
+ elements: Node_Array;
1703
+ slider: Amazing_Slider | Amazing_Lazy_Slider;
1704
+ displays: T[];
1705
+ };
1706
+ /**
1707
+ *
1708
+ * The most epic RecommendationSlider todate
1709
+ * @param t Instance of tenant class
1710
+ * @param recommendation_renderer_options Options for Recommendation Renderer
1711
+ * @param RecommendationGrid_options Similar options object to RecommendationGrid except that it also contains options to Amazing_Slider
1712
+ * @return a Surface (object) that contains displays, elements and the instance of the slider class (as `slider`)
1713
+ */
1714
+ export function RecommendationSlider<T extends Display>(t: Tenant | null, recommendation_renderer_options: Extended_RR_Options<T>, { container_elements, container_selector, override_rec_renderer, lazyfier_options, eager_images, grid_spacing, cols_at_size, override_vertical_spacing, rows, ...slider_options }: EasySliderOptions<T>): Promise<RecommendationSliderSurface<T> | RecRendererResult<T> | Surface<T>>;
1715
+ export function slider_autoscroll_factory(interval?: number): {
1716
+ constructor_plugin(this: Amazing_Slider): void;
1717
+ mutation_plugin: (this: Amazing_Slider, _intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1718
+ };
1719
+ export function make_button1(): {
1720
+ left: [HTMLImageElement];
1721
+ right: [HTMLImageElement];
1722
+ };
1723
+ /**
1724
+ * Returns an object to put into `button_contents` for `Pro_Slider` containing the icon arrow images
1725
+ * @return An object with left and right being an array containing one image
1726
+ */
1727
+ export function make_button2(): {
1728
+ left: HTMLImageElement[];
1729
+ right: HTMLImageElement[];
1730
+ };
1731
+ export function slider_dots_factory({ t, navcont_insertion_fn, navdot, dontshowonedot, bitesize, }: {
1732
+ t: Tenant;
1733
+ navcont_insertion_fn?: (slider: Amazing_Slider, navcont: HTMLDivElement) => any;
1734
+ navdot: (unique_name: number, index: number) => Element;
1735
+ dontshowonedot?: boolean;
1736
+ bitesize?: number;
1737
+ }): {
1738
+ constructor_plugin: () => void;
1739
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1740
+ };
1741
+ export function navdot(unique_name: string | number): HTMLElement;
1742
+ export function slider_draggable_factory(t: Tenant): {
1743
+ constructor_plugin: (slider_options: any) => void;
1744
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1745
+ post_pro_plugin: {
1746
+ instant: (items: HTMLCollection) => void;
1747
+ };
1748
+ };
1749
+ export function slider_fading_factory({ fade_in_duration_, fade_out_duration_, visible_opacity_, faded_opacity_, easing_, threshold_, }?: {
1750
+ fade_in_duration_?: number;
1751
+ fade_out_duration_?: number;
1752
+ visible_opacity_?: number;
1753
+ faded_opacity_?: number;
1754
+ easing_?: string;
1755
+ threshold_?: number;
1756
+ }): {
1757
+ readonly mutation_plugin_: (this: Amazing_Slider, entries: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1758
+ };
1759
+ export function slider_fractional_factory(_t?: any, fraction?: number, max_steps?: number, dont_enable_correct_bs_targets?: boolean, min_steps?: number): {
1760
+ constructor_plugin: (slider_options: Slider_Options) => void;
1761
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1762
+ };
1763
+ /**
1764
+ * * Plugin for rendering a scrollbar below the slider that follow the slider position.
1765
+ * * Scroll container class: `depict_slider_scroll`
1766
+ * * Scroll bar class: `depict_slider_scroll_bar`
1767
+ * @param options Options for the scrollbar. Add position styling and additional classes.
1768
+ */
1769
+ export function slider_show_scroll(options: {
1770
+ add_position_styling: boolean;
1771
+ scroll_bar_classes?: string[];
1772
+ scroll_container_classes?: string[];
1773
+ }): {
1774
+ constructor_plugin: (_slider_options: Slider_Options) => void;
1775
+ mutation_plugin: (_intersections: IntersectionObserverEntry[], _intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1776
+ };
1777
+ export function slider_snap_css(_t?: any, { snapEvery, align }?: {
1778
+ snapEvery?: number;
1779
+ align?: "center" | "start" | "end";
1780
+ }): {
1781
+ constructor_plugin: (_slider_options: Slider_Options) => void;
1782
+ mutation_plugin: (_intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1783
+ };
1784
+ export function can_use_snapping_and_still_scroll(): Promise<boolean>;
1785
+ export function slider_snapping_factory(options?: {
1786
+ stepsize?: number;
1787
+ threshold?: number;
1788
+ }): {
1789
+ constructor_plugin: (slider_options: any) => void | undefined;
1790
+ mutation_plugin: (intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void | undefined;
1791
+ };
1792
+ export function slider_wraparound_factory({ clones_per_side }?: {
1793
+ clones_per_side?: number | undefined;
1794
+ }): {
1795
+ constructor_plugin: (this: Amazing_Slider) => void;
1796
+ mutation_plugin: (this: Amazing_Slider, intersections: IntersectionObserverEntry[], intersecting_mutations: Record<number, IntersectionObserverEntry>) => void;
1797
+ post_processor: <T extends Display>(elements: Node_Array | NodeListOf<ChildNode>, _display: Display, info: InfoForProcessing<T>) => Promise<NodeListOf<ChildNode> | Node_Array>;
1798
+ };
1799
+ export type ReactiveTemplateValueContents = string | number | Node_Array[number] | undefined | (string | number | Node_Array[number])[];
1800
+ export function reactive_template(initial_value?: ReactiveTemplateValueContents): readonly [Node_Array, () => ReactiveTemplateValueContents, (arg0: ReactiveTemplateValueContents) => void];
1801
+ /**
1802
+ * A wrapper around window.matchMedia, basically cross browser compatibly adds an event listener to a media query that triggers when it changes
1803
+ * @param query The media query (without `@media`)
1804
+ * @param catchified_handler The function to execute
1805
+ * @param initial_call If the handler should be called instantly with the current state of the media query
1806
+ * @return An object containing `remove`, a function which removes the event listener again
1807
+ */
1808
+ export function javascript_media_query(// inspired by code in houdinisportswear modify script
1809
+ query: string, handler: (e: MediaQueryListEvent | MediaQueryList) => void, initial_call?: boolean): {
1810
+ remove(): void;
1811
+ };
1812
+ type RenderingFunction<T extends Display> = (...args: any[]) => Promise<{
1813
+ surface_: Surface<T> | void;
1814
+ cache_until_?: Promise<any>;
1815
+ }>;
1816
+ /**
1817
+ * 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.
1818
+ * @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.
1819
+ * @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_.
1820
+ * @return a `Surface` object which, utilising a `reactive_template` always represents the currently chosen surface
1821
+ */
1822
+ export function surface_mixer<T extends Display>({ surface_rendering_functions_, current_surface_, }: {
1823
+ surface_rendering_functions_: RenderingFunction<T>[];
1824
+ current_surface_: IPNS<number>;
1825
+ }): Promise<Surface<T>>;
1826
+ /**
1827
+ * To be used in conjunction with surface_mixer. Makes it possible to switch Surface depending on screen size
1828
+ * @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.
1829
+ * @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).
1830
+ * @return An IPNS resolving with the number of the surface that should currently be shown
1831
+ */
1832
+ export function sizes_to_surface(surface_per_size: [surface_index: number, min: string | null, max?: string][], cleanup_promise?: Promise<any>): IPNS<number>;
1833
+ /**
1834
+ * Returns a promise that resolve the next time the href is changed
1835
+ */
1836
+ export function promise_until_next_navigation(): Promise<string | undefined>;
1837
+ export function orderpage_transaction_id_extractor(t: Tenant, selector: string, filter?: (text: string) => string | undefined): void;
1838
+ /**
1839
+ * Looks at all entries in window.dataLayer, past present and future, and attempts to find transaction IDs in them.
1840
+ * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1841
+ * @param tenant The tenant we are tracking.
1842
+ * @param id_extractor Maps an entry to a transaction ID string, or something falsy if no transaction ID is found.
1843
+ * For example: entry => entry?.event?.purchase?.orderId
1844
+ */
1845
+ export function datalayer_transaction_id_extractor(tenant: Tenant, id_extractor: (layer_entry: any) => any): void;
1846
+ /**
1847
+ * Looks at all URL changes, including the current URL, and attempts to find transaction IDs in them.
1848
+ * Any transaction IDs found will automatically be sent to Depict's tracking for the given tenant.
1849
+ * @param tenant The tenant we are tracking.
1850
+ * @param id_extractor Maps an URL to a transaction ID string, or something falsy if no transaction ID is found.
1851
+ * For example: url => url.searchParams.get("orderId")
1852
+ */
1853
+ export function url_transaction_id_extractor(tenant: Tenant, id_extractor: (url: URL) => unknown): void;
1854
+ export function send_transaction_id_to_depict(t: Tenant, input_id: string, dsid?: string, filter?: (text: string) => string | undefined): void;
1855
+ /**
1856
+ * Intercepts google analytics events for transactions (e.g when payment is made) and also sends it to depict.
1857
+ * */
1858
+ export function ga_to_transaction_api(t: Tenant, filter?: (text: string) => string | undefined): void;
1859
+ export function send_product_unavailable_to_depict(t: Tenant, unavailability_type: EUnavailabilityType): Promise<void>;
1860
+ export interface ListenableSetEvent<T> extends CustomEvent {
1861
+ detail: T;
1862
+ }
1863
+ /**
1864
+ * Set but you can listen for values being added or removed
1865
+ * i.e. my_set.addEventListener("add", ({detail}) => console.log(detail, "was added to", my_set));
1866
+ */
1867
+ export class ListenableSet<T> extends Set<T> {
1868
+ #private;
1869
+ addEventListener(event: "add" | "delete", callback: (ev: ListenableSetEvent<T>) => unknown, options?: Parameters<(typeof EventTarget.prototype)["addEventListener"]>[2]): void;
1870
+ removeEventListener(event: "add" | "delete", callback: (ev: Event) => unknown): void;
1871
+ add(property: T): this;
1872
+ delete(property: T): any;
1873
+ }
1874
+ /**
1875
+ * 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.
1876
+ * @param element Element to start out at
1877
+ * @param selector Selector to search for
1878
+ * @param start_right=true In what direction to start: true = right, false = left
1879
+ * @return The found element or undefined
1880
+ */
1881
+ export function chaotic_closest(element: Element, selector: string, start_right?: boolean): Element | undefined;
1882
+ type CompareMethod<T> = (i1: T, i2: T) => boolean;
1883
+ export const deduplicate: <T>(arr1: T[], arr2: T[], compareFunc: CompareMethod<T>) => T[];
1884
+ export const dedup_products: <T extends LegacyDisplay>(arr1: T[], arr2: T[] | undefined) => T[];
1885
+ /**
1886
+ * Attempt to navigate using nextjs's spa router.
1887
+ * Falls back to default browser navigation.
1888
+ * Docs: https://nextjs.org/docs/api-reference/next/router
1889
+ */
1890
+ export function navigate_with_next_router(e: MouseEvent, url: string): false | undefined;
1891
+ /**
1892
+ * proxies window.fetch:
1893
+ * 1. Instead of window.fetch fetch_apply is called, target being the original fetch function
1894
+ * 2. fetch_proxy_handler is called and may read the request and return a (fake) response
1895
+ * 3. if fetch_proxy_handler fails the original target is called with the same this and arguments
1896
+ * We are meticulously preserving this, target and its arguments in case that someone replaces fetch with a function that does something else
1897
+ * 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
1898
+ * Remember to return response, else it will make another request
1899
+ * @param fetch_proxy_handler Called instead of the original fetch function everytime someone does fetch. Has to return a response.
1900
+ * @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
1901
+ * @return Nothing
1902
+ */
1903
+ 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>;
1904
+ /**
1905
+ * 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.
1906
+ * Useful when wanting to change the result of a `fetch request`
1907
+ * Please see repo for usage examples
1908
+ * @param response_string String to base Response object on
1909
+ * @param url URL to claim that the Response is from
1910
+ * @param headers Response headers
1911
+ * @param override_options More options to pass to the `Response` constructor
1912
+ */
1913
+ export class FakeResponse extends Response {
1914
+ constructor(response_string: string, url: string, headers?: HeadersInit, override_options?: ResponseInit);
1915
+ }
1916
+ export type ShopifyItem = {
1917
+ id: number;
1918
+ handle: string;
1919
+ quantity: number;
1920
+ url: string;
1921
+ };
1922
+ export type ShopifyError = {
1923
+ status: number;
1924
+ message: string;
1925
+ description: string;
1926
+ };
1927
+ /**
1928
+ * Represents a Shopify cart "event", i.e. Whenever a Shopify API request is sucessfull.
1929
+ * - `type` represent the type of event
1930
+ * - `response` resolves to a shopify response
1931
+ */
1932
+ export type ShopifyEvent = {
1933
+ type: "get_items";
1934
+ response: Promise<ShopifyItem[] | ShopifyError>;
1935
+ body?: object;
1936
+ } | {
1937
+ type: "add_items";
1938
+ response: Promise<ShopifyItem[] | ShopifyError>;
1939
+ body?: object;
1940
+ } | {
1941
+ type: "update_items";
1942
+ response: Promise<ShopifyItem[] | ShopifyError>;
1943
+ body?: object;
1944
+ } | {
1945
+ type: "change_items";
1946
+ response: Promise<ShopifyItem[] | ShopifyError>;
1947
+ body?: object;
1948
+ } | {
1949
+ type: "clear_items";
1950
+ response: Promise<[] | ShopifyError>;
1951
+ body?: object;
1952
+ };
1953
+ /**
1954
+ * Whenever any request to the shopify cart endpoint (this includes requests made by merchant code) is made {@link on_response} is called.
1955
+ *
1956
+ * ### Caveats
1957
+ * - This currently doesn't intercept XHR requests, only `fetch`. Interpecpting XHR should be implemented at some point!
1958
+ *
1959
+ * - Under the hood, this function works by proxying `window.fetch`. This isn't guaranted to work, and could even break merchant code.
1960
+ * Call this function early on in the execution for the best possibillity of success.
1961
+ *
1962
+ * - If the merchant performs a `window.fetch` to Shopify before `intercept` then that response wont be intercepted.
1963
+ * If you know that the merchant will make a request to Shopify early on then it might make sense to do something like:
1964
+ * ```
1965
+ * const handle = setTimeout(catchify(() => get_items_in_cart()), 2000)
1966
+ * intercept(evt => {
1967
+ * canel_timeout(handle)
1968
+ * ...
1969
+ * })
1970
+ * ```
1971
+ * In order to get the cart contents at some point even if you miss the merchants innitialt Shopify request.
1972
+ *
1973
+ * - `intercept` intercepts all requests to Shopify, including requests made by you.
1974
+ */
1975
+ export function intercept(on_request: (event: ShopifyEvent) => any): void;
1976
+ export type AddToCartOptions = {
1977
+ quantity?: number;
1978
+ };
1979
+ /**
1980
+ * Add an item to the Shopify cart.
1981
+ *
1982
+ * ### Caveats
1983
+ * Keep in mind that adding to the shopify cart wont neccesarily update the merchants UI,
1984
+ * it only means that when the merchant fetches the cart again then they'll get the item added by you.
1985
+ * Usually the merchant has it's own global add-to-cart function that can be used. While doing that can
1986
+ * take more developer time it means that you usually get the merchant UI to update correctly.
1987
+ *
1988
+ * @param shopify_id
1989
+ * @param options.quantity How many of an item to add, defaults to `1`.
1990
+ * @throws If the response JSON is in an unexpected format.
1991
+ */
1992
+ export function add_item(shopify_id: string, options?: AddToCartOptions): Promise<ShopifyItem[] | ShopifyError>;
1993
+ /**
1994
+ * Fetch the items in the shoppify cart.
1995
+ *
1996
+ * This is probably not the right function for mose use-cases.
1997
+ * Want to get notified when merchant code adds new items to the cart through Shopify?
1998
+ * Use {@link intercept} to intercept all calls to Shopify (even ones made by merchant code).
1999
+ *
2000
+ * @returns All items currently in the cart.
2001
+ * @throws If the response JSON is in an unexpected format.
2002
+ */
2003
+ export function get_items_in_cart(): Promise<ShopifyItem[] | ShopifyError>;
2004
+ declare global {
2005
+ interface Window {
2006
+ ShopifyAnalytics: {
2007
+ meta?: {
2008
+ product?: ShopifyMetaProduct;
2009
+ };
2010
+ };
2011
+ }
2012
+ }
2013
+ interface ShopifyMetaProduct {
2014
+ id?: string;
2015
+ vendor?: string;
2016
+ variants?: {
2017
+ id?: string;
2018
+ sku?: string;
2019
+ }[];
2020
+ }
2021
+ /** Shopify sites often has an interesting meta object defined on window.ShopifyAnalytics.meta
2022
+ * The SKU that backend requires might only be found in the meta object.
2023
+ * This function gives you that object in a safe way that won't break Shopify.
2024
+ */
2025
+ export const get_shopify_analytics_meta_product: () => Promise<ShopifyMetaProduct | undefined>;
2026
+ /**
2027
+ * 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`
2028
+ * @param t Instance of `Tenant class`
2029
+ * @param experiment_id Optimize experiment id of running A/B test
2030
+ * @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.
2031
+ * @param functions_to_variants [description]
2032
+ * @return The return value of the called function
2033
+ */
2034
+ export function get_optimize_variant({ t, experiment_id, functions_to_variants, }: {
2035
+ t: Tenant;
2036
+ experiment_id: string;
2037
+ functions_to_variants: Function[];
2038
+ }): Promise<any>;
2039
+ /**
2040
+ * Ensures that the attribute value of an element is what an AsyncIterable resolves with
2041
+ * @param el Element to set attribute on
2042
+ * @param attribute_name Name of the attribute to set
2043
+ * @param async_iterable AsyncIterable to loop over
2044
+ * @param quit_after_navigation=true Whether to stop awaiting the AsyncIterable if the page navigates
2045
+ * @return [description]
2046
+ */
2047
+ export function iterable_to_attribute(el: Element, attribute_name: string, async_iterable: AsyncIterable<string>, quit_after_navigation?: boolean): Element;
2048
+ /**
2049
+ * Merges an IPNS with `reactive_template` - if the IPNS updates the reactive template's state is updated to what the IPNS returns
2050
+ * @param async_iterable The async iterable to use
2051
+ * @param quit_after_navigation Whether to stop listening for the IPNS when navigating away
2052
+ * @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.
2053
+ */
2054
+ export function iterable_to_elems(async_iterable: AsyncIterable<ReactiveTemplateValueContents>, quit_after_navigation?: boolean): Node_Array;
2055
+ /**
2056
+ * 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
2057
+ * @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";
2058
+ * @return A wrapped function that now executes in a context
2059
+ */
2060
+ export const prevent_infinite_loop: <A extends any[], B>(cb: (...args: A) => void | B) => (...args: A) => void | B;
2061
+ /**
2062
+ * Inserts one or multiple surfaces into the DOM.
2063
+ * 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
2064
+ * @param surfaces Array with surfaces to insert
2065
+ * @param verb Verb on how to insert
2066
+ * @param target Selector for `observer.onexists` to find element to insert VERBto, alternatively an element
2067
+ * @param remove_after_navigation Whether to remove the elements from the DOM again if a navigation away occurs, defaults to true
2068
+ * @param try_forever Whether to try to insert the same surface even after the page has navigated away, defaults to false
2069
+ * @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
2070
+ * @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
2071
+ */
2072
+ export function insert_surfaces<T extends Display>({ surfaces: input_surfaces, verb, target, remove_after_navigation, try_forever, preserve_elements, }: {
2073
+ verb: InsertionVerb;
2074
+ target: string | HTMLElement;
2075
+ remove_after_navigation?: boolean;
2076
+ try_forever?: boolean;
2077
+ surfaces: (Promise<Surface<T> | void> | Surface<T> | void)[];
2078
+ preserve_elements?: boolean;
2079
+ }): Promise<{
2080
+ surface: Surface<T>;
2081
+ succeeded: boolean;
2082
+ }>[];
2083
+ export const revertable_remove: (target: string | Element | Node_Array, should_stay_inserted: Promise<boolean>) => Promise<void | undefined>;
2084
+ type MakePlaceholderRROption<T extends Display> = {
2085
+ override_rec_renderer?: (t: Tenant | null, rendering_options: Extended_RR_Options<T>) => Promise<RecRendererResult<T>>;
2086
+ image_width?: number;
2087
+ image_height?: number;
2088
+ color?: string;
2089
+ num_items?: number;
2090
+ on_no_rendering_result?: (result?: RecRendererResult<T>) => any;
2091
+ post_rendering?: (surface?: RecRendererResult<T>) => Promise<void> | void;
2092
+ };
2093
+ /**
2094
+ * We want to deprecate this
2095
+ */
2096
+ export type PlaceholderRenderingDisplay = {
2097
+ sale_price: number;
2098
+ page_url: "#" | string;
2099
+ image_url: string;
2100
+ original_price: number;
2101
+ product_id: "placeholder" | string;
2102
+ recommendation_id: "placeholder" | string;
2103
+ title: string;
2104
+ brand: string;
2105
+ };
2106
+ export const random_text_placeholder: () => string;
2107
+ export const placeholder_svg: (image_width: number, image_height: number, color?: string) => string;
2108
+ /**
2109
+ * 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.
2110
+ * @param [override_rec_renderer=default_rr] The recommendation renderer to use
2111
+ * @param [image_width=2000] Width of placeholder image svg (use to set aspect ratio)
2112
+ * @param [image_height=2000] Height of placeholder image svg (use to set aspect ratio)
2113
+ * @param [num_items=10] Number of placeholders to render
2114
+ * @param [color="#d9d9d9"] Color of placeholder image svg
2115
+ * @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
2116
+ * @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
2117
+ * @return It returns the same as a normal recommenation renderer would, meaning an object that might contain `displays` and `elements`
2118
+ */
2119
+ export function make_placeholder_rr<T extends Display>({ override_rec_renderer, image_width, image_height, num_items, color, on_no_rendering_result, post_rendering, }?: MakePlaceholderRROption<T>): Promise<(t: Tenant | null, rendering_options: Extended_RR_Options<T | PlaceholderRenderingDisplay>) => Promise<Record<string, never> | {
2120
+ elements: Node_Array;
2121
+ displays: T[];
2122
+ }>>;
2123
+ /**
2124
+ * 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
2125
+ * @return a WeakSet to add nodes to which you remove and want to ignore removal errors for
2126
+ */
2127
+ export function removeChild_error_swallowing_factory(): WeakSet<Node>;
2128
+ /**
2129
+ * 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)
2130
+ * @return void
2131
+ */
2132
+ export function replace_promise_with_native_if_exists_and_enforce(): void;
2133
+ /**
2134
+ * Creates a blank iframe inside <head> and returns window.Promise out of it
2135
+ * @return a pristine, unpolyfilled window.Promise
2136
+ */
2137
+ export function get_iframe_promise(): PromiseConstructor;
2138
+ /**
2139
+ * Proxies XMLHttpRequest.prototype.open to an open function which also calls the provided `fetch_handler` with useful information as parameter
2140
+ * @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
2141
+ * @return void
2142
+ */
2143
+ export function xhr_replace(fetch_handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, arg_array: Parameters<typeof XMLHttpRequest.prototype.open>) => void): void;
2144
+ /**
2145
+ * 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
2146
+ * @param handler The function called on load of every XHR request.
2147
+ * @return void
2148
+ */
2149
+ export function xhr_load(handler: (request: XMLHttpRequest, method: "GET" | "POST", url: string | URL, event: ProgressEvent<XMLHttpRequestEventTarget>) => any): void;
2150
+ 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>;
2151
+ /**
2152
+ * Intercepts someone reading `response`, `responseText` and `responseXML` on an XMLHttpRequest
2153
+ * @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`.
2154
+ */
2155
+ 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>;
2156
+ export function default_rp_fixes(orig_url?: string | undefined): Promise<void>;
2157
+ export function rp_relativify_history(orig_url_with_trailing_slash: string): void;
2158
+ export function rp_relativify_fetch(orig_url_with_trailing_slash: string): void;
2159
+ export function rp_relativify_xhr(orig_url_with_trailing_slash: string): void;
2160
+ /**
2161
+ * 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.
2162
+ */
2163
+ export function sort_obj<T>(maybe_obj: T): any;
2164
+ /**
2165
+ * Tries to figure out the tenant's market (`TwoLetterMarket` for new integrations) through various means.
2166
+ *
2167
+ * 1. Checks if there is a market in one of the url segments (www.tentant.se/foo/se/bar)
2168
+ * 2. Checks if the market is specified in the tenant's domain name (www.tenant-se.com)
2169
+ * 3. Checks the toplevel domain (www.tenant.se/foo/bar)
2170
+ *
2171
+ * @param allowed_markets An array the possible markets for the tenant.
2172
+ * Dont forget to specify the allowed market as const (`["se", "en"] as const`) to get the best typing
2173
+ * @param url Specify this to overide the url to check, defaults to the current url
2174
+ * @param tenant The tenant's name
2175
+ * @returns If a market specified in `allowed_markets`was found that is returned, `undefined` otherwise
2176
+ */
2177
+ export function standard_get_market<T extends readonly string[]>(allowed_markets: T, url?: string, tenant?: string): T[number] | undefined;
2178
+ /**
2179
+ * Listens to localstorage changes with `setItem` and direct assignment.
2180
+ * @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.
2181
+ */
2182
+ export function listenToLocalStorage(listener: (key: string, value: string) => void): void;
2183
+ /**
2184
+ * Timeout a promise after `ms` milliseconds.
2185
+ * If the promise is timed out this function will return `undefined` and not throw.
2186
+ */
2187
+ export function timeout_promise<T>(promise: Promise<T>, ms: number): Promise<Awaited<T> | undefined>;
2188
+ /**
2189
+ * Uses the default Voyado ID that is used in Voyado email recommendations.
2190
+ */
2191
+ export const use_voyado_id: () => void | undefined;
2192
+ type ButtonProps = Omit<Partial<JSX.IntrinsicElements["button"]>, "type"> & {
2193
+ class?: string;
2194
+ };
2195
+ export function DefaultViewMoreButton({ children, ...attributes }: ButtonProps): HTMLButtonElement;
2196
+ export function GeneralSideSlidein({ title_, children, CloseIcon, }: {
2197
+ title_: IPNS<string>;
2198
+ children: HTMLElement | HTMLElement[];
2199
+ CloseIcon: () => HTMLElement | SVGElement;
2200
+ }): Promise<{
2201
+ close_: VoidFunction;
2202
+ on_close_: (fn: VoidFunction) => number;
2203
+ }>;
2204
+ export function GeneralSizeSelector({ title_, items_, out_of_stock_text_, CloseIcon, }: {
2205
+ title_: IPNS<string>;
2206
+ out_of_stock_text_: IPNS<string>;
2207
+ items_: {
2208
+ id_: string;
2209
+ size_name_: string;
2210
+ is_available_: boolean;
2211
+ }[];
2212
+ CloseIcon: () => HTMLElement | SVGElement;
2213
+ }): Promise<string | void>;
2214
+ type PlaceholderProps = Omit<Partial<JSX.IntrinsicElements["div"]>, "style"> & {
2215
+ /** Any extra classes togheter with the default `depict-placeholder` class */
2216
+ class?: string;
2217
+ /** Convinence prop for setting element width */
2218
+ width?: string;
2219
+ /** Convinence prop for setting element height */
2220
+ height?: string;
2221
+ /** Will override the usage of width & height */
2222
+ style?: string;
2223
+ };
2224
+ type PlaceholderImageProps = Omit<PlaceholderProps, "width" | "height" | "style"> & {
2225
+ aspect_ratio: number;
2226
+ };
2227
+ /**
2228
+ * A Placeholder with shimmering animation.
2229
+ * For text you can use `height="1em"`.
2230
+ * For specific number of characters use `ch`, ex: `width="7ch"`
2231
+ */
2232
+ export const Placeholder: ({ width, height, class: extra_classes, style, ...attributes }: PlaceholderProps) => HTMLElement;
2233
+ /**
2234
+ * A wrapper of Placeholder with full width and maintained aspect ratio.
2235
+ * @see {@link Placeholder}
2236
+ */
2237
+ export const ContainedPlaceholderImage: ({ aspect_ratio, ...attributes }: PlaceholderImageProps) => HTMLElement;
2238
+ export const RecommendationContainer: (title?: string | HTMLElement, surface_classes?: string[]) => HTMLElement;
2239
+ export const RightChevron: () => HTMLElement;
2240
+ export const LeftChevron: () => HTMLElement;
2241
+ export type ColorObj = {
2242
+ /** the value passed as a css color */
2243
+ value: string;
2244
+ /** if specified, it's used as a title on hover */
2245
+ label?: string;
2246
+ /** Allow for arbitrary data to be passed */
2247
+ [key: string]: any;
2248
+ };
2249
+ interface ColorPickerProps {
2250
+ /** An array of colors that can be selected */
2251
+ colors: ColorObj[];
2252
+ onSelect: (color: ColorObj) => unknown;
2253
+ /**
2254
+ * Called everytime a color is hovered
2255
+ */
2256
+ onHoverUpdate?: (color: ColorObj, hovering: boolean) => unknown;
2257
+ /**
2258
+ * The color value to be initially selected. Can be omitted for no color to be selected.
2259
+ * If multiple colors use the same hex value, the label can also be specified (using a ColorObj)
2260
+ */
2261
+ initialColor?: string | ColorObj;
2262
+ /**
2263
+ * Enabled hovering preview. When true `onSelect` will be called with a new color when it's hovered,
2264
+ * then reverts back to the last clicked color when hovering is stopped
2265
+ * */
2266
+ selectOnHover?: boolean;
2267
+ /**
2268
+ * If set to true only `onSelect` will be called when an item is clicked
2269
+ */
2270
+ dontSetActiveOnClick?: boolean;
2271
+ /**
2272
+ * If only circles should be returned and not the container element
2273
+ */
2274
+ onlyCircles?: boolean;
2275
+ }
2276
+ /**
2277
+ * A color selector, that calls onSelect when a color is clicked and optionally on hover as well.
2278
+ */
2279
+ export function createColorPicker({ colors, initialColor, onSelect, selectOnHover, onHoverUpdate, dontSetActiveOnClick, onlyCircles, }: ColorPickerProps): {
2280
+ setActiveIndex: (index: number) => void | undefined;
2281
+ ColorPicker(): HTMLElement;
2282
+ };
2283
+ /**
2284
+ * For example how to use, check /src/glitter/main.tsx
2285
+ * Warning: Don't use margins for the element you want to expand, since the animation will look janky
2286
+ * EDIT: above no longer applies if you only have one element that you want to expand
2287
+ */
2288
+ export const useExpandingContainer: ({ duration, delay }?: {
2289
+ duration?: number;
2290
+ delay?: number;
2291
+ }) => {
2292
+ ExpandingContainer: ({ children }: {
2293
+ children?: Elem | Elem[] | undefined;
2294
+ }) => HTMLElement;
2295
+ expand: (expanding_delay?: any, time_to_expand?: any) => Promise<Animation | undefined>;
2296
+ collapse: (collapsing_delay?: any, time_to_collapse?: any) => Promise<Animation | undefined>;
2297
+ };
2298
+ export const resize_base_url: string;
2299
+ export const is_safari: boolean;
2300
+ /**
2301
+ * 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
2302
+ * @param what_to_watch Element to watch resizing of
2303
+ * @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
2304
+ * @param resolution_factor a factor to multiply the target-to-display resolution with
2305
+ * @return A function that will set the `sizes` atribute of the provided element to the size of `what_to_watch`, continuously
2306
+ */
2307
+ export function make_sizes_setter(what_to_watch: HTMLElement, sizes_communicator?: IPNS<number>, resolution_factor?: number): (el_to_resize: HTMLSourceElement | HTMLImageElement) => Promise<void>;
2308
+ /**
2309
+ * This function returns a function that can be used as JSX component.
2310
+ * It builds upon `make_sizes_setter` and uses it to set the `sizes` attribute of <source> and a fallback <img> tag that it creates.
2311
+ * @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.
2312
+ * @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.
2313
+ * @param formats An array of formats supported by the backends "ResizeImage" to allow the browser to use
2314
+ * @param resolutions An array of resolutions to generate a srcset for
2315
+ * @param sizes_communicator IPNS of which the resolution sets the `sizes` attribute on the images
2316
+ * @param sizes_setter_ a sizes setter returned by make_sizes_setter, you can provide one if you created it before creating the images
2317
+ * @param resolution_factor a factor to multiply the target-to-display resolution with
2318
+ * @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+)
2319
+ *
2320
+ * @example Per surface:
2321
+ * `const SourcesetComponent = make_sourceset_component(first_canvas, true, ["webp", "png", "tiff"]);`
2322
+ * and then instead of your <img> tags: `<SourcesetComponent data-src={d.image_url} class="image" />`
2323
+ */
2324
+ export function make_sourceset_component({ what_to_watch, set_dataset, formats, resolutions, sizes_communicator, resolution_factor, market_, sizes_setter_, }?: {
2325
+ what_to_watch?: HTMLElement;
2326
+ set_dataset?: boolean;
2327
+ formats?: string[];
2328
+ resolutions?: number[];
2329
+ sizes_communicator?: IPNS<number>;
2330
+ resolution_factor?: number;
2331
+ market_?: string;
2332
+ sizes_setter_?: ReturnType<typeof make_sizes_setter>;
2333
+ }): (image_options: Partial<JSX.IntrinsicElements["img"]> & {
2334
+ class?: string;
2335
+ }) => HTMLElement;
2336
+ /**
2337
+ * Adds query parameters from the `params` parameter to the `base` url.
2338
+ * Guaranteed to be correctly escaped and not doubled and perfectly formatted
2339
+ * @param base base url, can be relative
2340
+ * @param params an object like `{'param1': 'value'}` that will lead to `?param1=value` on the url
2341
+ * @return an absolute URL with the added query parameters
2342
+ */
2343
+ export function make_url_with_query_params(base: string, params: {
2344
+ [key: string]: any;
2345
+ }): string;
2346
+ export interface ImageOptions extends Partial<HTMLImageElement> {
2347
+ aspect_ratio: number;
2348
+ class?: string;
2349
+ rendering_options?: RR_Options<any>;
2350
+ srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2351
+ alt: string;
2352
+ remove_on_error?: boolean;
2353
+ /**
2354
+ * If true, inserts grey placeholder svg's before the image lazyloader and the sourceset component add the real source
2355
+ */
2356
+ init_with_placeholder?: boolean;
2357
+ }
2358
+ /**
2359
+ * Contained image gives an image (a container with) intrinsic size of the given aspect ratio, filling out available space.
2360
+ * It means that images with different aspect ratios will all take the same amount of space
2361
+ * and the sides where it doesn't fit the aspect ratio will be filled with transparent.
2362
+ * It makes sure the images doesn't get squished like setting `width` and `height` would do.
2363
+ * @param aspect_ratio The aspect ratio of the image, i.e. 4/3 = 1,3̅
2364
+ * @param alt Alt text of the image
2365
+ * @param remove_on_error Whether to remove the image if loading fails
2366
+ * @param rendering_options The rendering options. Please always provide this, it's only optional for compatibility reasons.
2367
+ * You should provide the `rendering_options` to the second argument, InfoForProcessing, provided to a template or preprocessor.
2368
+ * When provided to a postprocessor of a recommendation-renderer it will be the third argument
2369
+ * If you provide this, ContainedImage will automatically use `make_sourceset_component`
2370
+ * and the image resizing proxy to get you responsive images in a modern format (webp).
2371
+ * @param srcset_opts The options passed to `make_sourceset_component`, only used if `rendering_options` is set.
2372
+ * @param Everything else: attributes on the <img> tag
2373
+ * @returns It depends on options and build target. But it's always one HTMLElement.
2374
+ */
2375
+ export const ContainedImage: ({ init_with_placeholder, ...options }: ImageOptions) => HTMLElement;
2376
+ type HoverImageOptions = ImageOptions & {
2377
+ mobile_touch_hover?: boolean;
2378
+ extra_container_class?: string;
2379
+ main_extra_classes?: string;
2380
+ second_src?: string;
2381
+ second_srcset?: string;
2382
+ second_srcset_opts?: Parameters<typeof make_sourceset_component>[0];
2383
+ fade_length_seconds?: number;
2384
+ /** The minimum amount of time for a touch to be considered a link click */
2385
+ navigation_minimum_ms?: number;
2386
+ };
2387
+ export const ContainedHoverImage: ({ second_src, second_srcset, second_srcset_opts, fade_length_seconds, mobile_touch_hover, navigation_minimum_ms, ...options }: HoverImageOptions) => HTMLElement;
2388
+ /**
2389
+ * Shallowly converts all keys in an object from snake_case to camelCase.
2390
+ * Does not support symbol keys.
2391
+ *
2392
+ * @param obj the object. It will be cloned and not modified in-place.
2393
+ */
2394
+ export function camelCasifyObject<T extends {
2395
+ [key: string]: any;
2396
+ }, X extends T = T>(obj: T): X;
2397
+ /**
2398
+ * Shallowly converts all keys in an object from camelCase to snake_case.
2399
+ * Does not support symbol keys.
2400
+ * @param obj the object. It will be cloned and not modified in-place.
2401
+ */
2402
+ export function snakeCasifyObject<T extends {
2403
+ [key: string]: any;
2404
+ }, X extends T = T>(obj: T): X;
2405
+ /**
2406
+ * Converts RGB to HSL
2407
+ * Source of function: https://www.30secondsofcode.org/js/s/rgb-to-hsl
2408
+ */
2409
+ export function rgb_to_hsl(r: number, g: number, b: number): readonly [number, number, number];
2410
+ /**
2411
+ * Converts HSL to RGB
2412
+ * Source of function: https://www.30secondsofcode.org/js/s/hsl-to-rgb
2413
+ */
2414
+ export function hsl_to_rgb(h: number, s: number, l: number): readonly [number, number, number];
2415
+ /**
2416
+ * Converts HSV (or HSB, it's the same) to RGB.
2417
+ * Source of function: https://www.30secondsofcode.org/js/s/hsb-to-rgb/
2418
+ */
2419
+ export function hsb_to_rgb(h: number, s: number, b: number): readonly [number, number, number];
2420
+ /**
2421
+ * Calculates the relative luminance of a RGB color
2422
+ * Source: https://gist.github.com/jfsiii/5641126
2423
+ */
2424
+ export function relative_luminance_from_rgb(R8bit: number, G8bit: number, B8bit: number): number;