@apify/utilities 1.2.13 → 2.1.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/index.js +1736 -22
- package/index.js.map +1 -0
- package/index.mjs +1662 -0
- package/index.mjs.map +1 -0
- package/package.json +15 -7
- package/exponential_backoff.js +0 -53
- package/health_checker.js +0 -110
- package/parse_jsonl_stream.js +0 -85
- package/streams_utilities.js +0 -30
- package/utilities.client.js +0 -395
- package/utilities.js +0 -419
- package/webhook_payload_template.js +0 -201
package/utilities.js
DELETED
|
@@ -1,419 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/*!
|
|
3
|
-
* This module contains various server utility and helper functions.
|
|
4
|
-
* Note that it automatically exports functions from utilities.client.js
|
|
5
|
-
*
|
|
6
|
-
* Author: Jan Curn (jan@apify.com)
|
|
7
|
-
* Copyright(c) 2015 Apify. All rights reserved.
|
|
8
|
-
*
|
|
9
|
-
*/
|
|
10
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
11
|
-
if (k2 === undefined) k2 = k;
|
|
12
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
13
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
14
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
15
|
-
}
|
|
16
|
-
Object.defineProperty(o, k2, desc);
|
|
17
|
-
}) : (function(o, m, k, k2) {
|
|
18
|
-
if (k2 === undefined) k2 = k;
|
|
19
|
-
o[k2] = m[k];
|
|
20
|
-
}));
|
|
21
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
22
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
23
|
-
}) : function(o, v) {
|
|
24
|
-
o["default"] = v;
|
|
25
|
-
});
|
|
26
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
27
|
-
if (mod && mod.__esModule) return mod;
|
|
28
|
-
var result = {};
|
|
29
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
30
|
-
__setModuleDefault(result, mod);
|
|
31
|
-
return result;
|
|
32
|
-
};
|
|
33
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
34
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
35
|
-
};
|
|
36
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
-
exports.timeoutPromise = exports.configureLogger = exports.promisifyServerListen = exports.checkParamPrototypeOrThrow = exports.sequentializePromises = exports.isForbiddenUsername = exports.weightedAverage = exports.leftpad = exports.escapeRegExp = exports.betterClearInterval = exports.betterSetInterval = exports.expressErrorHandler = exports.http404Route = exports.removeFromArray = exports.delayPromise = exports.parseDateFromJson = exports.getRandomInt = exports.deterministicUniqueId = exports.cryptoRandomObjectId = void 0;
|
|
38
|
-
const crypto_1 = __importDefault(require("crypto"));
|
|
39
|
-
const log_1 = __importStar(require("@apify/log"));
|
|
40
|
-
const consts_1 = require("@apify/consts");
|
|
41
|
-
/**
|
|
42
|
-
* Generates a random cryptographically strong string consisting of 17 alphanumeric characters.
|
|
43
|
-
* This string is similar to MongoDB ObjectIds generated by Meteor.
|
|
44
|
-
*/
|
|
45
|
-
function cryptoRandomObjectId(length = 17) {
|
|
46
|
-
const chars = 'abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
47
|
-
const bytes = crypto_1.default.randomBytes(length);
|
|
48
|
-
let str = '';
|
|
49
|
-
// eslint-disable-next-line
|
|
50
|
-
for (let i = bytes.length - 1; i >= 0; i--) {
|
|
51
|
-
str += chars[(bytes[i] | 0) % chars.length];
|
|
52
|
-
}
|
|
53
|
-
return str;
|
|
54
|
-
}
|
|
55
|
-
exports.cryptoRandomObjectId = cryptoRandomObjectId;
|
|
56
|
-
/**
|
|
57
|
-
* Generates unique, deterministic record ID from the provided key with given length (defaults to 17).
|
|
58
|
-
*/
|
|
59
|
-
function deterministicUniqueId(key, length = 17) {
|
|
60
|
-
return crypto_1.default
|
|
61
|
-
.createHash('sha256')
|
|
62
|
-
.update(key)
|
|
63
|
-
.digest('base64')
|
|
64
|
-
.replace(/(\+|\/|=)/g, 'x')
|
|
65
|
-
.substr(0, length);
|
|
66
|
-
}
|
|
67
|
-
exports.deterministicUniqueId = deterministicUniqueId;
|
|
68
|
-
/**
|
|
69
|
-
* Returns a random integer between 0 and max (excluded, unless it is also 0).
|
|
70
|
-
* @param {number} maxExcluded
|
|
71
|
-
* @returns {number}
|
|
72
|
-
*/
|
|
73
|
-
function getRandomInt(maxExcluded) {
|
|
74
|
-
maxExcluded = Math.floor(maxExcluded);
|
|
75
|
-
return Math.floor(Math.random() * maxExcluded);
|
|
76
|
-
}
|
|
77
|
-
exports.getRandomInt = getRandomInt;
|
|
78
|
-
/**
|
|
79
|
-
* If 'date' is a String, this function converts and returns it as a Date object.
|
|
80
|
-
* Otherwise, the function returns the original 'date' argument.
|
|
81
|
-
* This function is useful to convert dates transfered via JSON which doesn't natively support dates.
|
|
82
|
-
*/
|
|
83
|
-
function parseDateFromJson(date) {
|
|
84
|
-
if (typeof date === 'string') {
|
|
85
|
-
return new Date(Date.parse(date));
|
|
86
|
-
}
|
|
87
|
-
return date;
|
|
88
|
-
}
|
|
89
|
-
exports.parseDateFromJson = parseDateFromJson;
|
|
90
|
-
/**
|
|
91
|
-
* Returns a Promise object that will wait a specific number of milliseconds.
|
|
92
|
-
* @param {number} millis Time to wait. If the value is not larger than zero, the promise resolves immediately.
|
|
93
|
-
*/
|
|
94
|
-
function delayPromise(millis) {
|
|
95
|
-
return new Promise(((resolve) => {
|
|
96
|
-
if (millis > 0) {
|
|
97
|
-
setTimeout(() => resolve(), millis);
|
|
98
|
-
}
|
|
99
|
-
else {
|
|
100
|
-
resolve();
|
|
101
|
-
}
|
|
102
|
-
}));
|
|
103
|
-
}
|
|
104
|
-
exports.delayPromise = delayPromise;
|
|
105
|
-
/**
|
|
106
|
-
* Removes an element from an array.
|
|
107
|
-
*/
|
|
108
|
-
function removeFromArray(array, element) {
|
|
109
|
-
const index = array.indexOf(element);
|
|
110
|
-
if (index >= 0) {
|
|
111
|
-
array.splice(index, 1);
|
|
112
|
-
return true;
|
|
113
|
-
}
|
|
114
|
-
return false;
|
|
115
|
-
}
|
|
116
|
-
exports.removeFromArray = removeFromArray;
|
|
117
|
-
/**
|
|
118
|
-
* A default route for HTTP 404 error page for API endpoints.
|
|
119
|
-
*/
|
|
120
|
-
function http404Route(req, res) {
|
|
121
|
-
res.status(404);
|
|
122
|
-
res.send('Page not found');
|
|
123
|
-
}
|
|
124
|
-
exports.http404Route = http404Route;
|
|
125
|
-
/**
|
|
126
|
-
* Default error handler of Express API endpoints.
|
|
127
|
-
*/
|
|
128
|
-
function expressErrorHandler(err, req, res, next) {
|
|
129
|
-
log_1.default.warning('Client HTTP request failed', { url: req.url, errMsg: err.message });
|
|
130
|
-
if (res.headersSent) {
|
|
131
|
-
return next(err);
|
|
132
|
-
}
|
|
133
|
-
res.status(505);
|
|
134
|
-
res.send('Internal server error');
|
|
135
|
-
}
|
|
136
|
-
exports.expressErrorHandler = expressErrorHandler;
|
|
137
|
-
/**
|
|
138
|
-
* Similar to setInterval() but with two important differences:
|
|
139
|
-
* First, it assumes the function is asynchronous and only schedules its next invocation AFTER the asynchronous function finished.
|
|
140
|
-
* Second, it invokes the function immediately.
|
|
141
|
-
* @param func Asynchronous function to be periodically executed. It must take a single argument with a callback that
|
|
142
|
-
* the function must invoke after it's done.
|
|
143
|
-
* @param delay The number of milliseconds to wait to next invocation of the function.
|
|
144
|
-
* @returns Object that can be passed to betterClearInterval()
|
|
145
|
-
*/
|
|
146
|
-
function betterSetInterval(func, delay) {
|
|
147
|
-
let callback;
|
|
148
|
-
let timeoutId;
|
|
149
|
-
let isRunning = true;
|
|
150
|
-
const funcWrapper = function () {
|
|
151
|
-
func(callback);
|
|
152
|
-
};
|
|
153
|
-
callback = function () {
|
|
154
|
-
if (isRunning)
|
|
155
|
-
timeoutId = setTimeout(funcWrapper, delay);
|
|
156
|
-
};
|
|
157
|
-
funcWrapper();
|
|
158
|
-
return {
|
|
159
|
-
// eslint-disable-next-line no-underscore-dangle
|
|
160
|
-
_betterClearInterval() {
|
|
161
|
-
isRunning = false;
|
|
162
|
-
clearTimeout(timeoutId);
|
|
163
|
-
},
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
exports.betterSetInterval = betterSetInterval;
|
|
167
|
-
function betterClearInterval(intervalID) {
|
|
168
|
-
// eslint-disable-next-line no-underscore-dangle
|
|
169
|
-
if (intervalID && intervalID._betterClearInterval) {
|
|
170
|
-
try {
|
|
171
|
-
// eslint-disable-next-line no-underscore-dangle
|
|
172
|
-
intervalID._betterClearInterval();
|
|
173
|
-
}
|
|
174
|
-
catch (e) {
|
|
175
|
-
log_1.default.exception(e, '_betterClearInterval() threw an exception!?');
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
exports.betterClearInterval = betterClearInterval;
|
|
180
|
-
/**
|
|
181
|
-
* Escapes a string so that it can be used in regular expression (e.g. converts "myfile.*" to "myfile\\.\\*").
|
|
182
|
-
*/
|
|
183
|
-
function escapeRegExp(str) {
|
|
184
|
-
// code taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
|
|
185
|
-
return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
186
|
-
}
|
|
187
|
-
exports.escapeRegExp = escapeRegExp;
|
|
188
|
-
/**
|
|
189
|
-
* String left pad
|
|
190
|
-
*/
|
|
191
|
-
function leftpad(str, len, ch = ' ') {
|
|
192
|
-
// code inspired by https://www.theregister.co.uk/2016/03/23/npm_left_pad_chaos/
|
|
193
|
-
str = String(str);
|
|
194
|
-
let i = -1;
|
|
195
|
-
if (!ch && ch !== 0)
|
|
196
|
-
ch = ' ';
|
|
197
|
-
len -= str.length;
|
|
198
|
-
while (++i < len) {
|
|
199
|
-
str = ch + str;
|
|
200
|
-
}
|
|
201
|
-
return str;
|
|
202
|
-
}
|
|
203
|
-
exports.leftpad = leftpad;
|
|
204
|
-
/**
|
|
205
|
-
* Computes weighted average of 2 values.
|
|
206
|
-
*/
|
|
207
|
-
function weightedAverage(val1, weight1, val2, weight2) {
|
|
208
|
-
return (val1 * weight1 + val2 * weight2) / (weight1 + weight2);
|
|
209
|
-
}
|
|
210
|
-
exports.weightedAverage = weightedAverage;
|
|
211
|
-
/**
|
|
212
|
-
* List of forbidden usernames. Note that usernames can be used as apify.com/username,
|
|
213
|
-
* so we need to prohibit any username that might be part of our website or confusing in anyway.
|
|
214
|
-
*/
|
|
215
|
-
const FORBIDDEN_USERNAMES_REGEXPS = [
|
|
216
|
-
// Meteor app routes
|
|
217
|
-
'page-not-found', 'docs', 'terms-of-use', 'about', 'pricing', 'privacy-policy', 'customers',
|
|
218
|
-
'request-form', 'request-solution', 'release-notes', 'jobs', 'api-reference', 'video-tutorials',
|
|
219
|
-
'acts', 'key-value-stores', 'schedules', 'account', 'sign-up', 'sign-in-discourse', 'admin',
|
|
220
|
-
'documentation', 'change-password', 'enroll-account', 'forgot-password', 'reset-password',
|
|
221
|
-
'sign-in', 'verify-email', 'live-status', 'browser-info', 'webhooks', 'health-check', 'api',
|
|
222
|
-
'change-log', 'dashboard', 'community', 'crawlers', 'ext',
|
|
223
|
-
// Various strings
|
|
224
|
-
'admin', 'administration', 'crawler', 'act', 'library', 'lib', 'apifier', 'team',
|
|
225
|
-
'contact', 'doc', 'documentation', 'for-business', 'for-developers', 'developers', 'business',
|
|
226
|
-
'integrations', 'job', 'setting', 'settings', 'privacy', 'policy', 'assets', 'help',
|
|
227
|
-
'config', 'configuration', 'terms', 'hiring', 'hire', 'status', 'status-page', 'solutions',
|
|
228
|
-
'support', 'market', 'marketplace', 'download', 'downloads', 'username', 'users', 'user',
|
|
229
|
-
'login', 'logout', 'signin', 'sign', 'signup', 'sign-out', 'signout', 'plugins', 'plug-ins',
|
|
230
|
-
'reset', 'password', 'passwords', 'square', 'profile-photos', 'profiles', 'true', 'false',
|
|
231
|
-
'js', 'css', 'img', 'images', 'image', 'partials', 'fonts', 'font', 'dynamic_templates',
|
|
232
|
-
'app', 'schedules', 'community', 'storage', 'storages', 'account', 'node_modules', 'bower_components',
|
|
233
|
-
'video', 'knowledgebase', 'forum', 'customers', 'blog', 'health-check', 'health', 'anim',
|
|
234
|
-
'forum_topics.json', 'forum_categories.json', 'me', 'you', 'him', 'she', 'it', 'external',
|
|
235
|
-
'actor', 'crawler', 'scheduler', 'api', 'sdk', 'puppeteer', 'webdriver',
|
|
236
|
-
'selenium', '(selenium.*webdriver)', 'undefined', 'page-analyzer', 'wp-login.php',
|
|
237
|
-
'welcome.action', 'echo', 'proxy', 'super-proxy', 'gdpr', 'case-studies', 'use-cases', 'how-to',
|
|
238
|
-
'kb', 'cookies', 'cookie-policy', 'cookies-policy', 'powered-by', 'run', 'runs', 'actor', 'actors',
|
|
239
|
-
'act', 'acts', 'success-stories', 'roadmap', 'join-marketplace', 'presskit', 'press-kit', 'covid-19',
|
|
240
|
-
'covid', 'covid19', 'matfyz', 'ideas', 'public-actors', 'resources', 'partners', 'affiliate',
|
|
241
|
-
'industries', 'web-scraping', 'custom-solutions', 'solution-provider', 'alternatives', 'platform',
|
|
242
|
-
// Special files
|
|
243
|
-
'index', 'index\\.html', '(favicon\\.[a-z]+)', 'BingSiteAuth.xml', '(google.+\\.html)', 'robots\\.txt',
|
|
244
|
-
'(sitemap\\.[a-z]+)', '(apple-touch-icon.*)', 'security-whitepaper\\.pdf',
|
|
245
|
-
// All hidden files
|
|
246
|
-
'(\\..*)',
|
|
247
|
-
// File starting with xxx-
|
|
248
|
-
'(xxx-.*)',
|
|
249
|
-
// Strings not starting with letter or number
|
|
250
|
-
'([^0-9a-z].*)',
|
|
251
|
-
// Strings not ending with letter or number
|
|
252
|
-
'(.*[^0-9a-z])',
|
|
253
|
-
// Strings where there's more than one underscore, comma or dash in row
|
|
254
|
-
'(.*[_.\\-]{2}.*)',
|
|
255
|
-
// Reserved usernames from https://github.com/shouldbee/reserved-usernames/blob/master/reserved-usernames.json
|
|
256
|
-
'0', 'about', 'access', 'account', 'accounts', 'activate', 'activities', 'activity', 'ad', 'add',
|
|
257
|
-
'address', 'adm', 'admin', 'administration', 'administrator', 'ads', 'adult', 'advertising',
|
|
258
|
-
'affiliate', 'affiliates', 'ajax', 'all', 'alpha', 'analysis', 'analytics', 'android', 'anon',
|
|
259
|
-
'anonymous', 'api', 'app', 'apps', 'archive', 'archives', 'article', 'asct', 'asset', 'atom',
|
|
260
|
-
'auth', 'authentication', 'avatar', 'backup', 'balancer-manager', 'banner', 'banners', 'beta',
|
|
261
|
-
'billing', 'bin', 'blog', 'blogs', 'board', 'book', 'bookmark', 'bot', 'bots', 'bug', 'business',
|
|
262
|
-
'cache', 'cadastro', 'calendar', 'call', 'campaign', 'cancel', 'captcha', 'career', 'careers',
|
|
263
|
-
'cart', 'categories', 'category', 'cgi', 'cgi-bin', 'changelog', 'chat', 'check', 'checking',
|
|
264
|
-
'checkout', 'client', 'cliente', 'clients', 'code', 'codereview', 'comercial', 'comment',
|
|
265
|
-
'comments', 'communities', 'community', 'company', 'compare', 'compras', 'config', 'configuration',
|
|
266
|
-
'connect', 'contact', 'contact-us', 'contact_us', 'contactus', 'contest', 'contribute', 'corp',
|
|
267
|
-
'create', 'css', 'dashboard', 'data', 'db', 'default', 'delete', 'demo', 'design', 'designer',
|
|
268
|
-
'destroy', 'dev', 'devel', 'developer', 'developers', 'diagram', 'diary', 'dict', 'dictionary',
|
|
269
|
-
'die', 'dir', 'direct_messages', 'directory', 'dist', 'doc', 'docs', 'documentation', 'domain',
|
|
270
|
-
'download', 'downloads', 'ecommerce', 'edit', 'editor', 'edu', 'education', 'email', 'employment',
|
|
271
|
-
'empty', 'end', 'enterprise', 'entries', 'entry', 'error', 'errors', 'eval', 'event', 'exit',
|
|
272
|
-
'explore', 'facebook', 'faq', 'favorite', 'favorites', 'feature', 'features', 'feed', 'feedback',
|
|
273
|
-
'feeds', 'file', 'files', 'first', 'flash', 'fleet', 'fleets', 'flog', 'follow', 'followers',
|
|
274
|
-
'following', 'forgot', 'form', 'forum', 'forums', 'founder', 'free', 'friend', 'friends', 'ftp',
|
|
275
|
-
'gadget', 'gadgets', 'game', 'games', 'get', 'gift', 'gifts', 'gist', 'github', 'graph', 'group',
|
|
276
|
-
'groups', 'guest', 'guests', 'help', 'home', 'homepage', 'host', 'hosting', 'hostmaster',
|
|
277
|
-
'hostname', 'howto', 'hpg', 'html', 'http', 'httpd', 'https', 'i', 'iamges', 'icon', 'icons',
|
|
278
|
-
'id', 'idea', 'ideas', 'image', 'images', 'imap', 'img', 'index', 'indice', 'info', 'information',
|
|
279
|
-
'inquiry', 'instagram', 'intranet', 'invitations', 'invite', 'ipad', 'iphone', 'irc', 'is',
|
|
280
|
-
'issue', 'issues', 'it', 'item', 'items', 'java', 'javascript', 'job', 'jobs', 'join', 'js',
|
|
281
|
-
'json', 'jump', 'knowledgebase', 'language', 'languages', 'last', 'ldap-status', 'legal', 'license',
|
|
282
|
-
'link', 'links', 'linux', 'list', 'lists', 'log', 'log-in', 'log-out', 'log_in', 'log_out',
|
|
283
|
-
'login', 'logout', 'logs', 'm', 'mac', 'mail', 'mail1', 'mail2', 'mail3', 'mail4', 'mail5',
|
|
284
|
-
'mailer', 'mailing', 'maintenance', 'manager', 'manual', 'map', 'maps', 'marketing', 'master',
|
|
285
|
-
'me', 'media', 'member', 'members', 'message', 'messages', 'messenger', 'microblog', 'microblogs',
|
|
286
|
-
'mine', 'mis', 'mob', 'mobile', 'movie', 'movies', 'mp3', 'msg', 'msn', 'music', 'musicas', 'mx',
|
|
287
|
-
'my', 'mysql', 'name', 'named', 'nan', 'navi', 'navigation', 'net', 'network', 'new', 'news',
|
|
288
|
-
'newsletter', 'nick', 'nickname', 'notes', 'noticias', 'notification', 'notifications', 'notify',
|
|
289
|
-
'ns', 'ns1', 'ns10', 'ns2', 'ns3', 'ns4', 'ns5', 'ns6', 'ns7', 'ns8', 'ns9', 'null', 'oauth',
|
|
290
|
-
'oauth_clients', 'offer', 'offers', 'official', 'old', 'online', 'openid', 'operator', 'order',
|
|
291
|
-
'orders', 'organization', 'organizations', 'overview', 'owner', 'owners', 'page', 'pager',
|
|
292
|
-
'pages', 'panel', 'password', 'payment', 'perl', 'phone', 'photo', 'photoalbum', 'photos', 'php',
|
|
293
|
-
'phpmyadmin', 'phppgadmin', 'phpredisadmin', 'pic', 'pics', 'ping', 'plan', 'plans', 'plugin',
|
|
294
|
-
'plugins', 'policy', 'pop', 'pop3', 'popular', 'portal', 'post', 'postfix', 'postmaster', 'posts',
|
|
295
|
-
'pr', 'premium', 'press', 'price', 'pricing', 'privacy', 'privacy-policy', 'privacy_policy',
|
|
296
|
-
'privacypolicy', 'private', 'product', 'products', 'profile', 'project', 'projects', 'promo',
|
|
297
|
-
'pub', 'public', 'purpose', 'put', 'python', 'query', 'random', 'ranking', 'read', 'readme',
|
|
298
|
-
'recent', 'recruit', 'recruitment', 'register', 'registration', 'release', 'remove', 'replies',
|
|
299
|
-
'report', 'reports', 'repositories', 'repository', 'req', 'request', 'requests', 'reset', 'roc',
|
|
300
|
-
'root', 'rss', 'ruby', 'rule', 'sag', 'sale', 'sales', 'sample', 'samples', 'save', 'school',
|
|
301
|
-
'script', 'scripts', 'search', 'secure', 'security', 'self', 'send', 'server', 'server-info',
|
|
302
|
-
'server-status', 'service', 'services', 'session', 'sessions', 'setting', 'settings', 'setup',
|
|
303
|
-
'share', 'shop', 'show', 'sign-in', 'sign-up', 'sign_in', 'sign_up', 'signin', 'signout', 'signup',
|
|
304
|
-
'site', 'sitemap', 'sites', 'smartphone', 'smtp', 'soporte', 'source', 'spec', 'special', 'sql',
|
|
305
|
-
'src', 'ssh', 'ssl', 'ssladmin', 'ssladministrator', 'sslwebmaster', 'staff', 'stage', 'staging',
|
|
306
|
-
'start', 'stat', 'state', 'static', 'stats', 'status', 'store', 'stores', 'stories', 'style',
|
|
307
|
-
'styleguide', 'stylesheet', 'stylesheets', 'subdomain', 'subscribe', 'subscriptions', 'suporte',
|
|
308
|
-
'support', 'svn', 'swf', 'sys', 'sysadmin', 'sysadministrator', 'system', 'tablet', 'tablets',
|
|
309
|
-
'tag', 'talk', 'task', 'tasks', 'team', 'teams', 'tech', 'telnet', 'term', 'terms',
|
|
310
|
-
'terms-of-service', 'terms_of_service', 'termsofservice', 'test', 'test1', 'test2', 'test3',
|
|
311
|
-
'teste', 'testing', 'tests', 'theme', 'themes', 'thread', 'threads', 'tmp', 'todo', 'tool',
|
|
312
|
-
'tools', 'top', 'topic', 'topics', 'tos', 'tour', 'translations', 'trends', 'tutorial', 'tux',
|
|
313
|
-
'tv', 'twitter', 'undef', 'unfollow', 'unsubscribe', 'update', 'upload', 'uploads', 'url',
|
|
314
|
-
'usage', 'user', 'username', 'users', 'usuario', 'vendas', 'ver', 'version', 'video', 'videos',
|
|
315
|
-
'visitor', 'watch', 'weather', 'web', 'webhook', 'webhooks', 'webmail', 'webmaster', 'website',
|
|
316
|
-
'websites', 'welcome', 'widget', 'widgets', 'wiki', 'win', 'windows', 'word', 'work', 'works',
|
|
317
|
-
'workshop', 'ww', 'wws', 'www', 'www1', 'www2', 'www3', 'www4', 'www5', 'www6', 'www7', 'wwws',
|
|
318
|
-
'wwww', 'xfn', 'xml', 'xmpp', 'xpg', 'xxx', 'yaml', 'year', 'yml', 'you', 'yourdomain', 'yourname',
|
|
319
|
-
'yoursite', 'yourusername',
|
|
320
|
-
];
|
|
321
|
-
// Regex matching forbidden usernames.
|
|
322
|
-
const FORBIDDEN_REGEXP = new RegExp(`^(${consts_1.ANONYMOUS_USERNAME}|${FORBIDDEN_USERNAMES_REGEXPS.join('|')})$`, 'i');
|
|
323
|
-
/**
|
|
324
|
-
* Checks whether username is listed in FORBIDDEN_USERNAMES
|
|
325
|
-
* or matches any root route path.
|
|
326
|
-
*/
|
|
327
|
-
function isForbiddenUsername(username) {
|
|
328
|
-
return !!username.match(FORBIDDEN_REGEXP);
|
|
329
|
-
}
|
|
330
|
-
exports.isForbiddenUsername = isForbiddenUsername;
|
|
331
|
-
/**
|
|
332
|
-
* Executes array of promises in sequence and then returns array where Nth item is result of Nth promise.
|
|
333
|
-
*/
|
|
334
|
-
async function sequentializePromises(promises) {
|
|
335
|
-
if (!promises.length)
|
|
336
|
-
return [];
|
|
337
|
-
const results = [];
|
|
338
|
-
for (const promiseOrFunc of promises) {
|
|
339
|
-
const promise = promiseOrFunc instanceof Function ? promiseOrFunc() : promiseOrFunc;
|
|
340
|
-
results.push(await promise);
|
|
341
|
-
}
|
|
342
|
-
return results;
|
|
343
|
-
}
|
|
344
|
-
exports.sequentializePromises = sequentializePromises;
|
|
345
|
-
/**
|
|
346
|
-
* Helper function for validation if parameter is an instance of given prototype or multiple prototypes.
|
|
347
|
-
*/
|
|
348
|
-
function checkParamPrototypeOrThrow(paramVal, paramName, prototypes, prototypeName, isOptional = false) {
|
|
349
|
-
if (isOptional && (paramVal === undefined || paramVal === null))
|
|
350
|
-
return;
|
|
351
|
-
const hasCorrectPrototype = prototypes instanceof Array
|
|
352
|
-
? prototypes.some((prototype) => paramVal instanceof prototype)
|
|
353
|
-
: paramVal instanceof prototypes;
|
|
354
|
-
if (!hasCorrectPrototype)
|
|
355
|
-
throw new Error(`Parameter "${paramName}" must be an instance of ${prototypeName}`);
|
|
356
|
-
}
|
|
357
|
-
exports.checkParamPrototypeOrThrow = checkParamPrototypeOrThrow;
|
|
358
|
-
/**
|
|
359
|
-
* Starts listening at a port specified in the constructor.
|
|
360
|
-
* Unfortunately server.listen() is not a normal function that fails on error, so we need this trickery.
|
|
361
|
-
* Returns a function that calls `server.listen(port)` and resolves once server starts listening.
|
|
362
|
-
*
|
|
363
|
-
* Usage: `promisifyServerListen(server)(1234)`;
|
|
364
|
-
*/
|
|
365
|
-
function promisifyServerListen(server) {
|
|
366
|
-
return (port) => {
|
|
367
|
-
return new Promise((resolve, reject) => {
|
|
368
|
-
const onError = (err) => {
|
|
369
|
-
removeListeners();
|
|
370
|
-
reject(err);
|
|
371
|
-
};
|
|
372
|
-
const onListening = () => {
|
|
373
|
-
removeListeners();
|
|
374
|
-
resolve();
|
|
375
|
-
};
|
|
376
|
-
const removeListeners = () => {
|
|
377
|
-
server.removeListener('error', onError);
|
|
378
|
-
server.removeListener('listening', onListening);
|
|
379
|
-
};
|
|
380
|
-
server.on('error', onError);
|
|
381
|
-
server.on('listening', onListening);
|
|
382
|
-
server.listen(port);
|
|
383
|
-
});
|
|
384
|
-
};
|
|
385
|
-
}
|
|
386
|
-
exports.promisifyServerListen = promisifyServerListen;
|
|
387
|
-
function configureLogger(givenLog, isProduction) {
|
|
388
|
-
if (isProduction) {
|
|
389
|
-
givenLog.setOptions({
|
|
390
|
-
level: log_1.LogLevel.INFO,
|
|
391
|
-
logger: new log_1.LoggerJson(),
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
else {
|
|
395
|
-
givenLog.setOptions({ level: log_1.LogLevel.DEBUG });
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
exports.configureLogger = configureLogger;
|
|
399
|
-
/**
|
|
400
|
-
* Wraps given promise with timeout.
|
|
401
|
-
*/
|
|
402
|
-
function timeoutPromise(promise, timeoutMillis, errorMessage = 'Promise has timed-out') {
|
|
403
|
-
return new Promise((resolve, reject) => {
|
|
404
|
-
let timeout;
|
|
405
|
-
let hasFulfilled = false;
|
|
406
|
-
const callback = (err, result) => {
|
|
407
|
-
if (hasFulfilled)
|
|
408
|
-
return;
|
|
409
|
-
clearTimeout(timeout);
|
|
410
|
-
hasFulfilled = true;
|
|
411
|
-
if (err)
|
|
412
|
-
return reject(err);
|
|
413
|
-
resolve(result);
|
|
414
|
-
};
|
|
415
|
-
promise.then((result) => callback(null, result), callback);
|
|
416
|
-
timeout = setTimeout(() => callback(new Error(errorMessage)), timeoutMillis);
|
|
417
|
-
});
|
|
418
|
-
}
|
|
419
|
-
exports.timeoutPromise = timeoutPromise;
|
|
@@ -1,201 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/* eslint-disable max-classes-per-file */
|
|
3
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.WebhookPayloadTemplate = exports.InvalidVariableError = exports.InvalidJsonError = void 0;
|
|
5
|
-
const utilities_client_1 = require("./utilities.client");
|
|
6
|
-
class WebhookPayloadTemplateError extends Error {
|
|
7
|
-
constructor(message) {
|
|
8
|
-
super(message);
|
|
9
|
-
this.name = this.constructor.name;
|
|
10
|
-
if (typeof Error.captureStackTrace === 'function') {
|
|
11
|
-
Error.captureStackTrace(this, this.constructor);
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
class InvalidJsonError extends WebhookPayloadTemplateError {
|
|
16
|
-
constructor(originalError) {
|
|
17
|
-
super(originalError.message);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
exports.InvalidJsonError = InvalidJsonError;
|
|
21
|
-
class InvalidVariableError extends Error {
|
|
22
|
-
constructor(variable) {
|
|
23
|
-
super(`Invalid payload template variable: ${variable}`);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
exports.InvalidVariableError = InvalidVariableError;
|
|
27
|
-
/**
|
|
28
|
-
* WebhookPayloadTemplate enables creation and parsing of webhook payload template strings.
|
|
29
|
-
* Template strings are JSON that may include template variables enclosed in double
|
|
30
|
-
* curly brackets: `{{variable}}`. When the template is parsed, variables are replaced
|
|
31
|
-
* with values from a provided context.
|
|
32
|
-
*
|
|
33
|
-
* This is useful to create dynamic webhook payloads where a template is saved on webhook
|
|
34
|
-
* creation and then variables are dynamically added on webhook dispatch.
|
|
35
|
-
*
|
|
36
|
-
* **Example:**
|
|
37
|
-
* ```js
|
|
38
|
-
* const payloadTemplate = `{
|
|
39
|
-
* "id": "some-id",
|
|
40
|
-
* "createdAt": "2019-05-08T15:22:21.095Z",
|
|
41
|
-
* "dataToSend": {{data}}
|
|
42
|
-
* }`
|
|
43
|
-
*
|
|
44
|
-
* const data = {
|
|
45
|
-
* status: 200,
|
|
46
|
-
* body: 'hello world'
|
|
47
|
-
* }
|
|
48
|
-
*
|
|
49
|
-
* const payloadObject = WebhookPayloadTemplate.parse(payloadTemplate, null, { data })
|
|
50
|
-
* ```
|
|
51
|
-
*
|
|
52
|
-
* **Produces:**
|
|
53
|
-
* ```js
|
|
54
|
-
* {
|
|
55
|
-
* id: "some-id",
|
|
56
|
-
* createdAt: '2019-05-08T15:22:21.095Z',
|
|
57
|
-
* dataToSend: {
|
|
58
|
-
* status: 200,
|
|
59
|
-
* body: 'hello world'
|
|
60
|
-
* }
|
|
61
|
-
* }
|
|
62
|
-
* ```
|
|
63
|
-
* @hideconstructor
|
|
64
|
-
*/
|
|
65
|
-
class WebhookPayloadTemplate {
|
|
66
|
-
constructor(template, allowedVariables = null, context = {}) {
|
|
67
|
-
this.template = template;
|
|
68
|
-
this.allowedVariables = allowedVariables;
|
|
69
|
-
this.context = context;
|
|
70
|
-
this.payload = this.template;
|
|
71
|
-
this.replacedVariables = [];
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Parse existing webhook payload template string into an object, replacing
|
|
75
|
-
* template variables using the provided context.
|
|
76
|
-
*
|
|
77
|
-
* Parse also validates the template structure, so it can be used
|
|
78
|
-
* to check validity of the template JSON and usage of allowedVariables.
|
|
79
|
-
*/
|
|
80
|
-
static parse(payloadTemplate, allowedVariables = null, context = {}) {
|
|
81
|
-
const type = typeof payloadTemplate;
|
|
82
|
-
if (type !== 'string')
|
|
83
|
-
throw new Error(`Cannot parse a ${type} payload template.`);
|
|
84
|
-
const template = new WebhookPayloadTemplate(payloadTemplate, allowedVariables, context);
|
|
85
|
-
return template._parse(); // eslint-disable-line no-underscore-dangle
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Stringify an object into a webhook payload template.
|
|
89
|
-
* Values created using `getTemplateVariable('foo.bar')`
|
|
90
|
-
* will be stringified to `{{foo.bar}}` template variable.
|
|
91
|
-
*/
|
|
92
|
-
static stringify(objectTemplate, replacer, indent = 2) {
|
|
93
|
-
const type = typeof objectTemplate;
|
|
94
|
-
if (!objectTemplate || type !== 'object')
|
|
95
|
-
throw new Error(`Cannot stringify a ${type} payload template.`);
|
|
96
|
-
return (0, utilities_client_1.jsonStringifyExtended)(objectTemplate, replacer, indent);
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Produces an instance of a template variable that can be used
|
|
100
|
-
* in objects and will be stringified into `{{variableName}}` syntax.
|
|
101
|
-
*
|
|
102
|
-
* **Example:**
|
|
103
|
-
* ```js
|
|
104
|
-
* const resourceVariable = WebhookPayloadTemplate.getVariable('resource');
|
|
105
|
-
* const objectTemplate = {
|
|
106
|
-
* foo: 'foo',
|
|
107
|
-
* bar: ['bar'],
|
|
108
|
-
* res: resourceVariable,
|
|
109
|
-
* }
|
|
110
|
-
*
|
|
111
|
-
* const payloadTemplate = WebhookPayloadTemplate.stringify(objectTemplate);
|
|
112
|
-
* ```
|
|
113
|
-
*
|
|
114
|
-
* **Produces:**
|
|
115
|
-
* ```json
|
|
116
|
-
* {
|
|
117
|
-
* "foo": "foo",
|
|
118
|
-
* "bar": ["bar"],
|
|
119
|
-
* "res": {{resource}},
|
|
120
|
-
* }
|
|
121
|
-
* ```
|
|
122
|
-
*/
|
|
123
|
-
static getVariable(variableName) {
|
|
124
|
-
return new utilities_client_1.JsonVariable(variableName);
|
|
125
|
-
}
|
|
126
|
-
_parse() {
|
|
127
|
-
while (true) {
|
|
128
|
-
// eslint-disable-line no-constant-condition
|
|
129
|
-
try {
|
|
130
|
-
return JSON.parse(this.payload);
|
|
131
|
-
}
|
|
132
|
-
catch (err) {
|
|
133
|
-
const position = this._findPositionOfNextVariable();
|
|
134
|
-
if (position) {
|
|
135
|
-
this._replaceVariable(position);
|
|
136
|
-
}
|
|
137
|
-
else {
|
|
138
|
-
// When we catch an error from JSON.parse, but there's
|
|
139
|
-
// no variable, we must have an invalid JSON.
|
|
140
|
-
throw new InvalidJsonError(err);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
_findPositionOfNextVariable(startIndex = 0) {
|
|
146
|
-
const openBraceIndex = this.payload.indexOf('{{', startIndex);
|
|
147
|
-
const closeBraceIndex = this.payload.indexOf('}}', openBraceIndex) + 1;
|
|
148
|
-
const someVariableMaybeExists = (openBraceIndex > -1) && (closeBraceIndex > -1);
|
|
149
|
-
if (!someVariableMaybeExists)
|
|
150
|
-
return null;
|
|
151
|
-
const isInsideString = this._isVariableInsideString(openBraceIndex);
|
|
152
|
-
if (!isInsideString)
|
|
153
|
-
return { openBraceIndex, closeBraceIndex };
|
|
154
|
-
return this._findPositionOfNextVariable(openBraceIndex + 1);
|
|
155
|
-
}
|
|
156
|
-
_isVariableInsideString(openBraceIndex) {
|
|
157
|
-
const unescapedQuoteCount = this._countUnescapedDoubleQuotesUpToIndex(openBraceIndex);
|
|
158
|
-
return unescapedQuoteCount % 2 === 1;
|
|
159
|
-
}
|
|
160
|
-
_countUnescapedDoubleQuotesUpToIndex(index) {
|
|
161
|
-
const payloadSection = this.payload.substring(0, index);
|
|
162
|
-
let unescapedQuoteCount = 0;
|
|
163
|
-
for (let i = 0; i < payloadSection.length; i++) {
|
|
164
|
-
const char = payloadSection[i];
|
|
165
|
-
const prevChar = payloadSection[i - 1];
|
|
166
|
-
if (char === '"' && prevChar !== '\\') {
|
|
167
|
-
unescapedQuoteCount++;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
return unescapedQuoteCount;
|
|
171
|
-
}
|
|
172
|
-
_replaceVariable({ openBraceIndex, closeBraceIndex }) {
|
|
173
|
-
const variableName = this.payload.substring(openBraceIndex + 2, closeBraceIndex - 1);
|
|
174
|
-
this._validateVariableName(variableName);
|
|
175
|
-
const replacement = this._getVariableReplacement(variableName);
|
|
176
|
-
this.replacedVariables.push({ variableName, replacement });
|
|
177
|
-
this.payload = this.payload.replace(`{{${variableName}}}`, replacement);
|
|
178
|
-
}
|
|
179
|
-
_validateVariableName(variableName) {
|
|
180
|
-
if (this.allowedVariables === null)
|
|
181
|
-
return;
|
|
182
|
-
const [variable] = variableName.split('.');
|
|
183
|
-
// Properties of the variable are not validated on purpose
|
|
184
|
-
// as they will later be set to null if not found.
|
|
185
|
-
// This serves to enable dynamic variable structures.
|
|
186
|
-
const isVariableValid = this.allowedVariables.has(variable);
|
|
187
|
-
if (!isVariableValid)
|
|
188
|
-
throw new InvalidVariableError(variableName);
|
|
189
|
-
}
|
|
190
|
-
_getVariableReplacement(variableName) {
|
|
191
|
-
const [variable, ...properties] = variableName.split('.');
|
|
192
|
-
const context = this.context[variable];
|
|
193
|
-
const replacement = properties.reduce((ctx, prop) => {
|
|
194
|
-
if (!ctx || typeof ctx !== 'object')
|
|
195
|
-
return null;
|
|
196
|
-
return ctx[prop];
|
|
197
|
-
}, context);
|
|
198
|
-
return replacement ? JSON.stringify(replacement) : null;
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
exports.WebhookPayloadTemplate = WebhookPayloadTemplate;
|