@vtex/ads-stories 0.4.1 → 0.5.0
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.
- package/CHANGELOG.md +60 -0
- package/README.md +250 -26
- package/dist/cdn/vtex-ads-stories.js +986 -72
- package/dist/cdn/vtex-ads-stories.js.map +1 -1
- package/dist/cjs/index.cjs +2911 -403
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +193 -8
- package/dist/cjs/react.cjs.map +1 -1
- package/dist/cjs/react.d.cts +45 -5
- package/dist/esm/index.d.ts +193 -8
- package/dist/esm/index.js +2528 -121
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/react.d.ts +45 -5
- package/package.json +18 -4
- package/src/cdn.ts +7 -3
- package/src/components/card/card.ts +64 -12
- package/src/components/carousel/carousel.ts +670 -0
- package/src/components/carousel/index.ts +15 -0
- package/src/components/events/events-controller.ts +212 -0
- package/src/components/events/index.ts +6 -0
- package/src/components/icons/assets/caret-left-bold.svg +1 -0
- package/src/components/icons/assets/caret-right-bold.svg +1 -0
- package/src/components/icons/assets/caret-up-bold.svg +1 -0
- package/src/components/icons/index.ts +6 -0
- package/src/components/media/index.ts +2 -1
- package/src/components/media/media.ts +21 -17
- package/src/components/media/video-controller.ts +47 -0
- package/src/components/player/index.ts +6 -2
- package/src/components/player/player.ts +797 -48
- package/src/components/product/cta.ts +56 -0
- package/src/components/product/index.ts +20 -0
- package/src/components/product/price.ts +86 -0
- package/src/components/product/product.styles.ts +369 -0
- package/src/components/product/product.ts +235 -0
- package/src/index.ts +9 -1
- package/src/locales/en.ts +29 -0
- package/src/locales/es.ts +30 -0
- package/src/locales/index.ts +36 -0
- package/src/locales/pt.ts +29 -0
- package/src/locales/types.ts +24 -0
- package/src/react.ts +49 -7
- package/src/story/index.ts +5 -1
- package/src/story/story.ts +505 -47
- package/src/tag-name.ts +1 -0
- package/src/types.ts +8 -12
- package/src/utils/fetch-story.ts +113 -0
- package/src/utils/http-url.ts +12 -0
- package/src/utils/hydrate-products.ts +88 -0
- package/src/utils/send-event.ts +71 -0
- package/src/utils/with-timeout.ts +43 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { getRawAds, type Channel } from "@vtex/ads-core";
|
|
2
|
+
import { TAG_NAME } from "../tag-name";
|
|
3
|
+
import type { StoryAd } from "../types";
|
|
4
|
+
import { withTimeout } from "./with-timeout";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Default time limit for the Story request, in milliseconds. A card that
|
|
8
|
+
* shows up later than this would appear well after the page loaded.
|
|
9
|
+
*/
|
|
10
|
+
export const DEFAULT_TIMEOUT_MS = 2000;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* How many Stories the element asks for.
|
|
14
|
+
*/
|
|
15
|
+
export const DEFAULT_QUANTITY = 8;
|
|
16
|
+
|
|
17
|
+
/** What the element sends to the ad API. */
|
|
18
|
+
export interface StoryRequest {
|
|
19
|
+
/** Required. */
|
|
20
|
+
publisherId?: string;
|
|
21
|
+
/** Required. */
|
|
22
|
+
sessionId?: string;
|
|
23
|
+
/** Required. */
|
|
24
|
+
placement?: string;
|
|
25
|
+
userId?: string;
|
|
26
|
+
accountName?: string;
|
|
27
|
+
channel?: Channel;
|
|
28
|
+
/**
|
|
29
|
+
* How many Stories to ask for: the carousel positions. Missing, below 1 or
|
|
30
|
+
* not a number: DEFAULT_QUANTITY. A fraction is rounded down.
|
|
31
|
+
*/
|
|
32
|
+
quantity?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface FetchStoryOptions {
|
|
36
|
+
/** Cancels the request. */
|
|
37
|
+
signal?: AbortSignal;
|
|
38
|
+
/**
|
|
39
|
+
* Time limit in milliseconds. Missing, zero, negative or not a number:
|
|
40
|
+
* DEFAULT_TIMEOUT_MS.
|
|
41
|
+
*/
|
|
42
|
+
timeout?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const toQuantity = (quantity?: number) =>
|
|
46
|
+
quantity !== undefined && Number.isFinite(quantity) && quantity >= 1
|
|
47
|
+
? Math.floor(quantity)
|
|
48
|
+
: DEFAULT_QUANTITY;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Requests up to `quantity` Stories for the placement from the ad API, in
|
|
52
|
+
* the order the ad API returns them.
|
|
53
|
+
*
|
|
54
|
+
* Resolves to an empty list, without throwing, when a required value is
|
|
55
|
+
* missing, during server-side rendering, when the request fails, is cancelled
|
|
56
|
+
* or takes longer than the time limit, or when the placement has no Story.
|
|
57
|
+
*/
|
|
58
|
+
export async function fetchStories(
|
|
59
|
+
{
|
|
60
|
+
publisherId,
|
|
61
|
+
sessionId,
|
|
62
|
+
placement,
|
|
63
|
+
userId,
|
|
64
|
+
accountName,
|
|
65
|
+
channel,
|
|
66
|
+
quantity,
|
|
67
|
+
}: StoryRequest,
|
|
68
|
+
{ signal, timeout }: FetchStoryOptions = {},
|
|
69
|
+
): Promise<StoryAd[]> {
|
|
70
|
+
// No request during server-side rendering, where nothing renders. Not
|
|
71
|
+
// Lit's isServer: it is also true in Node with a DOM, as in the tests.
|
|
72
|
+
const onServer = globalThis.window === undefined;
|
|
73
|
+
if (onServer || !publisherId || !sessionId || !placement) return [];
|
|
74
|
+
|
|
75
|
+
const limit = withTimeout(timeout, DEFAULT_TIMEOUT_MS, signal);
|
|
76
|
+
const count = toQuantity(quantity);
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
const { stories } = await getRawAds(
|
|
80
|
+
{
|
|
81
|
+
identity: {
|
|
82
|
+
accountName: accountName ?? "",
|
|
83
|
+
publisherId,
|
|
84
|
+
sessionId,
|
|
85
|
+
userId,
|
|
86
|
+
channel,
|
|
87
|
+
},
|
|
88
|
+
search: {},
|
|
89
|
+
placements: {
|
|
90
|
+
[placement]: { quantity: count, types: ["story"] },
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
{ signal: limit.signal },
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
// The ad API may send more than asked for: only the first ones fit.
|
|
97
|
+
return (stories[placement] ?? []).slice(0, count);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
// A cancelled or timed out request needs no log. Anything else (network
|
|
100
|
+
// failure, HTTP or validation error) is logged, so a failing request can
|
|
101
|
+
// be told apart from a placement with no Story.
|
|
102
|
+
if (!limit.signal.aborted) {
|
|
103
|
+
console.error(`[${TAG_NAME}] Story request failed`, {
|
|
104
|
+
placement,
|
|
105
|
+
publisherId,
|
|
106
|
+
error,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return [];
|
|
110
|
+
} finally {
|
|
111
|
+
limit.clear();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Only absolute http(s) URLs reach the DOM or the network. Relative and
|
|
2
|
+
// protocol-relative ones ("/a.jpg", "//host/a.jpg") don't parse without a
|
|
3
|
+
// base, so they're out.
|
|
4
|
+
export function httpUrl(value: string | undefined) {
|
|
5
|
+
if (!value) return null;
|
|
6
|
+
try {
|
|
7
|
+
const { protocol } = new URL(value);
|
|
8
|
+
return protocol === "https:" || protocol === "http:" ? value : null;
|
|
9
|
+
} catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hydrateAds,
|
|
3
|
+
intelligentSearchAvailability,
|
|
4
|
+
intelligentSearchFetcher,
|
|
5
|
+
intelligentSearchMatcher,
|
|
6
|
+
intelligentSearchPrice,
|
|
7
|
+
type Identity,
|
|
8
|
+
type Offer,
|
|
9
|
+
type Product,
|
|
10
|
+
type ProductFetcher,
|
|
11
|
+
type ProductPrice,
|
|
12
|
+
} from "@vtex/ads-core";
|
|
13
|
+
import { TAG_NAME } from "../tag-name";
|
|
14
|
+
import type { StoryAd } from "../types";
|
|
15
|
+
import { withTimeout } from "./with-timeout";
|
|
16
|
+
|
|
17
|
+
const DEFAULT_HYDRATION_TIMEOUT_MS = 5000;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Where the element gets its products' details: a fetcher and a matcher, as
|
|
21
|
+
* in `@vtex/ads-core`, and a reader for the price of a fetched product.
|
|
22
|
+
*/
|
|
23
|
+
export interface StoryHydration<TProduct extends object = object> {
|
|
24
|
+
fetcher: ProductFetcher<TProduct>;
|
|
25
|
+
matcher(product: TProduct, offer: Offer): boolean;
|
|
26
|
+
price(product: TProduct, offer: Offer): ProductPrice | undefined;
|
|
27
|
+
/** Whether the product can be bought. Without it, it isn't checked. */
|
|
28
|
+
available?(product: TProduct, offer: Offer): boolean | undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const intelligentSearchHydration: StoryHydration<Product> = {
|
|
32
|
+
fetcher: intelligentSearchFetcher,
|
|
33
|
+
matcher: intelligentSearchMatcher,
|
|
34
|
+
price: intelligentSearchPrice,
|
|
35
|
+
available: intelligentSearchAvailability,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export interface StoryProductDetails {
|
|
39
|
+
price?: ProductPrice;
|
|
40
|
+
/** Missing when the strategy doesn't say. */
|
|
41
|
+
available?: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface HydrateProductsOptions {
|
|
45
|
+
signal?: AbortSignal;
|
|
46
|
+
timeout?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function hydrateStoryProducts(
|
|
50
|
+
placement: string,
|
|
51
|
+
stories: StoryAd[],
|
|
52
|
+
hydration: StoryHydration,
|
|
53
|
+
identity: Identity,
|
|
54
|
+
{ signal, timeout }: HydrateProductsOptions = {},
|
|
55
|
+
): Promise<Map<string, StoryProductDetails>> {
|
|
56
|
+
const products = new Map<string, StoryProductDetails>();
|
|
57
|
+
const limit = withTimeout(timeout, DEFAULT_HYDRATION_TIMEOUT_MS, signal);
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const hydrated = await hydrateAds(
|
|
61
|
+
{ stories: { [placement]: stories } },
|
|
62
|
+
hydration.fetcher,
|
|
63
|
+
(product, offer) => hydration.matcher(product, offer),
|
|
64
|
+
identity,
|
|
65
|
+
{ signal: limit.signal },
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
for (const { story, product, offer } of hydrated.stories[placement] ?? []) {
|
|
69
|
+
if (!product || !offer) continue;
|
|
70
|
+
const price = hydration.price(product, offer);
|
|
71
|
+
const available = hydration.available?.(product, offer);
|
|
72
|
+
products.set(story.ad_id, {
|
|
73
|
+
...(price && { price }),
|
|
74
|
+
...(available !== undefined && { available }),
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
} catch (error) {
|
|
78
|
+
// As for the Story request: a cancelled or timed out request needs no
|
|
79
|
+
// log, any other failure does.
|
|
80
|
+
if (!limit.signal.aborted) {
|
|
81
|
+
console.error(`[${TAG_NAME}] Product request failed`, error);
|
|
82
|
+
}
|
|
83
|
+
} finally {
|
|
84
|
+
limit.clear();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return products;
|
|
88
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { httpUrl } from "./http-url";
|
|
2
|
+
import { TAG_NAME } from "../tag-name";
|
|
3
|
+
|
|
4
|
+
// A CORS-safelisted type: the browser sends the event without a preflight
|
|
5
|
+
// request, and sendBeacon accepts it everywhere. The event host reads the
|
|
6
|
+
// body as JSON whatever its type.
|
|
7
|
+
const CONTENT_TYPE = "text/plain;charset=utf-8";
|
|
8
|
+
|
|
9
|
+
/** Who the event is for: the same session sent in the ad request. */
|
|
10
|
+
export interface EventIdentity {
|
|
11
|
+
sessionId: string;
|
|
12
|
+
userId?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Sends an impression, view or click to the event URL from the ad response,
|
|
17
|
+
* as VTEX Ads asks of browsers: a POST with a JSON body holding `session_id`
|
|
18
|
+
* and, when known, `user_id`, through `navigator.sendBeacon`, so the event
|
|
19
|
+
* survives the page being left. Without the Beacon API, or when the browser
|
|
20
|
+
* refuses to queue the beacon, it falls back to a `fetch` with `keepalive`.
|
|
21
|
+
* The body goes as `text/plain` (see CONTENT_TYPE).
|
|
22
|
+
*
|
|
23
|
+
* The fallback isn't awaited: it returns true once the `fetch` starts, and a
|
|
24
|
+
* failed request is logged, not sent again. The server deduplicates by
|
|
25
|
+
* session anyway, and a retry could outlive the page.
|
|
26
|
+
*
|
|
27
|
+
* Returns false, sending nothing, when the URL isn't an absolute http(s)
|
|
28
|
+
* URL, during server-side rendering or when both ways fail at once.
|
|
29
|
+
*/
|
|
30
|
+
export function sendEvent(
|
|
31
|
+
url: string | undefined,
|
|
32
|
+
{ sessionId, userId }: EventIdentity,
|
|
33
|
+
): boolean {
|
|
34
|
+
const target = httpUrl(url);
|
|
35
|
+
if (!target || globalThis.window === undefined) return false;
|
|
36
|
+
|
|
37
|
+
const body = JSON.stringify(
|
|
38
|
+
userId
|
|
39
|
+
? { session_id: sessionId, user_id: userId }
|
|
40
|
+
: { session_id: sessionId },
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
const queued = globalThis.navigator?.sendBeacon?.(
|
|
45
|
+
target,
|
|
46
|
+
new Blob([body], { type: CONTENT_TYPE }),
|
|
47
|
+
);
|
|
48
|
+
if (queued) return true;
|
|
49
|
+
} catch {
|
|
50
|
+
// A browser that throws instead of refusing (for example, for a URL it
|
|
51
|
+
// won't beacon to): the fetch below sends it instead.
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (typeof globalThis.fetch !== "function") return false;
|
|
55
|
+
|
|
56
|
+
globalThis
|
|
57
|
+
.fetch(target, {
|
|
58
|
+
method: "POST",
|
|
59
|
+
headers: { "Content-Type": CONTENT_TYPE },
|
|
60
|
+
body,
|
|
61
|
+
keepalive: true,
|
|
62
|
+
credentials: "omit",
|
|
63
|
+
})
|
|
64
|
+
.catch((error: unknown) => {
|
|
65
|
+
console.error(`[${TAG_NAME}] Event request failed`, {
|
|
66
|
+
url: target,
|
|
67
|
+
error,
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A signal that aborts when the caller's signal aborts or after `timeout`
|
|
3
|
+
* milliseconds, whichever comes first. A `timeout` missing, zero, negative or
|
|
4
|
+
* not a number uses `fallback`. Built by hand instead of with
|
|
5
|
+
* `AbortSignal.any` and `AbortSignal.timeout`, which older browsers lack.
|
|
6
|
+
*
|
|
7
|
+
* Call `clear()` once the work is done, so the timer and the listener on the
|
|
8
|
+
* caller's signal don't outlive it.
|
|
9
|
+
*/
|
|
10
|
+
export const withTimeout = (
|
|
11
|
+
timeout: number | undefined,
|
|
12
|
+
fallback: number,
|
|
13
|
+
signal?: AbortSignal,
|
|
14
|
+
): { signal: AbortSignal; clear: () => void } => {
|
|
15
|
+
const ms =
|
|
16
|
+
timeout !== undefined && Number.isFinite(timeout) && timeout > 0
|
|
17
|
+
? timeout
|
|
18
|
+
: fallback;
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
|
|
21
|
+
const timer = setTimeout(
|
|
22
|
+
() =>
|
|
23
|
+
controller.abort(
|
|
24
|
+
new DOMException(`Timed out after ${ms} ms`, "TimeoutError"),
|
|
25
|
+
),
|
|
26
|
+
ms,
|
|
27
|
+
);
|
|
28
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
29
|
+
|
|
30
|
+
if (signal?.aborted) {
|
|
31
|
+
onAbort();
|
|
32
|
+
} else {
|
|
33
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
signal: controller.signal,
|
|
38
|
+
clear: () => {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
signal?.removeEventListener("abort", onAbort);
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
};
|