@giphy/js-util 4.4.2 → 5.1.0-beta.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/dist/index.js CHANGED
@@ -1,41 +1,364 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.checkIfWebP = exports.getSpecificRendition = exports.getGifWidth = exports.getGifHeight = exports.getBestVideo = exports.getBestRenditionUrl = exports.getBestRendition = exports.getAltText = exports.getPingbackId = exports.getClientRect = exports.setRenditionScaleUpMaxPixels = exports.bestfit = void 0;
21
- var bestfit_1 = require("./bestfit");
22
- Object.defineProperty(exports, "bestfit", { enumerable: true, get: function () { return __importDefault(bestfit_1).default; } });
23
- Object.defineProperty(exports, "setRenditionScaleUpMaxPixels", { enumerable: true, get: function () { return bestfit_1.setRenditionScaleUpMaxPixels; } });
24
- __exportStar(require("./collections"), exports);
25
- var get_client_rect_from_el_1 = require("./get-client-rect-from-el");
26
- Object.defineProperty(exports, "getClientRect", { enumerable: true, get: function () { return __importDefault(get_client_rect_from_el_1).default; } });
27
- var get_pingback_id_1 = require("./get-pingback-id");
28
- Object.defineProperty(exports, "getPingbackId", { enumerable: true, get: function () { return __importDefault(get_pingback_id_1).default; } });
29
- var gif_utils_1 = require("./gif-utils");
30
- Object.defineProperty(exports, "getAltText", { enumerable: true, get: function () { return gif_utils_1.getAltText; } });
31
- Object.defineProperty(exports, "getBestRendition", { enumerable: true, get: function () { return gif_utils_1.getBestRendition; } });
32
- Object.defineProperty(exports, "getBestRenditionUrl", { enumerable: true, get: function () { return gif_utils_1.getBestRenditionUrl; } });
33
- Object.defineProperty(exports, "getBestVideo", { enumerable: true, get: function () { return gif_utils_1.getBestVideo; } });
34
- Object.defineProperty(exports, "getGifHeight", { enumerable: true, get: function () { return gif_utils_1.getGifHeight; } });
35
- Object.defineProperty(exports, "getGifWidth", { enumerable: true, get: function () { return gif_utils_1.getGifWidth; } });
36
- Object.defineProperty(exports, "getSpecificRendition", { enumerable: true, get: function () { return gif_utils_1.getSpecificRendition; } });
37
- __exportStar(require("./log"), exports);
38
- __exportStar(require("./sdk-headers"), exports);
39
- var webp_check_1 = require("./webp-check");
40
- Object.defineProperty(exports, "checkIfWebP", { enumerable: true, get: function () { return webp_check_1.checkIfWebP; } });
41
- //# sourceMappingURL=index.js.map
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+
21
+ // src/log.ts
22
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
23
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
24
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
25
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
26
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
27
+ return LogLevel2;
28
+ })(LogLevel || {});
29
+ var Logger = {
30
+ ENABLED: typeof window !== "undefined" && typeof location !== "undefined" && location.search.indexOf("giphy-debug") !== -1,
31
+ LEVEL: 0,
32
+ PREFIX: "GiphyJS",
33
+ debug: (...msg) => {
34
+ if (Logger.ENABLED && Logger.LEVEL <= 0 /* DEBUG */) {
35
+ console.debug(Logger.PREFIX, ...msg);
36
+ }
37
+ },
38
+ info: (...msg) => {
39
+ if (Logger.ENABLED && Logger.LEVEL <= 1 /* INFO */) {
40
+ console.info(Logger.PREFIX, ...msg);
41
+ }
42
+ },
43
+ warn: (...msg) => {
44
+ if (Logger.ENABLED && Logger.LEVEL <= 2 /* WARN */) {
45
+ console.warn(Logger.PREFIX, ...msg);
46
+ }
47
+ },
48
+ error: (...msg) => {
49
+ if (Logger.ENABLED && Logger.LEVEL <= 3 /* ERROR */) {
50
+ console.error(Logger.PREFIX, ...msg);
51
+ }
52
+ }
53
+ };
54
+
55
+ // src/bestfit.ts
56
+ var closestArea = (width, height, renditions) => {
57
+ let currentBest = Infinity;
58
+ let result;
59
+ renditions.forEach((rendition) => {
60
+ const widthPercentage = rendition.width / width;
61
+ const heightPercentage = rendition.height / height;
62
+ const areaPercentage = widthPercentage * heightPercentage;
63
+ const testBest = Math.abs(1 - areaPercentage);
64
+ if (testBest < currentBest) {
65
+ currentBest = testBest;
66
+ result = rendition;
67
+ }
68
+ });
69
+ return result;
70
+ };
71
+ var SCALE_UP_MAX_PIXELS = 50;
72
+ var setRenditionScaleUpMaxPixels = (pixels) => {
73
+ Logger.debug(`@giphy/js-util set rendition selection scale up max pixels to ${pixels}`);
74
+ SCALE_UP_MAX_PIXELS = pixels;
75
+ };
76
+ function bestfit(renditions, width, height, scaleUpMaxPixels = SCALE_UP_MAX_PIXELS) {
77
+ let [largestRendition] = renditions;
78
+ const testRenditions = renditions.filter((rendition) => {
79
+ if (rendition.width * rendition.height > largestRendition.width * largestRendition.height) {
80
+ largestRendition = rendition;
81
+ }
82
+ return width - rendition.width <= scaleUpMaxPixels && height - rendition.height <= scaleUpMaxPixels;
83
+ });
84
+ if (testRenditions.length === 0) {
85
+ return largestRendition;
86
+ }
87
+ return closestArea(width, height, testRenditions);
88
+ }
89
+ var bestfit_default = bestfit;
90
+
91
+ // src/collections.ts
92
+ function mapValues(object, mapFn) {
93
+ if (Array.isArray(object)) {
94
+ throw `This map is just for objects, just use array.map for arrays`;
95
+ }
96
+ return Object.keys(object).reduce((result, key) => {
97
+ result[key] = mapFn(object[key], key);
98
+ return result;
99
+ }, {});
100
+ }
101
+ function forEach(object, mapFn) {
102
+ if (Array.isArray(object)) {
103
+ throw `This map is just for objects, just use array.forEach for arrays`;
104
+ }
105
+ return Object.keys(object).forEach((key) => {
106
+ mapFn(object[key], key);
107
+ });
108
+ }
109
+ function take(arr, count = 0) {
110
+ return arr.slice(0, count);
111
+ }
112
+ function without(arr, values) {
113
+ return arr.filter((val) => values.indexOf(val) === -1);
114
+ }
115
+ function pick(object, pick2) {
116
+ const res = {};
117
+ pick2.forEach((key) => {
118
+ if (object[key] !== void 0) {
119
+ res[key] = object[key];
120
+ }
121
+ });
122
+ return res;
123
+ }
124
+
125
+ // src/construct-moat-data.ts
126
+ var constructMoatData = ({ tdata }) => {
127
+ var _a;
128
+ const [moatTrackerData] = ((_a = tdata == null ? void 0 : tdata.web) == null ? void 0 : _a.filter((tracker) => tracker.vendor === "Moat")) || [];
129
+ if (moatTrackerData == null ? void 0 : moatTrackerData.verificationParameters) {
130
+ const {
131
+ moatClientLevel1 = "_ADVERTISER_",
132
+ moatClientLevel2 = "_CAMPAIGN_",
133
+ moatClientLevel3 = "_LINE_ITEM_",
134
+ moatClientLevel4 = "_CREATIVE_",
135
+ moatClientSlicer1 = "_SITE_",
136
+ moatClientSlicer2 = "_PLACEMENT_",
137
+ zMoatPosition = "_POSITION_"
138
+ } = moatTrackerData.verificationParameters;
139
+ return {
140
+ moatClientLevel1,
141
+ moatClientLevel2,
142
+ moatClientLevel3,
143
+ moatClientLevel4,
144
+ moatClientSlicer1,
145
+ moatClientSlicer2,
146
+ zMoatPosition
147
+ };
148
+ }
149
+ };
150
+
151
+ // src/get-client-rect-from-el.ts
152
+ var getClientRect = (el) => {
153
+ let left = 0;
154
+ let top = 0;
155
+ const width = el.offsetWidth;
156
+ const height = el.offsetHeight;
157
+ do {
158
+ left += el.offsetLeft;
159
+ top += el.offsetTop;
160
+ el = el.offsetParent;
161
+ } while (el);
162
+ const result = {
163
+ left,
164
+ top,
165
+ width,
166
+ height,
167
+ right: left + width,
168
+ bottom: top + height,
169
+ x: left,
170
+ y: top
171
+ };
172
+ return __spreadProps(__spreadValues({}, result), { toJSON: () => JSON.stringify(result) });
173
+ };
174
+ var get_client_rect_from_el_default = getClientRect;
175
+
176
+ // src/get-pingback-id.ts
177
+ import { v4 as uuid } from "uuid";
178
+ var pingbackId = "";
179
+ var idLength = 16;
180
+ var noUUIDRandom = () => {
181
+ let result = "";
182
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
183
+ const charactersLength = characters.length;
184
+ for (let i = 0; i < idLength; i++) {
185
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
186
+ }
187
+ return result;
188
+ };
189
+ var getPingbackId = () => {
190
+ if (!pingbackId) {
191
+ try {
192
+ pingbackId = sessionStorage.getItem("giphyPingbackId");
193
+ } catch (_) {
194
+ }
195
+ if (!pingbackId) {
196
+ const hexTime = (/* @__PURE__ */ new Date()).getTime().toString(16);
197
+ try {
198
+ pingbackId = `${hexTime}${uuid().replace(/-/g, "")}`.substring(0, idLength);
199
+ } catch (error) {
200
+ pingbackId = noUUIDRandom();
201
+ }
202
+ try {
203
+ sessionStorage.setItem("giphyPingbackId", pingbackId);
204
+ } catch (_) {
205
+ }
206
+ }
207
+ }
208
+ return pingbackId;
209
+ };
210
+ var get_pingback_id_default = getPingbackId;
211
+
212
+ // src/webp-check.ts
213
+ var SUPPORTS_WEBP = null;
214
+ var checkIfWebP = new Promise((resolve) => {
215
+ if (typeof Image === "undefined") {
216
+ resolve(false);
217
+ }
218
+ const webp = new Image();
219
+ webp.onload = () => {
220
+ SUPPORTS_WEBP = true;
221
+ resolve(SUPPORTS_WEBP);
222
+ };
223
+ webp.onerror = () => {
224
+ SUPPORTS_WEBP = false;
225
+ resolve(SUPPORTS_WEBP);
226
+ };
227
+ webp.src = "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";
228
+ });
229
+
230
+ // src/gif-utils.ts
231
+ var getSpecificRendition = ({ images, is_sticker: isSticker }, renditionLabel, isStill = false, useVideo = false) => {
232
+ if (!images || !renditionLabel)
233
+ return "";
234
+ isStill = isStill && !useVideo;
235
+ const rendition = images[`${renditionLabel}${isStill ? "_still" : ""}`];
236
+ if (rendition) {
237
+ if (isSticker || isStill) {
238
+ return rendition.url;
239
+ }
240
+ const webP = SUPPORTS_WEBP && rendition.webp;
241
+ return useVideo ? rendition.mp4 : webP || rendition.url;
242
+ }
243
+ return "";
244
+ };
245
+ var getBestVideo = (video, width, height) => {
246
+ let assets = video == null ? void 0 : video.assets;
247
+ if (assets) {
248
+ assets = __spreadValues({}, assets);
249
+ delete assets.source;
250
+ const filteredAssets = Object.values(assets).sort((a, b) => a.width - b.width);
251
+ return bestfit_default(filteredAssets, width, height);
252
+ }
253
+ };
254
+ var getRenditions = (type, images, video) => type === "video" && video && video.previews && !Object.keys(images).length ? video.previews : images;
255
+ var getBestRendition = (images, gifWidth, gifHeight, scaleUpMaxPixels) => {
256
+ const checkRenditions = pick(images, [
257
+ "original",
258
+ "fixed_width",
259
+ "fixed_height",
260
+ "fixed_width_small",
261
+ "fixed_height_small"
262
+ ]);
263
+ const testImages = Object.entries(checkRenditions).map(([renditionName, val]) => __spreadValues({
264
+ renditionName
265
+ }, val));
266
+ return bestfit_default(testImages, gifWidth, gifHeight, scaleUpMaxPixels);
267
+ };
268
+ var getBestRenditionUrl = ({ images, video, type }, gifWidth, gifHeight, options = { isStill: false, useVideo: false }) => {
269
+ if (!gifWidth || !gifHeight || !images)
270
+ return "";
271
+ const { useVideo, isStill, scaleUpMaxPixels } = options;
272
+ const renditions = getRenditions(type, images, video);
273
+ const { renditionName } = getBestRendition(renditions, gifWidth, gifHeight, scaleUpMaxPixels);
274
+ const key = `${renditionName}${isStill && !useVideo ? "_still" : ""}`;
275
+ const rendition = renditions[key];
276
+ const match = useVideo ? rendition.mp4 : SUPPORTS_WEBP && rendition.webp ? rendition.webp : rendition.url;
277
+ return match || "";
278
+ };
279
+ var getGifHeight = ({ images }, gifWidth) => {
280
+ const { fixed_width } = images;
281
+ if (fixed_width) {
282
+ const { width, height } = fixed_width;
283
+ const aspectRatio = width / height;
284
+ return Math.round(gifWidth / aspectRatio);
285
+ }
286
+ return 0;
287
+ };
288
+ var getGifWidth = ({ images }, gifHeight) => {
289
+ const { fixed_width } = images;
290
+ if (fixed_width) {
291
+ const { width, height } = fixed_width;
292
+ const aspectRatio = width / height;
293
+ return Math.round(gifHeight * aspectRatio);
294
+ }
295
+ return 0;
296
+ };
297
+ var getAltText = ({ alt_text, user, tags = [], is_sticker = false, title = "" }) => {
298
+ if (alt_text) {
299
+ return alt_text;
300
+ }
301
+ if (title) {
302
+ return title;
303
+ }
304
+ const username = user && user.username || "";
305
+ const filteredTags = take(without(tags, ["transparent"]), username ? 4 : 5);
306
+ return `${username ? `${username} ` : ``}${filteredTags.join(" ")} ${is_sticker ? "Sticker" : "GIF"}`;
307
+ };
308
+
309
+ // src/sdk-headers.ts
310
+ var gl = (typeof window !== "undefined" ? window : global) || {};
311
+ gl._GIPHY_SDK_HEADERS_ = gl._GIPHY_SDK_HEADERS_ || (gl.Headers ? new gl.Headers({
312
+ "X-GIPHY-SDK-PLATFORM": "web"
313
+ }) : void 0);
314
+ var getGiphySDKRequestHeaders = () => gl._GIPHY_SDK_HEADERS_;
315
+ var appendGiphySDKRequestHeader = (key, value) => {
316
+ var _a;
317
+ return (_a = getGiphySDKRequestHeaders()) == null ? void 0 : _a.set(key, value);
318
+ };
319
+ var appendGiphySDKRequestParam = (key, value) => {
320
+ var _a;
321
+ return (_a = getGiphySDKRequestHeaders()) == null ? void 0 : _a.set(key, value);
322
+ };
323
+
324
+ // src/tracking-pixel.ts
325
+ import DOMPurify from "dompurify";
326
+ var injectTrackingPixel = (tags = []) => {
327
+ tags.forEach((tag) => {
328
+ var _a;
329
+ const el = document.createElement("html");
330
+ tag = tag.replace("%%CACHEBUSTER%%", Date.now().toString());
331
+ el.innerHTML = DOMPurify.sanitize(tag);
332
+ const pixel = el.querySelector("img");
333
+ if (pixel) {
334
+ (_a = document == null ? void 0 : document.querySelector("head")) == null ? void 0 : _a.appendChild(pixel);
335
+ }
336
+ });
337
+ };
338
+ var tracking_pixel_default = injectTrackingPixel;
339
+ export {
340
+ LogLevel,
341
+ Logger,
342
+ appendGiphySDKRequestHeader,
343
+ appendGiphySDKRequestParam,
344
+ bestfit_default as bestfit,
345
+ checkIfWebP,
346
+ constructMoatData,
347
+ forEach,
348
+ getAltText,
349
+ getBestRendition,
350
+ getBestRenditionUrl,
351
+ getBestVideo,
352
+ get_client_rect_from_el_default as getClientRect,
353
+ getGifHeight,
354
+ getGifWidth,
355
+ getGiphySDKRequestHeaders,
356
+ get_pingback_id_default as getPingbackId,
357
+ getSpecificRendition,
358
+ tracking_pixel_default as injectTrackingPixel,
359
+ mapValues,
360
+ pick,
361
+ setRenditionScaleUpMaxPixels,
362
+ take,
363
+ without
364
+ };
package/package.json CHANGED
@@ -1,32 +1,32 @@
1
1
  {
2
2
  "scripts": {
3
- "clean": "rm -rf ./dist ./esm",
3
+ "lint": "run -T eslint . --ext .ts,.tsx",
4
+ "clean": "rm -rf ./dist",
4
5
  "dev": "tsc --watch",
5
- "build": "tsc && npm run build:esm",
6
- "build:esm": "tsc -p ./tsconfig-esm.json",
6
+ "build": "run -T tsup src/index.ts --format cjs,esm --dts && run -T publint",
7
7
  "prepublish": "npm run clean && npm run build",
8
8
  "test": "run -T jest --config ./jestconfig.js",
9
9
  "test:watch": "run -T jest --config ./jestconfig.js --watchAll"
10
10
  },
11
11
  "name": "@giphy/js-util",
12
- "version": "4.4.2",
13
- "main": "dist/index.js",
12
+ "version": "5.1.0-beta.0",
14
13
  "description": "Shared giphy js utils",
15
14
  "homepage": "https://github.com/Giphy/giphy-js/tree/master/packages/util",
15
+ "main": "dist/index.cjs",
16
16
  "types": "dist/index.d.ts",
17
- "module": "esm/index.js",
17
+ "module": "dist/index.js",
18
+ "type": "module",
18
19
  "sideEffects": false,
19
20
  "exports": {
20
21
  ".": {
21
22
  "types": "./dist/index.d.ts",
22
- "import": "./esm/index.js",
23
- "require": "./dist/index.js"
23
+ "import": "./dist/index.js",
24
+ "require": "./dist/index.cjs"
24
25
  },
25
26
  "./package.json": "./package.json"
26
27
  },
27
28
  "files": [
28
29
  "dist/",
29
- "esm/",
30
30
  "src/**/*"
31
31
  ],
32
32
  "license": "MIT",
@@ -34,8 +34,8 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "@giphy/js-types": "*",
38
- "dompurify": "^2.2.2",
37
+ "@giphy/js-types": "5.1.0-beta.0",
38
+ "dompurify": "3.1.0",
39
39
  "uuid": "^9.0.0"
40
40
  },
41
41
  "devDependencies": {
@@ -3,12 +3,7 @@ import { forEach, mapValues, pick, take, without } from '../collections'
3
3
  import getPingbackId from '../get-pingback-id'
4
4
  import { getAltText, getBestRenditionUrl, getGifHeight, getGifWidth, getSpecificRendition } from '../gif-utils'
5
5
 
6
- jest.mock('../webp-check')
7
-
8
6
  describe('response parsing', () => {
9
- afterEach(() => {
10
- require('../webp-check').__setWebP(false)
11
- })
12
7
  test('getGifHeight getGifWidth', () => {
13
8
  const gif = {
14
9
  images: {
@@ -73,9 +68,8 @@ describe('response parsing', () => {
73
68
  expect(getBestRenditionUrl(dummyGif as IGif, 10, 10)).toBe(fixedWidth.url)
74
69
  expect(getBestRenditionUrl(dummyGif as IGif, 10, 10, { isStill: true })).toBe(fixedWidthStill.url)
75
70
  expect(getBestRenditionUrl(dummyGif as IGif, 10, 10, { useVideo: true })).toBe(fixedWidth.mp4)
76
- require('../webp-check').__setWebP(true)
77
- expect(getBestRenditionUrl(dummyGif as IGif, 10, 10)).toBe(fixedWidth.webp)
78
- expect(getBestRenditionUrl(dummyGif as IGif, 10, 10, { isStill: true })).toBe(fixedWidthStill.webp)
71
+ expect(getBestRenditionUrl(dummyGif as IGif, 10, 10)).toBe(fixedWidth.url)
72
+ expect(getBestRenditionUrl(dummyGif as IGif, 10, 10, { isStill: true })).toBe(fixedWidthStill.url)
79
73
  })
80
74
 
81
75
  test('getSpecificRendition', () => {
@@ -104,8 +98,7 @@ describe('response parsing', () => {
104
98
  expect(getSpecificRendition(dummyGif as IGif, 'fixed_width', true)).toBe(fixedWidthStill.url)
105
99
  expect(getSpecificRendition(dummyGif as IGif, 'fixed_width', true, true)).toBe(fixedWidth.mp4)
106
100
  expect(getSpecificRendition(dummyGif as IGif, 'fixed_width_still', true, true)).toBe(fixedWidthStill.mp4)
107
- require('../webp-check').__setWebP(true)
108
- expect(getSpecificRendition(dummyGif as IGif, 'fixed_width')).toBe(fixedWidth.webp)
101
+ expect(getSpecificRendition(dummyGif as IGif, 'fixed_width')).toBe(fixedWidth.url)
109
102
  expect(getSpecificRendition(dummyGif as IGif, 'dsakfjslkj')).toBe('')
110
103
  expect(getSpecificRendition({} as IGif, 'fixed_width')).toBe('')
111
104
  })
@@ -0,0 +1,44 @@
1
+ type MoatData = {
2
+ moatClientLevel1: string
3
+ moatClientLevel2: string
4
+ moatClientLevel3: string
5
+ moatClientLevel4: string
6
+ moatClientSlicer1: string
7
+ moatClientSlicer2: string
8
+ zMoatPosition: string
9
+ zMoatSession?: string
10
+ }
11
+
12
+ type Tracker = {
13
+ vendor: string
14
+ verificationParameters: any
15
+ }
16
+
17
+ type TData = {
18
+ web?: Tracker[]
19
+ }
20
+
21
+ export const constructMoatData = ({ tdata }: { tdata: TData }): MoatData | undefined => {
22
+ const [moatTrackerData] = tdata?.web?.filter((tracker) => tracker.vendor === 'Moat') || []
23
+ if (moatTrackerData?.verificationParameters) {
24
+ const {
25
+ moatClientLevel1 = '_ADVERTISER_',
26
+ moatClientLevel2 = '_CAMPAIGN_',
27
+ moatClientLevel3 = '_LINE_ITEM_',
28
+ moatClientLevel4 = '_CREATIVE_',
29
+ moatClientSlicer1 = '_SITE_',
30
+ moatClientSlicer2 = '_PLACEMENT_',
31
+ zMoatPosition = '_POSITION_',
32
+ } = moatTrackerData.verificationParameters
33
+
34
+ return {
35
+ moatClientLevel1,
36
+ moatClientLevel2,
37
+ moatClientLevel3,
38
+ moatClientLevel4,
39
+ moatClientSlicer1,
40
+ moatClientSlicer2,
41
+ zMoatPosition,
42
+ }
43
+ }
44
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { default as bestfit, setRenditionScaleUpMaxPixels } from './bestfit'
2
2
  export * from './collections'
3
+ export * from './construct-moat-data'
3
4
  export { default as getClientRect } from './get-client-rect-from-el'
4
5
  export { default as getPingbackId } from './get-pingback-id'
5
6
  export {
@@ -13,4 +14,5 @@ export {
13
14
  } from './gif-utils'
14
15
  export * from './log'
15
16
  export * from './sdk-headers'
17
+ export { default as injectTrackingPixel } from './tracking-pixel'
16
18
  export { checkIfWebP } from './webp-check'
@@ -0,0 +1,15 @@
1
+ import DOMPurify from 'dompurify'
2
+
3
+ const injectTrackingPixel = (tags: string[] = []) => {
4
+ tags.forEach((tag) => {
5
+ const el = document.createElement('html')
6
+ tag = tag.replace('%%CACHEBUSTER%%', Date.now().toString())
7
+ el.innerHTML = DOMPurify.sanitize(tag)
8
+ const pixel = el.querySelector('img')
9
+ if (pixel) {
10
+ document?.querySelector('head')?.appendChild(pixel)
11
+ }
12
+ })
13
+ }
14
+
15
+ export default injectTrackingPixel
package/esm/bestfit.d.ts DELETED
@@ -1,18 +0,0 @@
1
- import { IRendition } from '@giphy/js-types';
2
- export declare const setRenditionScaleUpMaxPixels: (pixels: number) => void;
3
- /**
4
- * Finds image rendition that best fits a given container preferring images
5
- * ##### Note: all renditions are assumed to have the same aspect ratio
6
- *
7
- * When we have a portrait target and landscape gif, we choose a higher rendition to match
8
- * the height of the portrait target, otherwise it's blurry (same applies for landscape to portrait)
9
- *
10
- * @name bestfit
11
- * @function
12
- * @param {Array.<Object>} renditions available image renditions each having a width and height property
13
- * @param {Number} width
14
- * @param {Number} height
15
- * @param {Number} scaleUpMaxPixels the maximum pixels an asset should be scaled up
16
- */
17
- declare function bestfit(renditions: Array<IRendition>, width: number, height: number, scaleUpMaxPixels?: number): IRendition;
18
- export default bestfit;
package/esm/bestfit.js DELETED
@@ -1,57 +0,0 @@
1
- import { Logger } from './log';
2
- var closestArea = function (width, height, renditions) {
3
- var currentBest = Infinity;
4
- var result;
5
- // sort the renditions so we can avoid scaling up low resolutions
6
- renditions.forEach(function (rendition) {
7
- var widthPercentage = rendition.width / width;
8
- var heightPercentage = rendition.height / height;
9
- // a width percentage of 1 is exact, 2 is double, .5 half etc
10
- var areaPercentage = widthPercentage * heightPercentage;
11
- // img could be bigger or smaller
12
- var testBest = Math.abs(1 - areaPercentage); // the closer to 0 the better
13
- if (testBest < currentBest) {
14
- currentBest = testBest;
15
- result = rendition;
16
- }
17
- });
18
- return result;
19
- };
20
- var SCALE_UP_MAX_PIXELS = 50;
21
- export var setRenditionScaleUpMaxPixels = function (pixels) {
22
- Logger.debug("@giphy/js-util set rendition selection scale up max pixels to ".concat(pixels));
23
- SCALE_UP_MAX_PIXELS = pixels;
24
- };
25
- /**
26
- * Finds image rendition that best fits a given container preferring images
27
- * ##### Note: all renditions are assumed to have the same aspect ratio
28
- *
29
- * When we have a portrait target and landscape gif, we choose a higher rendition to match
30
- * the height of the portrait target, otherwise it's blurry (same applies for landscape to portrait)
31
- *
32
- * @name bestfit
33
- * @function
34
- * @param {Array.<Object>} renditions available image renditions each having a width and height property
35
- * @param {Number} width
36
- * @param {Number} height
37
- * @param {Number} scaleUpMaxPixels the maximum pixels an asset should be scaled up
38
- */
39
- function bestfit(renditions, width, height, scaleUpMaxPixels) {
40
- if (scaleUpMaxPixels === void 0) { scaleUpMaxPixels = SCALE_UP_MAX_PIXELS; }
41
- var largestRendition = renditions[0];
42
- // filter out renditions that are smaller than the target width and height by scaleUpMaxPixels value
43
- var testRenditions = renditions.filter(function (rendition) {
44
- if (rendition.width * rendition.height > largestRendition.width * largestRendition.height) {
45
- largestRendition = rendition;
46
- }
47
- return width - rendition.width <= scaleUpMaxPixels && height - rendition.height <= scaleUpMaxPixels;
48
- });
49
- // if all are too small, use the largest we have
50
- if (testRenditions.length === 0) {
51
- return largestRendition;
52
- }
53
- // find the closest area of the filtered renditions
54
- return closestArea(width, height, testRenditions);
55
- }
56
- export default bestfit;
57
- //# sourceMappingURL=bestfit.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"bestfit.js","sourceRoot":"","sources":["../src/bestfit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAA;AAE9B,IAAM,WAAW,GAAG,UAAC,KAAa,EAAE,MAAc,EAAE,UAAwB;IACxE,IAAI,WAAW,GAAG,QAAQ,CAAA;IAC1B,IAAI,MAAkB,CAAA;IACtB,iEAAiE;IACjE,UAAU,CAAC,OAAO,CAAC,UAAC,SAAqB;QACrC,IAAM,eAAe,GAAG,SAAS,CAAC,KAAK,GAAG,KAAK,CAAA;QAC/C,IAAM,gBAAgB,GAAG,SAAS,CAAC,MAAM,GAAG,MAAM,CAAA;QAClD,6DAA6D;QAC7D,IAAM,cAAc,GAAG,eAAe,GAAG,gBAAgB,CAAA;QACzD,iCAAiC;QACjC,IAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,cAAc,CAAC,CAAA,CAAC,6BAA6B;QAC3E,IAAI,QAAQ,GAAG,WAAW,EAAE;YACxB,WAAW,GAAG,QAAQ,CAAA;YACtB,MAAM,GAAG,SAAS,CAAA;SACrB;IACL,CAAC,CAAC,CAAA;IACF,OAAO,MAAO,CAAA;AAClB,CAAC,CAAA;AAED,IAAI,mBAAmB,GAAG,EAAE,CAAA;AAC5B,MAAM,CAAC,IAAM,4BAA4B,GAAG,UAAC,MAAc;IACvD,MAAM,CAAC,KAAK,CAAC,wEAAiE,MAAM,CAAE,CAAC,CAAA;IACvF,mBAAmB,GAAG,MAAM,CAAA;AAChC,CAAC,CAAA;AACD;;;;;;;;;;;;;GAaG;AACH,SAAS,OAAO,CACZ,UAA6B,EAC7B,KAAa,EACb,MAAc,EACd,gBAA8C;IAA9C,iCAAA,EAAA,sCAA8C;IAEzC,IAAA,gBAAgB,GAAI,UAAU,GAAd,CAAc;IACnC,oGAAoG;IACpG,IAAM,cAAc,GAAG,UAAU,CAAC,MAAM,CAAC,UAAA,SAAS;QAC9C,IAAI,SAAS,CAAC,KAAK,GAAG,SAAS,CAAC,MAAM,GAAG,gBAAgB,CAAC,KAAK,GAAG,gBAAgB,CAAC,MAAM,EAAE;YACvF,gBAAgB,GAAG,SAAS,CAAA;SAC/B;QACD,OAAO,KAAK,GAAG,SAAS,CAAC,KAAK,IAAI,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAAC,MAAM,IAAI,gBAAgB,CAAA;IACvG,CAAC,CAAC,CAAA;IACF,gDAAgD;IAChD,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC,EAAE;QAC7B,OAAO,gBAAgB,CAAA;KAC1B;IACD,mDAAmD;IACnD,OAAO,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,cAAc,CAAC,CAAA;AACrD,CAAC;AAED,eAAe,OAAO,CAAA"}
@@ -1,5 +0,0 @@
1
- export declare function mapValues(object: any, mapFn: (val: any, key: string) => any): any;
2
- export declare function forEach(object: any, mapFn: (val: any, key: any) => void): void;
3
- export declare function take<T>(arr: T[], count?: number): T[];
4
- export declare function without<T>(arr: T[], values: T[]): T[];
5
- export declare function pick<T extends object, U extends keyof T>(object: T, pick: Array<U>): Pick<T, U>;