@apify/utilities 1.2.14 → 2.0.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.
@@ -1,395 +0,0 @@
1
- "use strict";
2
- /*!
3
- * This module contains various client-side utility and helper functions.
4
- *
5
- * Author: Jan Curn (jan@apify.com)
6
- * Copyright(c) 2016 Apify. All rights reserved.
7
- *
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.isUrlRelative = exports.splitFullName = exports.jsonStringifyExtended = exports.JsonVariable = exports.isBadForMongo = exports.unescapeFromBson = exports.escapeForBson = exports.traverseObject = exports.unescapePropertyName = exports.escapePropertyName = exports.buildOrVersionNumberIntToStr = exports.markedDecreaseHeadsLevel = exports.markedSetNofollowLinks = exports.normalizeUrl = exports.parseUrl = exports.getOrdinalSuffix = exports.truncate = exports.dateToString = exports.isBuffer = exports.isNullOrUndefined = void 0;
11
- const consts_1 = require("@apify/consts");
12
- /**
13
- * Returns true if object equals null or undefined, otherwise returns false.
14
- */
15
- function isNullOrUndefined(obj) {
16
- return obj == null;
17
- }
18
- exports.isNullOrUndefined = isNullOrUndefined;
19
- function isBuffer(obj) {
20
- return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
21
- }
22
- exports.isBuffer = isBuffer;
23
- /**
24
- * Converts Date object to ISO string.
25
- */
26
- function dateToString(date, middleT) {
27
- if (!(date instanceof Date)) {
28
- return '';
29
- }
30
- const year = date.getFullYear();
31
- const month = date.getMonth() + 1; // January is 0, February is 1, and so on.
32
- const day = date.getDate();
33
- const hours = date.getHours();
34
- const minutes = date.getMinutes();
35
- const seconds = date.getSeconds();
36
- const millis = date.getMilliseconds();
37
- const pad = (num) => (num < 10 ? `0${num}` : num);
38
- const datePart = `${year}-${pad(month)}-${pad(day)}`;
39
- // eslint-disable-next-line no-nested-ternary
40
- const millisPart = millis < 10 ? `00${millis}` : (millis < 100 ? `0${millis}` : millis);
41
- const timePart = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}.${millisPart}`;
42
- return `${datePart}${middleT ? 'T' : ' '}${timePart}`;
43
- }
44
- exports.dateToString = dateToString;
45
- /**
46
- * Ensures a string is shorter than a specified number of character, and truncates it if not,
47
- * appending a specific suffix to it.
48
- * @param str
49
- * @param maxLength
50
- * @param [suffix] Suffix to be appended to truncated string. Defaults to "...[truncated]".
51
- */
52
- function truncate(str, maxLength, suffix = '...[truncated]') {
53
- maxLength = Math.floor(maxLength);
54
- // TODO: we should just ignore rest of the suffix...
55
- if (suffix.length > maxLength) {
56
- throw new Error('suffix string cannot be longer than maxLength');
57
- }
58
- if (typeof str === 'string' && str.length > maxLength) {
59
- str = str.substr(0, maxLength - suffix.length) + suffix;
60
- }
61
- return str;
62
- }
63
- exports.truncate = truncate;
64
- /**
65
- * Gets ordinal suffix for a number (e.g. "nd" for 2).
66
- */
67
- function getOrdinalSuffix(num) {
68
- // code from https://ecommerce.shopify.com/c/ecommerce-design/t/ordinal-number-in-javascript-1st-2nd-3rd-4th-29259
69
- const s = ['th', 'st', 'nd', 'rd'];
70
- const v = num % 100;
71
- return s[(v - 20) % 10] || s[v] || s[0];
72
- }
73
- exports.getOrdinalSuffix = getOrdinalSuffix;
74
- function parseUrl(str) {
75
- if (typeof str !== 'string')
76
- return {};
77
- const o = {
78
- strictMode: false,
79
- key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port',
80
- 'relative', 'path', 'directory', 'file', 'query', 'fragment'],
81
- q: {
82
- name: 'queryKey',
83
- parser: /(?:^|&)([^&=]*)=?([^&]*)/g,
84
- },
85
- parser: {
86
- strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
87
- loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/, // eslint-disable-line max-len,no-useless-escape
88
- },
89
- };
90
- // eslint-disable-next-line @typescript-eslint/no-shadow
91
- const m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str);
92
- const uri = {};
93
- let i = o.key.length;
94
- while (i--)
95
- uri[o.key[i]] = m[i] || '';
96
- uri[o.q.name] = {};
97
- uri[o.key[12]].replace(o.q.parser, ($0, $1, $2) => {
98
- if ($1)
99
- uri[o.q.name][$1] = $2;
100
- });
101
- // our extension - parse fragment using a query string format (i.e. "#key1=val1&key2=val2")
102
- // this format is used by many websites
103
- uri.fragmentKey = {};
104
- if (uri.fragment) {
105
- // casting as any, as the usage seems invalid, replacer should always return something (but keeping as is to mitigate unwanted BCs)
106
- uri.fragment.replace(o.q.parser, (($0, $1, $2) => {
107
- if ($1)
108
- uri.fragmentKey[$1] = $2;
109
- }));
110
- }
111
- return uri;
112
- }
113
- exports.parseUrl = parseUrl;
114
- function normalizeUrl(url, keepFragment) {
115
- if (typeof url !== 'string' || !url.length) {
116
- return null;
117
- }
118
- const urlObj = parseUrl(url.trim());
119
- if (!urlObj.protocol || !urlObj.host) {
120
- return null;
121
- }
122
- const path = urlObj.path.replace(/\/$/, '');
123
- const params = (urlObj.query
124
- ? urlObj.query
125
- .split('&')
126
- .filter((param) => {
127
- return !/^utm_/.test(param);
128
- })
129
- .sort()
130
- : []);
131
- return `${urlObj.protocol.trim().toLowerCase()}://${urlObj.host.trim().toLowerCase()}${path.trim()}${params.length ? `?${params.join('&').trim()}` : ''}${keepFragment && urlObj.fragment ? `#${urlObj.fragment.trim()}` : ''}`;
132
- }
133
- exports.normalizeUrl = normalizeUrl;
134
- // Helper function for markdown rendered marked
135
- // Renders links outside apify.com in readme with rel="noopener noreferrer nofollow" and target="_blank" attributes
136
- function markedSetNofollowLinks(href, title, text) {
137
- let urlParsed;
138
- try {
139
- urlParsed = new URL(href);
140
- }
141
- catch (e) {
142
- // Probably invalid url, go on
143
- }
144
- const isApifyLink = (urlParsed && /(\.|^)apify\.com$/i.test(urlParsed.hostname));
145
- return (isApifyLink)
146
- ? `<a href="${href}">${title || text}</a>`
147
- : `<a rel="noopener noreferrer nofollow" target="_blank" href="${href}">${title || text}</a>`;
148
- }
149
- exports.markedSetNofollowLinks = markedSetNofollowLinks;
150
- // Helper function for markdown rendered marked
151
- // Decreases level of all headings by one, h1 -> h2
152
- function markedDecreaseHeadsLevel(text, level) {
153
- level += 1;
154
- return `<h${level}>${text}</h${level}>`;
155
- }
156
- exports.markedDecreaseHeadsLevel = markedDecreaseHeadsLevel;
157
- /**
158
- * Converts integer version number previously generated by buildNumberToInt() or versionNumberToInt()
159
- * to string in a form 'MAJOR.MINOR' or 'MAJOR.MINOR.BUILD' in case build number is non-zero.
160
- */
161
- function buildOrVersionNumberIntToStr(int) {
162
- if (typeof int !== 'number' || !(int >= 0))
163
- return null;
164
- const major = Math.floor(int / consts_1.VERSION_INT_MAJOR_BASE);
165
- const remainder = int % consts_1.VERSION_INT_MAJOR_BASE;
166
- const minor = Math.floor(remainder / consts_1.VERSION_INT_MINOR_BASE);
167
- const build = remainder % consts_1.VERSION_INT_MINOR_BASE;
168
- let str = `${major}.${minor}`;
169
- if (build > 0)
170
- str += `.${build}`;
171
- return str;
172
- }
173
- exports.buildOrVersionNumberIntToStr = buildOrVersionNumberIntToStr;
174
- // escaped variants for various strings
175
- const ESCAPE_DOT = '\uFF0E'; // "."
176
- const ESCAPE_DOLLAR = '\uFF04'; // "$"
177
- const ESCAPE_TO_BSON = '\uFF54\uFF4F\uFF22\uFF33\uFF2F\uFF2E'; // "toBSON"
178
- const ESCAPE_TO_STRING = '\uFF54\uFF4F\uFF33\uFF54\uFF52\uFF49\uFF4E\uFF47'; // "toString"
179
- const ESCAPE_BSON_TYPE = '\uFF3F\uFF42\uFF53\uFF4F\uFF4E\uFF54\uFF59\uFF50\uFF45'; // "_bsontype"
180
- const ESCAPE_NULL = ''; // "\0" (null chars are removed completely, they won't be recovered)
181
- const REGEXP_IS_ESCAPED = new RegExp(`(${ESCAPE_DOT}|^${ESCAPE_DOLLAR}|^${ESCAPE_TO_BSON}$|^${ESCAPE_BSON_TYPE}|^${ESCAPE_TO_STRING}$)`);
182
- const REGEXP_DOT = new RegExp(ESCAPE_DOT, 'g');
183
- const REGEXP_DOLLAR = new RegExp(`^${ESCAPE_DOLLAR}`);
184
- const REGEXP_TO_BSON = new RegExp(`^${ESCAPE_TO_BSON}$`);
185
- const REGEXP_TO_STRING = new RegExp(`^${ESCAPE_TO_STRING}$`);
186
- const REGEXP_BSON_TYPE = new RegExp(`^${ESCAPE_BSON_TYPE}$`);
187
- /**
188
- * If a property name is invalid for MongoDB or BSON, the function transforms
189
- * it to a valid form, which can be (most of the time) reversed back using unescapePropertyName().
190
- * For a detailed list of transformations, see escapeForBson().
191
- * @private
192
- */
193
- function escapePropertyName(name) {
194
- // From MongoDB docs:
195
- // "Field names cannot contain dots (.) or null ("\0") characters, and they must not start with
196
- // a dollar sign (i.e. $). See faq-dollar-sign-escaping for an alternate approach."
197
- // Moreover, the name cannot be "toBSON" and "_bsontype" because they have a special meaning in BSON serialization.
198
- // Other special BSON properties like $id and $db are covered thanks to $ escape.
199
- // 2021-06-25: The `toString` string was added as a property to escape because
200
- // it generates issues due to a bug in mongo bson-ext package https://jira.mongodb.org/browse/NODE-3375.
201
- // pre-test to improve performance
202
- if (/(\.|^\$|^toBSON$|^_bsontype$|^toString$|\0)/.test(name)) {
203
- name = name.replace(/\./g, ESCAPE_DOT);
204
- name = name.replace(/^\$/, ESCAPE_DOLLAR);
205
- name = name.replace(/^toBSON$/, ESCAPE_TO_BSON);
206
- name = name.replace(/^toString$/, ESCAPE_TO_STRING);
207
- name = name.replace(/^_bsontype$/, ESCAPE_BSON_TYPE);
208
- name = name.replace(/\0/g, ESCAPE_NULL);
209
- }
210
- return name;
211
- }
212
- exports.escapePropertyName = escapePropertyName;
213
- /**
214
- * Reverses a string transformed using escapePropertyName() back to its original form.
215
- * Note that the reverse transformation might not be 100% correct for certain unlikely-to-occur strings
216
- * (e.g. string contain null chars).
217
- * @private
218
- */
219
- function unescapePropertyName(name) {
220
- // pre-test to improve performance
221
- if (REGEXP_IS_ESCAPED.test(name)) {
222
- name = name.replace(REGEXP_DOT, '.');
223
- name = name.replace(REGEXP_DOLLAR, '$');
224
- name = name.replace(REGEXP_TO_BSON, 'toBSON');
225
- name = name.replace(REGEXP_TO_STRING, 'toString');
226
- name = name.replace(REGEXP_BSON_TYPE, '_bsontype');
227
- }
228
- return name;
229
- }
230
- exports.unescapePropertyName = unescapePropertyName;
231
- /**
232
- * Traverses an object, creates a deep clone if requested and transforms object keys and values using a provided function.
233
- * The `traverseObject` is recursive, hence if the input object has circular references, the function will run into
234
- * and infinite recursion and crash the Node.js process.
235
- * @param obj Object to traverse, it must not contain circular references!
236
- * @param clone If true, object is not modified but cloned.
237
- * @param transformFunc Function used to transform the property names na value.
238
- * It has the following signature: `(key, value) => [key, value]`.
239
- * Beware that the transformed value is only set if it !== old value.
240
- * @returns {*}
241
- * @private
242
- */
243
- function traverseObject(obj, clone, transformFunc) {
244
- // Primitive types don't need to be cloned or further traversed.
245
- // Buffer needs to be skipped otherwise this will iterate over the whole buffer which kills the event loop.
246
- if (obj === null
247
- || typeof obj !== 'object'
248
- || Object.prototype.toString.call(obj) === '[object Date]'
249
- || isBuffer(obj))
250
- return obj;
251
- let result;
252
- if (Array.isArray(obj)) {
253
- // obj is an array, keys are numbers and never need to be escaped
254
- result = clone ? new Array(obj.length) : obj;
255
- for (let i = 0; i < obj.length; i++) {
256
- const val = traverseObject(obj[i], clone, transformFunc);
257
- if (clone)
258
- result[i] = val;
259
- }
260
- return result;
261
- }
262
- // obj is an object, all keys need to be checked
263
- result = clone ? {} : obj;
264
- for (const key in obj) { // eslint-disable-line no-restricted-syntax, guard-for-in
265
- const val = traverseObject(obj[key], clone, transformFunc);
266
- const [transformedKey, transformedVal] = transformFunc(key, val);
267
- if (key === transformedKey) {
268
- // For better efficiency, skip setting the key-value if not cloning and nothing changed
269
- if (clone || val !== transformedVal)
270
- result[key] = transformedVal;
271
- }
272
- else {
273
- // Key has been renamed
274
- result[transformedKey] = transformedVal;
275
- if (!clone)
276
- delete obj[key];
277
- }
278
- }
279
- return result;
280
- }
281
- exports.traverseObject = traverseObject;
282
- /**
283
- * Transforms an object so that it can be stored to MongoDB or serialized to BSON.
284
- * It does so by transforming prohibited property names (e.g. names starting with "$",
285
- * containing "." or null char, equal to "toBSON" or "_bsontype") to equivalent full-width Unicode chars
286
- * which are normally allowed. To revert this transformation, use unescapeFromBson().
287
- * @param obj Object to be transformed. It must not contain circular references or any complex types (e.g. Maps, Promises etc.)!
288
- * @param clone If true, the function transforms a deep clone of the object rather than the original object.
289
- * @returns {*} Transformed object
290
- */
291
- function escapeForBson(obj, clone = false) {
292
- return traverseObject(obj, clone, (key, value) => [escapePropertyName(key), value]);
293
- }
294
- exports.escapeForBson = escapeForBson;
295
- /**
296
- * Reverts a transformation of object property names performed by escapeForBson().
297
- * Note that the reverse transformation might not be 100% equal to the original object
298
- * for certain unlikely-to-occur property name (e.g. one contain null chars or full-width Unicode chars).
299
- * @param obj Object to be transformed. It must not contain circular references or any complex types (e.g. Maps, Promises etc.)!
300
- * @param clone If true, the function transforms a deep clone of the object rather than the original object.
301
- * @returns {*} Transformed object.
302
- */
303
- function unescapeFromBson(obj, clone = false) {
304
- return traverseObject(obj, clone, (key, value) => [unescapePropertyName(key), value]);
305
- }
306
- exports.unescapeFromBson = unescapeFromBson;
307
- /**
308
- * Determines whether an object contains property names that cannot be stored to MongoDB.
309
- * See escapeForBson() for more details.
310
- * Note that this function only works with objects that are serializable to JSON!
311
- * @param obj Object to be checked. It must not contain circular references or any complex types (e.g. Maps, Promises etc.)!
312
- * @returns {boolean} Returns true if object is invalid, otherwise it returns false.
313
- */
314
- function isBadForMongo(obj) {
315
- let isBad = false;
316
- try {
317
- traverseObject(obj, false, (key, value) => {
318
- const escapedKey = escapePropertyName(key);
319
- if (key !== escapedKey) {
320
- isBad = true;
321
- throw new Error();
322
- }
323
- return [key, value];
324
- });
325
- }
326
- catch (e) {
327
- if (!isBad)
328
- throw e;
329
- }
330
- return isBad;
331
- }
332
- exports.isBadForMongo = isBadForMongo;
333
- class JsonVariable {
334
- constructor(name) {
335
- this.name = name;
336
- }
337
- getToken() {
338
- return `{{${this.name}}}`;
339
- }
340
- }
341
- exports.JsonVariable = JsonVariable;
342
- /**
343
- * Stringifies provided value to JSON with a difference that supports functions that
344
- * are stringified using .toString() method.
345
- *
346
- * In addition to that supports instances of JsonVariable('my.token') that are replaced
347
- * with a {{my.token}}.
348
- */
349
- function jsonStringifyExtended(value, replacer, space = 0) {
350
- if (replacer && !(replacer instanceof Function))
351
- throw new Error('Parameter "replacer" of jsonStringifyExtended() must be a function!');
352
- const replacements = {};
353
- const extendedReplacer = (key, val) => {
354
- val = replacer ? replacer(key, val) : val;
355
- if (val instanceof Function)
356
- return val.toString();
357
- if (val instanceof JsonVariable) {
358
- const randomToken = `<<<REPLACEMENT_TOKEN::${Math.random()}>>>`;
359
- replacements[randomToken] = val.getToken();
360
- return randomToken;
361
- }
362
- return val;
363
- };
364
- let stringifiedValue = JSON.stringify(value, extendedReplacer, space);
365
- Object.entries(replacements).forEach(([replacementToken, replacementValue]) => {
366
- stringifiedValue = stringifiedValue.replace(`"${replacementToken}"`, replacementValue);
367
- });
368
- return stringifiedValue;
369
- }
370
- exports.jsonStringifyExtended = jsonStringifyExtended;
371
- /**
372
- * Splits a full name into the first name and last name, trimming all internal and external spaces.
373
- * Returns an array with two elements or null if splitting is not possible.
374
- */
375
- function splitFullName(fullName) {
376
- if (typeof fullName !== 'string')
377
- return [null, null];
378
- const names = (fullName || '').trim().split(' ');
379
- const nonEmptyNames = names.filter((val) => val);
380
- if (nonEmptyNames.length === 0) {
381
- return [null, null];
382
- }
383
- if (nonEmptyNames.length === 1) {
384
- return [null, nonEmptyNames[0]];
385
- }
386
- return [names[0], nonEmptyNames.slice(1).join(' ')];
387
- }
388
- exports.splitFullName = splitFullName;
389
- /**
390
- * Perform a Regex test on a given URL to see if it is relative.
391
- */
392
- function isUrlRelative(url) {
393
- return consts_1.RELATIVE_URL_REGEX.test(url);
394
- }
395
- exports.isUrlRelative = isUrlRelative;