@streamlayer/feature-advertisement 1.1.1-rc.8.pd3aefe41 → 1.2.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.
Files changed (96) hide show
  1. package/lib/advertisement.d.ts +6 -6
  2. package/lib/advertisement.js +9 -9
  3. package/lib/index.d.ts +14 -15
  4. package/lib/index.js +9 -9
  5. package/lib/units/external-ad.d.ts +2 -2
  6. package/lib/units/external-ad.js +3 -3
  7. package/lib/units/external-pause-ad.js +1 -1
  8. package/lib/units/gam.js +1 -1
  9. package/lib/units/pause-ad.d.ts +1 -1
  10. package/lib/units/pause-ad.js +1 -1
  11. package/lib/units/sponsor-logo.d.ts +4 -12
  12. package/lib/units/sponsor-logo.js +3 -4
  13. package/lib/units/ssai-ad-break.d.ts +1 -1
  14. package/lib/units/ssai-creative.d.ts +1 -1
  15. package/lib/units/ssai-creative.js +1 -1
  16. package/lib/units/ssai-detector.d.ts +1 -1
  17. package/lib/units/ssai-detector.js +1 -1
  18. package/lib/units/ssai-preload.d.ts +1 -1
  19. package/lib/units/ssai-providers.d.ts +1 -1
  20. package/lib/units/ssai-providers.js +1 -1
  21. package/lib/units/vast-tracker.d.ts +1 -1
  22. package/package.json +9 -42
  23. package/classic/package.json +0 -5
  24. package/lib/cjs/advertisement.d.ts +0 -64
  25. package/lib/cjs/advertisement.js +0 -322
  26. package/lib/cjs/index.d.ts +0 -21
  27. package/lib/cjs/index.js +0 -41
  28. package/lib/cjs/package.json +0 -1
  29. package/lib/cjs/units/ad-macros.d.ts +0 -7
  30. package/lib/cjs/units/ad-macros.js +0 -91
  31. package/lib/cjs/units/external-ad.d.ts +0 -127
  32. package/lib/cjs/units/external-ad.js +0 -421
  33. package/lib/cjs/units/external-pause-ad.d.ts +0 -50
  34. package/lib/cjs/units/external-pause-ad.js +0 -259
  35. package/lib/cjs/units/gam.d.ts +0 -26
  36. package/lib/cjs/units/gam.js +0 -152
  37. package/lib/cjs/units/parse-vast-extensions.d.ts +0 -26
  38. package/lib/cjs/units/parse-vast-extensions.js +0 -56
  39. package/lib/cjs/units/pause-ad-card.d.ts +0 -49
  40. package/lib/cjs/units/pause-ad-card.js +0 -136
  41. package/lib/cjs/units/pause-ad.d.ts +0 -16
  42. package/lib/cjs/units/pause-ad.js +0 -52
  43. package/lib/cjs/units/sponsor-logo.d.ts +0 -78
  44. package/lib/cjs/units/sponsor-logo.js +0 -194
  45. package/lib/cjs/units/ssai-ad-break.d.ts +0 -21
  46. package/lib/cjs/units/ssai-ad-break.js +0 -11
  47. package/lib/cjs/units/ssai-creative.d.ts +0 -89
  48. package/lib/cjs/units/ssai-creative.js +0 -136
  49. package/lib/cjs/units/ssai-detector.d.ts +0 -180
  50. package/lib/cjs/units/ssai-detector.js +0 -1172
  51. package/lib/cjs/units/ssai-log.d.ts +0 -16
  52. package/lib/cjs/units/ssai-log.js +0 -23
  53. package/lib/cjs/units/ssai-preload.d.ts +0 -20
  54. package/lib/cjs/units/ssai-preload.js +0 -62
  55. package/lib/cjs/units/ssai-providers.d.ts +0 -117
  56. package/lib/cjs/units/ssai-providers.js +0 -300
  57. package/lib/cjs/units/vast-tracker.d.ts +0 -45
  58. package/lib/cjs/units/vast-tracker.js +0 -64
  59. package/lib/classic/_virtual/_rollupPluginBabelHelpers.js +0 -71
  60. package/lib/classic/advertisement.js +0 -348
  61. package/lib/classic/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -77
  62. package/lib/classic/cjs/advertisement.js +0 -350
  63. package/lib/classic/cjs/index.js +0 -49
  64. package/lib/classic/cjs/package.json +0 -1
  65. package/lib/classic/cjs/units/ad-macros.js +0 -115
  66. package/lib/classic/cjs/units/external-ad.js +0 -500
  67. package/lib/classic/cjs/units/external-pause-ad.js +0 -278
  68. package/lib/classic/cjs/units/gam.js +0 -173
  69. package/lib/classic/cjs/units/parse-vast-extensions.js +0 -60
  70. package/lib/classic/cjs/units/pause-ad-card.js +0 -134
  71. package/lib/classic/cjs/units/pause-ad.js +0 -72
  72. package/lib/classic/cjs/units/sponsor-logo.js +0 -201
  73. package/lib/classic/cjs/units/ssai-ad-break.js +0 -11
  74. package/lib/classic/cjs/units/ssai-creative.js +0 -142
  75. package/lib/classic/cjs/units/ssai-detector.js +0 -1195
  76. package/lib/classic/cjs/units/ssai-log.js +0 -23
  77. package/lib/classic/cjs/units/ssai-preload.js +0 -72
  78. package/lib/classic/cjs/units/ssai-providers.js +0 -361
  79. package/lib/classic/cjs/units/vast-tracker.js +0 -81
  80. package/lib/classic/index.js +0 -29
  81. package/lib/classic/units/ad-macros.js +0 -113
  82. package/lib/classic/units/external-ad.js +0 -491
  83. package/lib/classic/units/external-pause-ad.js +0 -275
  84. package/lib/classic/units/gam.js +0 -171
  85. package/lib/classic/units/parse-vast-extensions.js +0 -58
  86. package/lib/classic/units/pause-ad-card.js +0 -131
  87. package/lib/classic/units/pause-ad.js +0 -70
  88. package/lib/classic/units/sponsor-logo.js +0 -197
  89. package/lib/classic/units/ssai-ad-break.js +0 -9
  90. package/lib/classic/units/ssai-creative.js +0 -140
  91. package/lib/classic/units/ssai-detector.js +0 -1192
  92. package/lib/classic/units/ssai-log.js +0 -21
  93. package/lib/classic/units/ssai-preload.js +0 -68
  94. package/lib/classic/units/ssai-providers.js +0 -351
  95. package/lib/classic/units/vast-tracker.js +0 -77
  96. package/lib/vast-client.d.ts +0 -9
@@ -1,491 +0,0 @@
1
- import { asyncToGenerator as _asyncToGenerator } from '../_virtual/_rollupPluginBabelHelpers.js';
2
- import 'core-js/modules/es.symbol.description.js';
3
- import 'core-js/modules/es.error.cause.js';
4
- import 'core-js/modules/es.array.iterator.js';
5
- import 'core-js/modules/es.array.reduce.js';
6
- import 'core-js/modules/es.array.sort.js';
7
- import 'core-js/modules/es.json.stringify.js';
8
- import 'core-js/modules/es.promise.js';
9
- import 'core-js/modules/es.regexp.exec.js';
10
- import 'core-js/modules/es.string.replace.js';
11
- import 'core-js/modules/es.string.replace-all.js';
12
- import 'core-js/modules/esnext.iterator.constructor.js';
13
- import 'core-js/modules/esnext.iterator.filter.js';
14
- import 'core-js/modules/esnext.iterator.find.js';
15
- import 'core-js/modules/esnext.iterator.map.js';
16
- import 'core-js/modules/esnext.iterator.reduce.js';
17
- import 'core-js/modules/web.dom-collections.iterator.js';
18
- import 'core-js/modules/web.url.js';
19
- import 'core-js/modules/web.url.to-json.js';
20
- import 'core-js/modules/web.url-search-params.js';
21
- import 'core-js/modules/web.url-search-params.delete.js';
22
- import 'core-js/modules/web.url-search-params.has.js';
23
- import 'core-js/modules/web.url-search-params.size.js';
24
- import { createLogger } from '@streamlayer/sdk-web-logger/classic';
25
- import { VASTClient, VASTParser } from '@dailymotion/vast-client';
26
- import '@streamlayer/sdk-web-api/classic';
27
- import VMAP from 'vmap';
28
- import { gam } from './gam.js';
29
- import { parseVastExtension } from './parse-vast-extensions.js';
30
- import { collectAssets, selectCardLogo } from './sponsor-logo.js';
31
-
32
- const log = createLogger('ui:gam-external-ad');
33
- /** Default budget for a single VAST resolution before it is treated as "no ad". */
34
- const VAST_FETCH_TIMEOUT_MS = 10000;
35
- /**
36
- * Resolve `promise`, but fall back to `undefined` if it doesn't settle within `ms`.
37
- * A slow/unreachable VAST endpoint must degrade to "no ad" instead of leaving the
38
- * fetcher (and the sidebar) stuck waiting. Uses a timer rather than `AbortController`
39
- * so it stays safe on the ES5/Chrome-32 target.
40
- */
41
- const withTimeout = (promise, ms) => {
42
- return Promise.race([promise, new Promise(resolve => {
43
- setTimeout(() => resolve(undefined), ms);
44
- })]);
45
- };
46
- // const preloadImage = (src: string) => {
47
- // return new Promise((resolve, reject) => {
48
- // const image = new Image()
49
- // image.onload = () => resolve(src)
50
- // image.onerror = () => reject()
51
- // image.src = src
52
- // })
53
- // }
54
- /**
55
- * Get the first valid creative from an ad
56
- */
57
- const getCreative = ad => {
58
- return ad.creatives.find(creative => getMediaFileUrl(creative));
59
- };
60
- /**
61
- * Get the URL of the first media file in the creative
62
- */
63
- const getMediaFileUrl = creative => {
64
- var _mediaFiles$find;
65
- const mediaFiles = creative === null || creative === void 0 ? void 0 : creative.mediaFiles;
66
- if (!(mediaFiles !== null && mediaFiles !== void 0 && mediaFiles.length)) {
67
- return '';
68
- }
69
- return ((_mediaFiles$find = mediaFiles.find(mediaFile => mediaFile.fileURL)) === null || _mediaFiles$find === void 0 ? void 0 : _mediaFiles$find.fileURL) || '';
70
- };
71
- /**
72
- * Extract the linear creative's `<ClickThrough>` URL. Sources the sidebar CTA (QR code
73
- * + click-through). `videoClickThroughURLTemplate` isn't strongly typed in the client lib.
74
- */
75
- const getClickThrough = creative => {
76
- var _creative$videoClickT;
77
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
78
- // @ts-ignore — vast-client types `videoClickThroughURLTemplate` loosely
79
- return (creative === null || creative === void 0 || (_creative$videoClickT = creative.videoClickThroughURLTemplate) === null || _creative$videoClickT === void 0 ? void 0 : _creative$videoClickT.url) || undefined;
80
- };
81
- /** Product companion mapping: the 300x75 companion is the logo, the banner-sized one the media. */
82
- const LOGO_COMPANION_WIDTH = 300;
83
- const LOGO_COMPANION_HEIGHT = 75;
84
- const isLogoSized = companion => (companion === null || companion === void 0 ? void 0 : companion.width) === LOGO_COMPANION_WIDTH && (companion === null || companion === void 0 ? void 0 : companion.height) === LOGO_COMPANION_HEIGHT;
85
- const companionArea = companion => (companion.width || 0) * (companion.height || 0);
86
- /**
87
- * Split a `<CompanionAds>` creative's variations into the logo and media slots.
88
- *
89
- * The pair mapping activates only for a tag that ships an exact 300x75 companion next to at
90
- * least one other. Deliberately conservative pending broader product sizes: on any other tag
91
- * no companion is promoted to the logo slot and the first one stays the media/strip candidate.
92
- *
93
- * Both halves of that gate are load-bearing and neither is an aspect rule: a 320x80 companion is
94
- * the same 4:1 shape as 300x75 and is still rejected, and a lone 300x75 companion is rejected too
95
- * (the Standard Ad Sidebar recovers that one as `AdData.loneLogo` when a Linear / NonLinear is
96
- * the media, so it is not needed here).
97
- * This is **narrower than iOS**, which has no size rule at all and fills its logo slot from a
98
- * single companion — see `docs/wiki/programmatic-ads-display-ios-parity.md`. Exported for
99
- * `external-ad.spec.ts` only; `src/index.ts` re-exports names explicitly, so this stays out of the
100
- * package's public API.
101
- */
102
- const selectCompanions = companions => {
103
- const logo = companions.length > 1 ? companions.find(companion => isLogoSized(companion)) : undefined;
104
- if (!logo) {
105
- return {
106
- logo: undefined,
107
- media: companions[0]
108
- };
109
- }
110
- const media = companions.filter(companion => companion !== logo).sort((a, b) => companionArea(a) - companionArea(b)).pop();
111
- return {
112
- logo,
113
- media
114
- };
115
- };
116
- /**
117
- * Map a parsed VAST response into our `AdData` shape. Shared by both acquisition
118
- * paths — the GAM/VMAP tag flow and the Prebid auction flow — so the two always
119
- * produce identical downstream data.
120
- *
121
- * Returns `undefined` for a no-ad, which is two distinct shapes: a response with no ad carrying
122
- * creatives, and an ad whose creatives carry no RENDERABLE asset — no linear `<MediaFile>`, no
123
- * `<NonLinear>` still and no `<Companion>` image. Both callers `filter(Boolean)` the result, so a
124
- * no-ad leaves `ads: []` and the card keeps whatever the server configured for it.
125
- *
126
- * Exported for `vast-mapping.spec.ts`, which drives it over the same fixture corpus the iOS suite
127
- * uses. `src/index.ts` re-exports names explicitly, so this stays out of the package's public API.
128
- */
129
- const buildAdData = (parsedVAST, order) => {
130
- var _validAd$extensions$f;
131
- // Defensive, and unreachable through either production path: `@dailymotion/vast-client` discards
132
- // an ad whose creatives all fail to parse (empty `<Linear>`, empty/missing `<Creatives>`, unknown
133
- // creative element) before `parseVAST` resolves, so it never yields an Ad with zero creatives.
134
- // Kept because it costs nothing and `buildAdData` is also reachable from tests with a hand-built
135
- // response — see the `invalid_ad` case in `vast-mapping.spec.ts`, which pins the parser contract
136
- // this relies on rather than pretending to exercise the guard.
137
- const validAd = parsedVAST.ads.find(ads => ads.creatives.length > 0);
138
- if (!validAd) {
139
- log.warn({
140
- order,
141
- ads: parsedVAST.ads.length
142
- }, 'vast response carries no ad with creatives — treated as no-ad');
143
- return undefined;
144
- }
145
- const extension = (_validAd$extensions$f = validAd.extensions.find(ext => ext.attributes.type.startsWith('streamlayer'))) === null || _validAd$extensions$f === void 0 ? void 0 : _validAd$extensions$f.children[0];
146
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
147
- // @ts-expect-error
148
- const parsedExtension = parseVastExtension(extension);
149
- const creative = getCreative(validAd);
150
- const mediaFileUrl = getMediaFileUrl(creative);
151
- const images = collectAssets(validAd);
152
- const companions = images.filter(asset => asset.origin === 'companion');
153
- const nonLinear = images.find(asset => asset.origin === 'nonlinear');
154
- // An ad the parser KEPT whose creatives carry nothing any shell can draw is a no-ad, exactly
155
- // like a response with no ad at all. vast-client only discards a creative it cannot parse; a
156
- // `<NonLinear>` or `<Companion>` whose `<StaticResource>` body is empty parses fine and just
157
- // yields no url, so the guard above cannot catch it. Without this the fabricated promotion still
158
- // took the slot and drew the ad's TEXT — title and description over an empty media box — which
159
- // is a billable impression for a creative that does not exist.
160
- //
161
- // "Renderable" is the union of the three slots the shells can fill: a linear `<MediaFile>`, a
162
- // `<NonLinear>` still, or a `<Companion>` image. `collectAssets` already drops the imageless
163
- // ones, so a non-empty `companions` means at least one drawable image. A tag carrying only a
164
- // `<Mezzanine>` never reaches here — the parser drops that Linear itself — but it lands in the
165
- // same place either way.
166
- if (!mediaFileUrl && !nonLinear && companions.length === 0) {
167
- log.warn({
168
- order,
169
- adId: validAd.id,
170
- creatives: validAd.creatives.length
171
- }, 'vast ad carries no renderable asset (no media file, no nonlinear, no companion) — treated as no-ad');
172
- return undefined;
173
- }
174
- const {
175
- logo,
176
- media: mediaCompanion
177
- } = selectCompanions(companions);
178
- const clickThrough = getClickThrough(creative) || (nonLinear === null || nonLinear === void 0 ? void 0 : nonLinear.clickUrl) || (mediaCompanion === null || mediaCompanion === void 0 ? void 0 : mediaCompanion.clickUrl);
179
- // Mirror iOS's greedy `pool.select([hero, .cardLogo])`: the hero claims first and a claimed
180
- // asset is gone for later roles. Web's hero precedence (`createActiveAdFromVast`) is linear
181
- // video → pair media companion (unreachable here: a `logo` short-circuits the whole selection)
182
- // → NonLinear still → lone companion, so a companion is only unavailable to the logo slot when
183
- // it IS the hero, i.e. when the tag ships neither. `selectCardLogo` already filters to companion
184
- // origins, so the NonLinear never needs excluding.
185
- //
186
- // Excluding `companions[0]` (which is what `mediaCompanion` is when there is no `logo`) rather
187
- // than the largest-area asset is a deliberate difference from iOS's `areaDominant` hero: web's
188
- // content slot draws the FIRST companion in document order, so document order is the correct
189
- // criterion for "what the hero already claimed" on this platform.
190
- const companionIsHero = !mediaFileUrl && !nonLinear;
191
- const cardLogoAsset = logo ? undefined : selectCardLogo(validAd, companionIsHero ? [mediaCompanion] : []);
192
- // Share the selected resource wrapper so drawn-companion identity remains stable.
193
- const cardLogo = cardLogoAsset ? companions.find(item => item.variation === cardLogoAsset.variation && item.imageUrl === cardLogoAsset.imageUrl) : undefined;
194
- // Same collected instance as `companion` (identity matters to `drawnCompanions`). A lone
195
- // companion never satisfies the pair rule, so this can only fill a slot `logo` left empty.
196
- const loneLogo = companions.length === 1 && !companionIsHero && isLogoSized(companions[0]) ? companions[0] : undefined;
197
- log.info({
198
- order,
199
- adId: validAd.id,
200
- title: validAd.title || undefined,
201
- found: {
202
- linear: !!creative,
203
- mediaFile: mediaFileUrl || undefined,
204
- nonLinear: nonLinear ? `${nonLinear.width}x${nonLinear.height}` : undefined,
205
- companions: companions.map(item => `${item.width}x${item.height}`)
206
- },
207
- selected: {
208
- logo: logo ? {
209
- size: `${logo.width}x${logo.height}`,
210
- url: logo.imageUrl
211
- } : undefined,
212
- media: mediaCompanion ? {
213
- size: `${mediaCompanion.width}x${mediaCompanion.height}`,
214
- url: mediaCompanion.imageUrl
215
- } : undefined,
216
- cardLogo: cardLogo ? {
217
- size: `${cardLogo.width}x${cardLogo.height}`,
218
- url: cardLogo.imageUrl
219
- } : undefined,
220
- loneLogo: loneLogo ? {
221
- size: `${loneLogo.width}x${loneLogo.height}`,
222
- url: loneLogo.imageUrl
223
- } : undefined,
224
- clickThrough: !!clickThrough
225
- }
226
- }, 'vast ad parsed');
227
- return {
228
- creative,
229
- order,
230
- mediaFileUrl,
231
- companion: companions[0],
232
- logo,
233
- cardLogo,
234
- loneLogo,
235
- mediaCompanion,
236
- nonLinear,
237
- clickThrough,
238
- title: validAd.title || undefined,
239
- description: validAd.description || undefined,
240
- ad: validAd,
241
- extension: parsedExtension,
242
- raw: parsedVAST
243
- };
244
- };
245
- /** Path of the self-hosted Prebid Server OpenRTB auction endpoint. */
246
- const PREBID_AUCTION_PATH = '/openrtb2/auction';
247
- /**
248
- * A Prebid link points at our Prebid Server auction endpoint (staging:
249
- * `https://prebid.next.streamlayer.io/openrtb2/auction`) rather than at a VAST tag.
250
- * Detected by path so both staging and production hosts match.
251
- */
252
- const isPrebidUrl = url => url.pathname.endsWith(PREBID_AUCTION_PATH);
253
- /** Unique per-auction request id — Prebid responses are never cached/reused (RFC §5). */
254
- const createRequestId = () => `sl-web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
255
- /**
256
- * Build the OpenRTB request body for a single video auction. Placement config is
257
- * carried on the Prebid link's query string so the consumer-facing interface stays a
258
- * single URL string:
259
- * - `configId` → `imp.ext.prebid.storedrequest.id` (production stored request).
260
- * - `storedauctionresponse` → `imp.ext.prebid.storedauctionresponse.id` (staging mock).
261
- * - `test=1` → top-level `test` flag.
262
- * - `w` / `h` → video dimensions (default 1920×1080).
263
- *
264
- * The host's GDPR consent (`AdTagParams`) rides the OpenRTB 2.5 extension fields Prebid Server
265
- * reads — `regs.ext.gdpr` and `user.ext.consent` — the same signal the `${GDPR}` /
266
- * `${GDPR_CONSENT}` macros carry for a VAST tag. Each is sent only when the host passed it.
267
- */
268
- const buildAuctionRequest = (url, adTagParams) => {
269
- var _ref, _params$get, _params$get2;
270
- const params = url.searchParams;
271
- const width = Number(params.get('w')) || 1920;
272
- const height = Number(params.get('h')) || 1080;
273
- const configId = (_ref = (_params$get = params.get('configId')) !== null && _params$get !== void 0 ? _params$get : params.get('config_id')) !== null && _ref !== void 0 ? _ref : undefined;
274
- const storedAuctionResponse = (_params$get2 = params.get('storedauctionresponse')) !== null && _params$get2 !== void 0 ? _params$get2 : undefined;
275
- const prebid = {};
276
- if (storedAuctionResponse) {
277
- prebid.storedauctionresponse = {
278
- id: storedAuctionResponse
279
- };
280
- }
281
- if (configId) {
282
- prebid.storedrequest = {
283
- id: configId
284
- };
285
- }
286
- prebid.bidder = {
287
- appnexus: {
288
- placementId: 13144370
289
- }
290
- };
291
- const request = {
292
- id: createRequestId(),
293
- imp: [{
294
- id: '1',
295
- video: {
296
- mimes: ['video/mp4'],
297
- protocols: [2, 3, 5, 6],
298
- w: width,
299
- h: height,
300
- placement: 1,
301
- linearity: 1
302
- },
303
- ext: {
304
- prebid
305
- }
306
- }],
307
- site: {
308
- page: typeof location !== 'undefined' ? location.href : url.origin
309
- },
310
- tmax: 500
311
- };
312
- if (params.get('test') === '1') {
313
- request.test = 1;
314
- }
315
- if ((adTagParams === null || adTagParams === void 0 ? void 0 : adTagParams.gdprApplies) !== undefined) {
316
- request.regs = {
317
- ext: {
318
- gdpr: adTagParams.gdprApplies ? 1 : 0
319
- }
320
- };
321
- }
322
- if (adTagParams !== null && adTagParams !== void 0 && adTagParams.tcString) {
323
- request.user = {
324
- ext: {
325
- consent: adTagParams.tcString
326
- }
327
- };
328
- }
329
- return request;
330
- };
331
- /**
332
- * Run one Prebid Server auction and turn the winning inline VAST into an `AdStore`.
333
- * Every bid's `adm` is inline VAST XML (no URL to fetch); bids are ordered by price
334
- * so the winner plays first (RFC §2). A single bad bid must not drop the batch.
335
- */
336
- const fetchPrebidAds = /*#__PURE__*/function () {
337
- var _ref2 = _asyncToGenerator(function* (prebidUrl, adTagParams) {
338
- var _auction$seatbid, _params$get3, _params$get4;
339
- const response = yield fetch(prebidUrl.toString(), {
340
- method: 'POST',
341
- headers: {
342
- 'Content-Type': 'application/json'
343
- },
344
- body: JSON.stringify(buildAuctionRequest(prebidUrl, adTagParams))
345
- });
346
- if (!response.ok) {
347
- throw new Error(`prebid auction failed with status ${response.status}`);
348
- }
349
- const auction = yield response.json();
350
- const bids = ((_auction$seatbid = auction.seatbid) !== null && _auction$seatbid !== void 0 ? _auction$seatbid : []).reduce((acc, seat) => {
351
- var _seat$bid;
352
- return acc.concat((_seat$bid = seat.bid) !== null && _seat$bid !== void 0 ? _seat$bid : []);
353
- }, []).filter(bid => !!bid.adm)
354
- // Highest price wins — the winner is order 0 (RFC §2).
355
- .sort((a, b) => {
356
- var _b$price, _a$price;
357
- return ((_b$price = b.price) !== null && _b$price !== void 0 ? _b$price : 0) - ((_a$price = a.price) !== null && _a$price !== void 0 ? _a$price : 0);
358
- });
359
- const parser = new DOMParser();
360
- const loadedAds = yield Promise.all(bids.map((bid, i) => {
361
- const xmlDoc = parser.parseFromString(bid.adm, 'text/xml');
362
- // A fresh `VASTParser` per bid isolates parser state, mirroring the fresh
363
- // `VASTClient` per link in the tag flow. `resolveAll: true` follows any
364
- // `VASTAdTagURI` wrapper chain the bid's inline VAST may still contain.
365
- return new VASTParser()
366
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
367
- // @ts-ignore
368
- .parseVAST(xmlDoc, {
369
- resolveAll: true,
370
- wrapperLimit: 10,
371
- allowMultipleAds: true
372
- }).then(parsedVAST => buildAdData(parsedVAST, i)).catch(err => {
373
- // A single failing bid must not drop the whole batch.
374
- log.error(err, 'failed to parse prebid VAST');
375
- return undefined;
376
- });
377
- }));
378
- const params = prebidUrl.searchParams;
379
- const autoplay = ((_params$get3 = params.get('vpa')) === null || _params$get3 === void 0 ? void 0 : _params$get3.replaceAll('?', '')) !== 'click';
380
- const muted = ((_params$get4 = params.get('vpmute')) === null || _params$get4 === void 0 ? void 0 : _params$get4.replaceAll('?', '')) === '1';
381
- return {
382
- ads: loadedAds.filter(d => !!d),
383
- autoplay,
384
- muted
385
- };
386
- });
387
- return function fetchPrebidAds(_x, _x2) {
388
- return _ref2.apply(this, arguments);
389
- };
390
- }();
391
- const externalAd = instance => {
392
- return gamUrl => instance.transport.nanoquery.createFetcherStore([gamUrl], {
393
- dedupeTime: Infinity,
394
- revalidateInterval: 0,
395
- fetcher: function () {
396
- var _ref3 = _asyncToGenerator(function* (adUrl) {
397
- var _noncedLink$searchPar, _noncedLink$searchPar2, _noncedLink$searchPar3;
398
- if (!adUrl || typeof adUrl !== 'string') {
399
- throw new Error('ad url is empty');
400
- }
401
- const parsedAdUrl = (() => {
402
- try {
403
- return new URL(adUrl);
404
- } catch (_unused) {
405
- return undefined;
406
- }
407
- })();
408
- // The host's CURRENT macro values, read per request rather than baked into the store: the
409
- // store is cached by url for the session, and consent routinely arrives after the SDK
410
- // starts (a CMP answers asynchronously) or changes mid-session.
411
- const adTagParams = instance.sdk.options.get().adTagParams;
412
- // Prebid links hit our Prebid Server auction endpoint instead of a VAST tag.
413
- // Run the OpenRTB auction and parse the winning bid's inline VAST (`adm`) into
414
- // the same `AdStore` shape the GAM/VMAP path returns. See rfcs/prebid.
415
- if (parsedAdUrl && isPrebidUrl(parsedAdUrl)) {
416
- return fetchPrebidAds(parsedAdUrl, adTagParams);
417
- }
418
- const generateUrl = gam(adUrl, undefined, adTagParams);
419
- const generatedUrl = yield generateUrl();
420
- const noncedLink = generatedUrl === null || generatedUrl === void 0 ? void 0 : generatedUrl.url;
421
- if (!noncedLink) {
422
- throw new Error('ad url is not generated');
423
- }
424
- let links;
425
- if (((_noncedLink$searchPar = noncedLink.searchParams.get('output')) === null || _noncedLink$searchPar === void 0 ? void 0 : _noncedLink$searchPar.replaceAll('?', '')) === 'vmap') {
426
- const response = yield withTimeout(fetch(noncedLink.toString()), VAST_FETCH_TIMEOUT_MS);
427
- if (!response) {
428
- throw new Error('vmap fetch timed out');
429
- }
430
- const parser = new DOMParser();
431
- const xmlStr = yield response.text();
432
- const xmlDoc = parser.parseFromString(xmlStr, 'text/xml');
433
- const vmap = new VMAP(xmlDoc);
434
- links = vmap.adBreaks.map(ad => {
435
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
436
- // @ts-expect-error
437
- return ad.adSource.adTagURI.uri;
438
- });
439
- } else {
440
- links = [noncedLink.toString()];
441
- }
442
- const loadedAds = yield Promise.all(links.map((link, i) => {
443
- // `resolveAll: true` makes the client follow every `VASTAdTagURI` wrapper chain
444
- // (up to the default depth of 10) and resolve all Ads, merging wrapper-level
445
- // Impression/tracking URLs into the inline Ad. The default (`resolveAll: false`)
446
- // only resolves the first standalone Ad and defers wrappers/remaining Ads to
447
- // `getNextAds()`, which this fetcher never calls. A fresh `VASTClient` per link
448
- // isolates parser state so concurrent (VMAP) resolutions don't clobber each other.
449
- return withTimeout(new VASTClient()
450
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
451
- // @ts-ignore
452
- .get(link, {
453
- resolveAll: true,
454
- wrapperLimit: 10,
455
- allowMultipleAds: true
456
- }), VAST_FETCH_TIMEOUT_MS).then(parsedVAST => {
457
- // `parsedVAST` is `undefined` when the resolution timed out (see `withTimeout`).
458
- if (!parsedVAST) {
459
- log.warn({
460
- link,
461
- timeoutMs: VAST_FETCH_TIMEOUT_MS
462
- }, 'vast resolution timed out — treated as no-ad');
463
- return undefined;
464
- }
465
- return buildAdData(parsedVAST, i);
466
- }).catch(err => {
467
- // A single failing wrapper chain must not drop the whole batch.
468
- log.error(err, 'failed to resolve VAST');
469
- return undefined;
470
- });
471
- }));
472
- const autoplay = ((_noncedLink$searchPar2 = noncedLink.searchParams.get('vpa')) === null || _noncedLink$searchPar2 === void 0 ? void 0 : _noncedLink$searchPar2.replaceAll('?', '')) !== 'click';
473
- const muted = ((_noncedLink$searchPar3 = noncedLink.searchParams.get('vpmute')) === null || _noncedLink$searchPar3 === void 0 ? void 0 : _noncedLink$searchPar3.replaceAll('?', '')) === '1';
474
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
475
- // @ts-expect-error
476
- const nonceManager = generatedUrl.manager;
477
- return {
478
- ads: loadedAds.filter(d => !!d),
479
- autoplay,
480
- muted,
481
- nonceManager
482
- };
483
- });
484
- return function fetcher(_x3) {
485
- return _ref3.apply(this, arguments);
486
- };
487
- }()
488
- });
489
- };
490
-
491
- export { buildAdData, buildAuctionRequest, externalAd, selectCompanions };