@surfside/ads-react 0.1.0 → 0.1.1

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 (72) hide show
  1. package/README.md +127 -127
  2. package/lib/cjs/components/SurfsideBanner.js +71 -0
  3. package/lib/cjs/components/SurfsideBanner.js.map +1 -0
  4. package/lib/cjs/components/SurfsideCarousel.js +103 -0
  5. package/lib/cjs/components/SurfsideCarousel.js.map +1 -0
  6. package/lib/cjs/components/SurfsideDynamicZone.js +131 -0
  7. package/lib/cjs/components/SurfsideDynamicZone.js.map +1 -0
  8. package/lib/cjs/components/SurfsideProduct.js +3 -0
  9. package/lib/cjs/components/SurfsideProduct.js.map +1 -0
  10. package/lib/cjs/components/SurfsideVideo.js +82 -0
  11. package/lib/cjs/components/SurfsideVideo.js.map +1 -0
  12. package/lib/cjs/components/index.js +23 -0
  13. package/lib/cjs/components/index.js.map +1 -0
  14. package/lib/cjs/hooks/index.js +22 -0
  15. package/lib/cjs/hooks/index.js.map +1 -0
  16. package/lib/cjs/hooks/useSurfsideBanner.js +215 -0
  17. package/lib/cjs/hooks/useSurfsideBanner.js.map +1 -0
  18. package/lib/cjs/hooks/useSurfsideDynamicZone.js +202 -0
  19. package/lib/cjs/hooks/useSurfsideDynamicZone.js.map +1 -0
  20. package/lib/cjs/hooks/useSurfsideProducts.js +366 -0
  21. package/lib/cjs/hooks/useSurfsideProducts.js.map +1 -0
  22. package/lib/cjs/hooks/useSurfsideVideo.js +295 -0
  23. package/lib/cjs/hooks/useSurfsideVideo.js.map +1 -0
  24. package/lib/cjs/index.js +20 -16325
  25. package/lib/cjs/index.js.map +1 -0
  26. package/lib/cjs/provider/SurfsideContextProvider.js +158 -0
  27. package/lib/cjs/provider/SurfsideContextProvider.js.map +1 -0
  28. package/lib/cjs/provider/index.js +19 -0
  29. package/lib/cjs/provider/index.js.map +1 -0
  30. package/lib/cjs/utils/Analytics.js +181 -0
  31. package/lib/cjs/utils/Analytics.js.map +1 -0
  32. package/lib/cjs/utils/index.js +18 -0
  33. package/lib/cjs/utils/index.js.map +1 -0
  34. package/lib/esm/components/SurfsideBanner.js +67 -0
  35. package/lib/esm/components/SurfsideBanner.js.map +1 -0
  36. package/lib/esm/components/SurfsideCarousel.js +99 -0
  37. package/lib/esm/components/SurfsideCarousel.js.map +1 -0
  38. package/lib/esm/components/SurfsideDynamicZone.js +126 -0
  39. package/lib/esm/components/SurfsideDynamicZone.js.map +1 -0
  40. package/lib/esm/components/SurfsideProduct.js +2 -0
  41. package/lib/esm/components/SurfsideProduct.js.map +1 -0
  42. package/lib/esm/components/SurfsideVideo.js +78 -0
  43. package/lib/esm/components/SurfsideVideo.js.map +1 -0
  44. package/lib/esm/components/index.js +7 -0
  45. package/lib/esm/components/index.js.map +1 -0
  46. package/lib/esm/hooks/index.js +6 -0
  47. package/lib/esm/hooks/index.js.map +1 -0
  48. package/lib/esm/hooks/useSurfsideBanner.js +209 -0
  49. package/lib/esm/hooks/useSurfsideBanner.js.map +1 -0
  50. package/lib/esm/hooks/useSurfsideDynamicZone.js +197 -0
  51. package/lib/esm/hooks/useSurfsideDynamicZone.js.map +1 -0
  52. package/lib/esm/hooks/useSurfsideProducts.js +359 -0
  53. package/lib/esm/hooks/useSurfsideProducts.js.map +1 -0
  54. package/lib/esm/hooks/useSurfsideVideo.js +289 -0
  55. package/lib/esm/hooks/useSurfsideVideo.js.map +1 -0
  56. package/lib/esm/index.js +4 -16299
  57. package/lib/esm/index.js.map +1 -0
  58. package/lib/esm/provider/SurfsideContextProvider.js +151 -0
  59. package/lib/esm/provider/SurfsideContextProvider.js.map +1 -0
  60. package/lib/esm/provider/index.js +3 -0
  61. package/lib/esm/provider/index.js.map +1 -0
  62. package/lib/esm/utils/Analytics.js +171 -0
  63. package/lib/esm/utils/Analytics.js.map +1 -0
  64. package/lib/esm/utils/index.js +2 -0
  65. package/lib/esm/utils/index.js.map +1 -0
  66. package/lib/types/components/SurfsideBanner.d.ts +1 -2
  67. package/lib/types/components/SurfsideVideo.d.ts +0 -1
  68. package/lib/types/hooks/useSurfsideBanner.d.ts +1 -1
  69. package/package.json +41 -34
  70. package/lib/types/hooks/useSurfDynamicZone.d.ts +0 -7
  71. package/lib/types/types.d.ts +0 -33
  72. package/lib/types/utils/analytics.d.ts +0 -58
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSurfsideDynamicZone.js","sourceRoot":"src/","sources":["hooks/useSurfsideDynamicZone.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAMH,SAAS,EACT,GAAG,EACH,EAAE,GACL,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAUH,2BAA2B,EAC3B,yBAAyB,EAC5B,MAAM,UAAU,CAAC;AAoHjB,CAAC;AAWD,CAAC;AAUD,CAAC;AAoBD,CAAC;AAYD,CAAC;AAcD,CAAC;AA6BF;;;;;;;GAOG,CAAA,CAAC;AAqBJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,MAAM,UAAU,sBAAsB,CAAC,EACnC,MAAM,EACN,QAAQ,EACR,OAAO,GAAG,IAAI,EACd,eAAe,GAAG,IAAI,EACE;IACxB,MAAM,EACF,cAAc,EACd,uBAAuB,EACvB,oBAAoB,EACpB,OAAO,EAAE,UAAU,EACnB,QAAQ,EAAE,WAAW,EACrB,KAAK,EAAE,QAAQ,EAClB,GAAG,kBAAkB,EAAE,CAAC;IAEzB,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,EAAmC,CAAC;IAEpE,cAAc;IACd,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,EAAoC,CAAC;IACvF,MAAM,qBAAqB,GAAG,2BAA2B,CAAC,aAAa,CAAC,CAAC;I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;IACN,CAAC;AACL,CAAC;AAAA,CAAC;AAEF,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAClB;IAA5B,YAA4B,MAAc;QACtC,KAAK,CACD,yFAAyF;YACzF,kBAAkB,CACrB,CAAC;QAJsB,WAAM,GAAN,MAAM,CAAQ;IAK1C,CAAC;CACJ"}
@@ -0,0 +1,359 @@
1
+ 'use client';
2
+ import { useState, useEffect, useCallback } from 'react';
3
+ import { useSurfsideContext } from '../provider';
4
+ import { ConsumeNAsync, Ctx, Err, GetValueOrThrow, TryDo } from '@surfside/ads-core-client';
5
+ ;
6
+ ;
7
+ ;
8
+ /**
9
+ * Fetches a page of either product data or product IDs. Returns a set of callbacks for fetching more products and
10
+ * callbacks for tracking impression and click events.
11
+ *
12
+ * This hook is useful for implementing carousels or pages of sponsored product listings within search results.
13
+ *
14
+ * This will either return a set of products and their data fields (i.e, name, description, price, etc.) or a set of
15
+ * product IDs, depending on the value of `props.withProductInfo`.
16
+ *
17
+ * @param props The page information and recommender strategy. See {@link UseSurfsideProductsPropsWithProductIDs} and
18
+ * {@link UseSurfsideProductsPropsWithProductData}
19
+
20
+ *
21
+ * @example
22
+ * To retrieve full product data, including all available fields:
23
+ *
24
+ * ```tsx
25
+ * // returns product data
26
+ * const { products } = useSurfsideProducts({
27
+ * zoneId: '123',
28
+ * pageSize: 6,
29
+ * strategy: 'sponsored',
30
+ * withProductInfo: true // or pass nothing - withProductInfo is true by default
31
+ * })
32
+ *
33
+ * console.log(products.map(product => product.data.name))
34
+ * ```
35
+ *
36
+ * *(See {@link IProductInfoData} and {@link IProductInformation} for a list of fields and the full return type)*
37
+ *
38
+ * @example
39
+ * To retrieve *only* product IDs:
40
+ *
41
+ * ```tsx
42
+ * // returns product IDs
43
+ * const { products } = useSurfsideProducts({
44
+ * zoneId: '123',
45
+ * pageSize: 6,
46
+ * strategy: 'sponsored',
47
+ * withProductInfo: false
48
+ * })
49
+ *
50
+ * console.log(products.map(product => product.id))
51
+ * ```
52
+ *
53
+ * *(See {@link IProductIDData} for the full return type)*
54
+ *
55
+ * @example
56
+ * Both return types will return an object with a `type` field:
57
+ *
58
+ * ```ts
59
+ * {
60
+ * type: 'sponsored' | 'recommended'
61
+ * // either product ID or product data goes here...
62
+ * }
63
+ * ```
64
+ *
65
+ * This is so you can mark Sponsored products as sponsored. In the United States,
66
+ * [
67
+ * the FTC requires all advertisements be conspicuously labeled as such
68
+ * ](https://www.ftc.gov/business-guidance/resources/ftcs-endorsement-guides-what-people-are-asking#\
69
+ * :~:text=The%20FTC%20Act%20applies%20to,have%20you%20mention%20that%20product).
70
+ *
71
+ * When rendering a product card, you might use this field thusly:
72
+ *
73
+ * ```tsx
74
+ * products.map(product => <div>
75
+ * {product.data.name}
76
+ * {product.type === 'sponsored'
77
+ * ? <span>Sponsored</span>
78
+ * : <></>
79
+ * }
80
+ * </div>);
81
+ * ```
82
+ *
83
+ * @example
84
+ * A very simple carousel implementation might look like:
85
+ *
86
+ * ```tsx
87
+ * const myCarousel = ({ zoneId }: MyCarouselProps) => {
88
+ * const { products, hasMore, fetchNextPage, analytics } = useSurfsideProducts({
89
+ * zoneId,
90
+ * strategy: 'sponsored',
91
+ * pageSize: 6
92
+ * });
93
+ *
94
+ * return <div>
95
+ * <div class="products">
96
+ * {products.map(product => <div>
97
+ * { \/* Product Image is a URL string *\/ }
98
+ * <img src={product.data.image} />
99
+ * { \/* Product name *\/ }
100
+ * <h2>{product.data.name}</h2>
101
+ * { \/* Details is a short description of the product *\/ }
102
+ * <p>{product.data.details}</p>
103
+ * { \/* product.type is either 'sponsored' or 'recommended' *\/ }
104
+ * {product.type === 'sponsored'
105
+ * ? <span>Sponsored</span>
106
+ * : <></>
107
+ * }
108
+ * </div>)}
109
+ * </div>
110
+ * <div class="controls">
111
+ * { \/* hasMore indicates that there are more products available to be fetched *\/ }
112
+ * {hasMore
113
+ * ? <button class="nextButton" onClick={fetchNextPage}>➡️</button>
114
+ * : <></>
115
+ * }
116
+ * </div>
117
+ * </div>
118
+ * }
119
+ * ```
120
+ */
121
+ export function useSurfsideProducts(props) {
122
+ const internalState = useSurfsideProductsResponse({
123
+ carousel: undefined,
124
+ ...props
125
+ });
126
+ useEffect(() => {
127
+ internalState.refetch?.();
128
+ }, [internalState.refetch]);
129
+ return internalState;
130
+ }
131
+ ;
132
+ export function useSurfsideProductsResponse(props) {
133
+ const { defaultNative, startRequest, buildHybridCarousel, buildSponsoredCarousel, buildRecommendedCarousel, isReady: apiIsReady, hasError: apiHasError, error: apiError, logger } = useSurfsideContext();
134
+ const log = Ctx(logger)?.with('useSurfsideProductsResponse');
135
+ log?.info('Using surfside products response!');
136
+ const [internalCarousel, setInternalCarousel] = useState(props?.carousel);
137
+ const [loading, setLoading] = useState(true);
138
+ const [products, setProducts] = useState([]);
139
+ const [dataSource, setDataSource] = useState();
140
+ const [productsError, setProductsError] = useState();
141
+ const [hasMore, setHasMore] = useState(false);
142
+ log?.debug('Props', props, products);
143
+ /* If the API has an error, set an error */
144
+ useEffect(() => {
145
+ if (apiError !== undefined) {
146
+ log?.error(apiError);
147
+ setErrorState(apiError);
148
+ }
149
+ }, [apiHasError, apiError]);
150
+ /* If the API is still loading, set the loading state */
151
+ useEffect(() => {
152
+ if (!apiIsReady) {
153
+ log?.debug('Loading...');
154
+ setLoadingState();
155
+ }
156
+ else {
157
+ log?.debug('Ready!');
158
+ setReady();
159
+ }
160
+ }, [apiIsReady]);
161
+ /* If the datasource was just set, fetch a page of products */
162
+ useEffect(() => {
163
+ log?.debug('Checking data source...');
164
+ if (dataSource !== undefined) {
165
+ log?.debug('Fetching!');
166
+ fetchProducts();
167
+ }
168
+ }, [dataSource]);
169
+ /* If the internalCarousel was just set, set the datasource from that internal carousel
170
+ * This can either be passed in to the arguments (i.e, dynamic zones) or it can be set by calling
171
+ * refetch, which also works as an initial fetch request */
172
+ useEffect(() => {
173
+ log?.debug('Checking internal carousel response...');
174
+ if (internalCarousel?.ok === true) {
175
+ log?.debug('Found internal carousel!');
176
+ setDataSource(internalCarousel.value.getProduct());
177
+ }
178
+ else if (internalCarousel?.ok === false) {
179
+ log?.debug('Did not find internal carousel!');
180
+ setErrorState(internalCarousel);
181
+ }
182
+ }, [internalCarousel]);
183
+ useEffect(() => {
184
+ log?.info('Setting loading state...');
185
+ if (props === undefined) {
186
+ setLoadingState();
187
+ }
188
+ else {
189
+ setInternalCarousel(props.carousel);
190
+ }
191
+ }, [props]);
192
+ const setSuccessState = (newproducts, hasMore) => {
193
+ log?.debug('Success!', newproducts, products);
194
+ setLoading(false);
195
+ setProductsError(undefined);
196
+ setHasMore(hasMore);
197
+ setProducts(newproducts);
198
+ };
199
+ const setErrorState = (error) => {
200
+ setLoading(false);
201
+ setProductsError(error);
202
+ setHasMore(false);
203
+ };
204
+ const setLoadingState = () => {
205
+ setLoading(true);
206
+ setProductsError(undefined);
207
+ };
208
+ const setReady = () => {
209
+ setLoading(false);
210
+ setProductsError(undefined);
211
+ };
212
+ /* This is used for re-requesting the carousel, and is also called by useSurfsideProducts to initialize the data */
213
+ const refetch = useCallback(() => {
214
+ log?.debug('Refetching');
215
+ if (props === undefined || !apiIsReady || props.enabled === false) {
216
+ if (apiHasError) {
217
+ setErrorState(apiError);
218
+ }
219
+ return;
220
+ }
221
+ setLoadingState();
222
+ const request = startRequest(props.zoneId)
223
+ .withNative(defaultNative().withMetaProduct().build())
224
+ .build();
225
+ const recommenderType = props.recommenderType ?? 'top-products';
226
+ const carousel = TryDo(() => {
227
+ switch (props.strategy) {
228
+ case 'hybrid':
229
+ return GetValueOrThrow(buildHybridCarousel({
230
+ type: recommenderType
231
+ }, request));
232
+ case 'sponsored':
233
+ return GetValueOrThrow(buildSponsoredCarousel(request));
234
+ case 'recommended':
235
+ return GetValueOrThrow(buildRecommendedCarousel({ type: recommenderType }));
236
+ default:
237
+ throw new InvalidStrategyError(props.strategy);
238
+ }
239
+ });
240
+ setInternalCarousel(carousel);
241
+ }, [
242
+ apiIsReady,
243
+ apiError,
244
+ props?.zoneId,
245
+ startRequest,
246
+ defaultNative,
247
+ buildHybridCarousel,
248
+ buildSponsoredCarousel,
249
+ buildRecommendedCarousel,
250
+ props?.recommenderType,
251
+ props?.strategy,
252
+ props
253
+ ]);
254
+ const fetchProducts = useCallback(() => {
255
+ log?.debug('Fetching', products);
256
+ if (props === undefined) {
257
+ return;
258
+ }
259
+ if (dataSource !== undefined) {
260
+ const actualPageSize = props.maxProducts !== undefined
261
+ ? Math.min(props.maxProducts - products.length, props.pageSize)
262
+ : props.pageSize;
263
+ ConsumeNAsync(dataSource, actualPageSize)
264
+ .then(([data, finished]) => setSuccessState([...products, ...data], !finished));
265
+ }
266
+ }, [dataSource, props?.maxProducts, props?.pageSize, props, products]);
267
+ const mappedProducts = props?.withProductInfo === true
268
+ ? products.map(mapProductToData)
269
+ : products.map(mapProductToIds);
270
+ log?.debug('Final State', loading, productsError, products, apiError);
271
+ if (!loading && productsError === undefined) { /* Handle Success State */
272
+ return {
273
+ loading,
274
+ error: undefined,
275
+ products: mappedProducts,
276
+ hasMore,
277
+ refetch,
278
+ fetchNextPage: fetchProducts,
279
+ analytics: {
280
+ trackClick: product => {
281
+ const winUrl = product.productCardResponse.trackers?.win;
282
+ if (winUrl !== undefined) {
283
+ fetch(winUrl);
284
+ }
285
+ },
286
+ trackImpression: product => {
287
+ const impressionUrl = product.productCardResponse.trackers?.imp;
288
+ if (impressionUrl !== undefined) {
289
+ impressionUrl.forEach(url => fetch(url));
290
+ }
291
+ },
292
+ }
293
+ };
294
+ }
295
+ else if (!loading && productsError !== undefined) { /* Handle Error State */
296
+ return {
297
+ loading,
298
+ error: productsError,
299
+ products: mappedProducts,
300
+ hasMore: false,
301
+ refetch: undefined,
302
+ fetchNextPage: undefined,
303
+ analytics: undefined
304
+ };
305
+ }
306
+ else if (loading && productsError === undefined) { /* Handle Loading State */
307
+ return {
308
+ loading,
309
+ error: undefined,
310
+ products: mappedProducts,
311
+ hasMore,
312
+ refetch: undefined,
313
+ fetchNextPage: undefined,
314
+ analytics: undefined
315
+ };
316
+ }
317
+ else { /* Handle invalid states */
318
+ return {
319
+ loading: false,
320
+ error: Err(new InvalidProductsStateError(products, productsError, loading)),
321
+ products: mappedProducts,
322
+ hasMore,
323
+ refetch: undefined,
324
+ fetchNextPage: undefined,
325
+ analytics: undefined
326
+ };
327
+ }
328
+ }
329
+ ;
330
+ const mapProductToData = (product) => ({
331
+ data: product.product,
332
+ type: product.sponsored ? 'sponsored' : 'recommended',
333
+ productCardResponse: product,
334
+ });
335
+ const mapProductToIds = (product) => ({
336
+ id: product.product.id,
337
+ type: product.sponsored ? 'sponsored' : 'recommended',
338
+ productCardResponse: product
339
+ });
340
+ export class InvalidStrategyError extends Error {
341
+ strategy;
342
+ constructor(strategy) {
343
+ super('Invalid strategy withing useSurfsideProducts');
344
+ this.strategy = strategy;
345
+ }
346
+ }
347
+ export class InvalidProductsStateError extends Error {
348
+ products;
349
+ error;
350
+ loading;
351
+ constructor(products, error, loading) {
352
+ super('useSurfsideProducts resulted in an invalid state');
353
+ this.products = products;
354
+ this.error = error;
355
+ this.loading = loading;
356
+ }
357
+ }
358
+ ;
359
+ //# sourceMappingURL=useSurfsideProducts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSurfsideProducts.js","sourceRoot":"src/","sources":["hooks/useSurfsideProducts.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAOH,aAAa,EACb,GAAG,EACH,GAAG,EACH,eAAe,EACf,KAAK,EACR,MAAM,2BAA2B,CAAC;AAmClC,CAAC;AAkED,CAAC;AAgBD,CAAC;AAuHF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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YACxB,OAAO;YACP,OAAO,EAAE,SAAS;YAClB,aAAa,EAAE,SAAS;YACxB,SAAS,EAAE,SAAS;SACvB,CAAC;IACN,CAAC;AACL,CAAC;AAAA,CAAC;AAEF,MAAM,gBAAgB,GAAG,CAAC,OAAkC,EAAoB,EAAE,CAAC,CAAC;IAChF,IAAI,EAAE,OAAO,CAAC,OAAO;IACrB,IAAI,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,aAAa;IACrD,mBAAmB,EAAE,OAAO;CAC/B,CAAC,CAAC;AAEH,MAAM,eAAe,GAAG,CAAC,OAAkC,EAAkB,EAAE,CAAC,CAAC;IAC7E,EAAE,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE;IACtB,IAAI,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,aAAa;IACrD,mBAAmB,EAAE,OAAO;CAC/B,CAAC,CAAC;AAEH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACf;IAA5B,YAA4B,QAAgB;QACxC,KAAK,CAAC,8CAA8C,CAAC,CAAC;QAD9B,aAAQ,GAAR,QAAQ,CAAQ;IAE5C,CAAC;CACJ;AAED,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IAE5B;IACA;IACA;IAHpB,YACoB,QAAqC,EACrC,KAA4B,EAC5B,OAAgB;QAEhC,KAAK,CAAC,kDAAkD,CAAC,CAAC;QAJ1C,aAAQ,GAAR,QAAQ,CAA6B;QACrC,UAAK,GAAL,KAAK,CAAuB;QAC5B,YAAO,GAAP,OAAO,CAAS;IAGpC,CAAC;CACJ;AAAA,CAAC"}
@@ -0,0 +1,289 @@
1
+ 'use client';
2
+ import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
3
+ import { useSurfsideContext } from '../provider';
4
+ import { AsyncPipe, Err, WrapValue, Ctx, } from '@surfside/ads-core-client';
5
+ /**
6
+ * Requests and returns a video creative. Accepts size, duration, and MIME type arguments and returns an object wrapping
7
+ * the creative, exporting both a deserialized object representing the VAST 3.0 XML markup as well as the raw XML
8
+ * itself, which can be passed into video players supporting the VAST 3.0 XML specification. The return type also
9
+ * contains an `analytics` object which is a set of callback functions to be called for specific video playback events,
10
+ * such as completing each quartile of the video playback, recording impressions, and starting/finishing the video.
11
+ *
12
+ * @remarks
13
+ * Video players are more complicated to implement than static banner creatives because of their inherently interactive
14
+ * nature. Modern browsers will disallow videos from autoplaying unmuted, [except under specific circumstances](
15
+ * https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Autoplay#autoplay_availability). For this reason, it is
16
+ * recommended that you mark your `<video>` tag as `autoPlay muted`. e.g:
17
+ *
18
+ * ```html
19
+ * <video autoPlay muted>
20
+ * <!-- ... <source> tags go here -->
21
+ * </video>
22
+ * ```
23
+ *
24
+ * It is *possible* to autoplay a video unmuted under other circumstances, such as if the user has interacted with the
25
+ * page already. That implementation is left up to the developer.
26
+ *
27
+ * Surfside's bidder will always return with a single video creative per video bid request. This means that the
28
+ * `video.vast.ads` field will always have exactly one {@link IAd} object, and all VAST creative types will be a single
29
+ * `linear` video creative. This means that it will always be safe to do this:
30
+ *
31
+ * ```ts
32
+ * if (video !== undefined) {
33
+ * // URL of the video and its MIME type
34
+ * const { url, type } = video.ads[0].inline.creatives[0].mediaFiles[0];
35
+ * }
36
+ * ```
37
+ *
38
+ * Since this is somewhat verbose, these values are available to you through the `video.url` and `video.mime` fields
39
+ * within the {@link IVideo} object.
40
+ *
41
+ * @example
42
+ * A very simple video player for a video response might look like this
43
+ *
44
+ * ```tsx
45
+ * const { video, loading, error, analytics } = useSurfsideVideo({
46
+ * zoneId: 'my-zone',
47
+ * size: [4, 3], // 4x3 video ad
48
+ * maxDuration: 30 // 30 seconds max
49
+ * });
50
+ *
51
+ * // Call impression and win handlers if they exist
52
+ * useEffect(() => {
53
+ * analytics?.impression();
54
+ * analytics?.win();
55
+ * }, [analytics]);
56
+ *
57
+ * if (loading) {
58
+ * return <div>loading...</div>;
59
+ * }
60
+ *
61
+ * if (error) {
62
+ * throw error.error; // error.error is the Javascript Error type and can be safely thrown
63
+ * }
64
+ *
65
+ * return (
66
+ * <video autoplay muted>
67
+ * <source src={video.url} type={video.mime} />
68
+ * </video>
69
+ * );
70
+ * ```
71
+ *
72
+ * Note that this implementation ONLY implements the `win` and `impression` events. In order to implement playback-based
73
+ * events, you must write handlers for the [`play`, `ended`, and `timeupdate` events](
74
+ * https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/video#events). For quartile playback events, you
75
+ * will need to check the current time of the video during the `timeupdate` events to determine if the proper quartile
76
+ * has been passed (e.g, `firstQuartile` must be fired **a single time, only after the video has surpassed 25% of its
77
+ * duration**).
78
+ *
79
+ * @param {IUseSurfsideVideoOptions} props
80
+ *
81
+ * @expandType IUseSurfsideVideoOptions
82
+ * @expandType UseSurfsideVideoReturn
83
+ */
84
+ export const useSurfsideVideo = ({ zoneId, size, minDuration = 0, maxDuration, mimes = ['video/mp4'], enabled = true }) => {
85
+ const resolvedMimes = useMemo(() => mimes, [mimes.join(',')]);
86
+ const respProps = useMemo(() => ({
87
+ video: undefined,
88
+ zoneId,
89
+ size,
90
+ minDuration,
91
+ maxDuration,
92
+ mimes: resolvedMimes,
93
+ enabled
94
+ }), [zoneId, size?.[0], size?.[1], minDuration, maxDuration, resolvedMimes, enabled]);
95
+ const internalState = useSurfsideVideoResponse(respProps);
96
+ useEffect(() => {
97
+ internalState.refetch?.();
98
+ }, [internalState.refetch]);
99
+ return internalState;
100
+ };
101
+ export const useSurfsideVideoResponse = (props) => {
102
+ const { startRequest, requestBids, buildVideoResponse, logger, error: apiError, hasError: apiHasError, isReady: apiIsReady } = useSurfsideContext();
103
+ const [internalVideo, setInternalVideo] = useState(props?.video);
104
+ const [video, setVideo] = useState();
105
+ const [loading, setLoading] = useState(true);
106
+ const [videoError, setVideoError] = useState();
107
+ const trackingEvents = useRef();
108
+ useEffect(() => {
109
+ if (internalVideo?.ok === true) {
110
+ const value = internalVideo.value;
111
+ const ad = value.video.ads[0];
112
+ const creative = ad?.inline.creatives[0];
113
+ const mediaFile = creative?.mediaFiles[0];
114
+ const adm = internalVideo.value.bid.adm;
115
+ if (ad !== undefined && creative !== undefined && mediaFile !== undefined && adm !== undefined) {
116
+ setSuccessState({
117
+ ...internalVideo.value,
118
+ id: internalVideo.value.bid.id,
119
+ title: ad.inline.adTitle,
120
+ duration: creative.duration,
121
+ mime: mediaFile.type,
122
+ adm: adm,
123
+ videoUrl: mediaFile.url,
124
+ }, creative.trackingEvents);
125
+ }
126
+ }
127
+ else if (internalVideo?.ok === false) {
128
+ setErrorState(internalVideo);
129
+ }
130
+ }, [internalVideo]);
131
+ useEffect(() => {
132
+ if (props?.video === undefined) {
133
+ // setLoadingState();
134
+ // } else if (internalVideo?.ok === false) {
135
+ // setErrorState(internalVideo);
136
+ }
137
+ else {
138
+ setInternalVideo(props?.video);
139
+ }
140
+ }, [props?.video]);
141
+ const setErrorState = (err) => {
142
+ setVideoError(err);
143
+ setVideo(undefined);
144
+ setLoading(false);
145
+ trackingEvents.current = undefined;
146
+ };
147
+ const setLoadingState = () => {
148
+ setVideoError(undefined);
149
+ setVideo(undefined);
150
+ setLoading(true);
151
+ trackingEvents.current = undefined;
152
+ };
153
+ const setSuccessState = (video, track) => {
154
+ setVideoError(undefined);
155
+ setVideo(video);
156
+ setLoading(false);
157
+ trackingEvents.current = track;
158
+ };
159
+ const refetch = useCallback(async () => {
160
+ if (props === undefined || !apiIsReady || props.enabled === false) {
161
+ if (apiHasError) {
162
+ setErrorState(apiError);
163
+ }
164
+ return;
165
+ }
166
+ setLoadingState();
167
+ const request = startRequest(props.zoneId)
168
+ .withVideo(props.size[0], props.size[1], props.minDuration, props.maxDuration, props.mimes)
169
+ .build();
170
+ const videoResult = await AsyncPipe(requestBids(request))
171
+ .then(bidResponse => WrapValue(bidResponse.seatbid?.[0]?.bid?.[0]))
172
+ .then(buildVideoResponse)
173
+ .result();
174
+ setInternalVideo(videoResult);
175
+ }, [
176
+ apiIsReady,
177
+ apiError,
178
+ startRequest,
179
+ buildVideoResponse,
180
+ props?.enabled,
181
+ props?.zoneId,
182
+ props?.size[0],
183
+ props?.size[1],
184
+ props?.minDuration,
185
+ props?.maxDuration,
186
+ props?.mimes
187
+ ]);
188
+ const analytics = useMemo(() => {
189
+ if (video === undefined) {
190
+ return undefined;
191
+ }
192
+ return {
193
+ ...trackVideoEvents(trackingEvents.current, logger),
194
+ ...trackVideoWin
195
+ };
196
+ }, [video?.id]);
197
+ if (!loading && videoError === undefined && video !== undefined) {
198
+ return {
199
+ video,
200
+ error: videoError,
201
+ loading,
202
+ isReady: true,
203
+ analytics,
204
+ refetch
205
+ };
206
+ }
207
+ else if (!loading && videoError !== undefined && video === undefined) {
208
+ return {
209
+ video,
210
+ error: videoError,
211
+ loading: loading,
212
+ isReady: false,
213
+ analytics: undefined,
214
+ refetch
215
+ };
216
+ }
217
+ else if (loading && videoError === undefined && video === undefined) {
218
+ return {
219
+ video,
220
+ error: videoError,
221
+ loading,
222
+ isReady: false,
223
+ analytics: undefined,
224
+ refetch
225
+ };
226
+ }
227
+ else {
228
+ return {
229
+ video: undefined,
230
+ error: Err(new InvalidVideoStateError(video, videoError, loading)),
231
+ loading: false,
232
+ isReady: false,
233
+ analytics: undefined,
234
+ refetch: refetch
235
+ };
236
+ }
237
+ };
238
+ export class InvalidVideoStateError extends Error {
239
+ video;
240
+ error;
241
+ loading;
242
+ constructor(video, error, loading) {
243
+ super('useSurfsideBanner resulted in an invalid state');
244
+ this.video = video;
245
+ this.error = error;
246
+ this.loading = loading;
247
+ }
248
+ }
249
+ ;
250
+ const trackVideoWin = (video, logger) => () => {
251
+ if (video === undefined) {
252
+ return;
253
+ }
254
+ const log = Ctx(logger)?.with('trackWin');
255
+ if (video.bid.nurl !== undefined) {
256
+ const url = new URL(video.bid.nurl);
257
+ url.searchParams.delete('url');
258
+ fetch(url.toString()).then(() => log?.debug('Won auction', video));
259
+ }
260
+ else {
261
+ log?.error('Missing nurl on video bid response! This should never happen', video);
262
+ }
263
+ };
264
+ const trackVideoEvents = (trackingEvents, logger) => {
265
+ if (trackingEvents === undefined) {
266
+ return;
267
+ }
268
+ const log = Ctx(logger)?.with('trackVideoEvents');
269
+ // Helper to safely return a tracking function or no-op
270
+ const getTracker = (eventName) => {
271
+ const event = trackingEvents.find((e) => e.event === eventName);
272
+ if (event?.url === undefined) {
273
+ return () => log?.debug(`No tracker for event: ${eventName}`);
274
+ }
275
+ return () => {
276
+ fetch(event.url).then(() => log?.debug(`Tracked event: ${eventName}`));
277
+ };
278
+ };
279
+ return {
280
+ start: getTracker('start'),
281
+ firstQuartile: getTracker('firstQuartile'),
282
+ midpoint: getTracker('midpoint'),
283
+ thirdQuartile: getTracker('thirdQuartile'),
284
+ complete: getTracker('complete'),
285
+ impression: getTracker('impression'),
286
+ win: getTracker('win'),
287
+ };
288
+ };
289
+ //# sourceMappingURL=useSurfsideVideo.js.map