-
Notifications
You must be signed in to change notification settings - Fork 776
/
Copy pathutils.js
242 lines (206 loc) · 6.71 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
'use strict';
var Buffer = require('safe-buffer').Buffer;
var EventEmitter = require('events').EventEmitter;
var qs = require('qs');
var crypto = require('crypto');
var hasOwn = {}.hasOwnProperty;
var isPlainObject = require('lodash.isplainobject');
var OPTIONS_KEYS = ['api_key', 'idempotency_key', 'stripe_account', 'stripe_version'];
var utils = module.exports = {
isAuthKey: function(key) {
return typeof key == 'string' && /^(?:[a-z]{2}_)?[A-z0-9]{32}$/.test(key);
},
isOptionsHash: function(o) {
return isPlainObject(o) && OPTIONS_KEYS.some(function(key) {
return hasOwn.call(o, key);
});
},
/**
* Stringifies an Object, accommodating nested objects
* (forming the conventional key 'parent[child]=value')
*/
stringifyRequestData: function(data) {
return qs.stringify(data, {serializeDate: function (d) { return Math.floor(d.getTime() / 1000); }})
// Don't use strict form encoding by changing the square bracket control
// characters back to their literals. This is fine by the server, and
// makes these parameter strings easier to read.
.replace(/%5B/g, '[').replace(/%5D/g, ']');
},
/**
* Outputs a new function with interpolated object property values.
* Use like so:
* var fn = makeURLInterpolator('some/url/{param1}/{param2}');
* fn({ param1: 123, param2: 456 }); // => 'some/url/123/456'
*/
makeURLInterpolator: (function() {
var rc = {
'\n': '\\n', '\"': '\\\"',
'\u2028': '\\u2028', '\u2029': '\\u2029',
};
return function makeURLInterpolator(str) {
var cleanString = str.replace(/["\n\r\u2028\u2029]/g, function($0) {
return rc[$0];
});
return function(outputs) {
return cleanString.replace(/\{([\s\S]+?)\}/g, function($0, $1) {
return encodeURIComponent(outputs[$1] || '');
});
};
};
}()),
/**
* Return the data argument from a list of arguments
*/
getDataFromArgs: function(args) {
if (args.length < 1 || !isPlainObject(args[0])) {
return {};
}
if (!utils.isOptionsHash(args[0])) {
return args.shift();
}
var argKeys = Object.keys(args[0]);
var optionKeysInArgs = argKeys.filter(function(key) {
return OPTIONS_KEYS.indexOf(key) > -1;
});
// In some cases options may be the provided as the first argument.
// Here we're detecting a case where there are two distinct arguments
// (the first being args and the second options) and with known
// option keys in the first so that we can warn the user about it.
if (optionKeysInArgs.length > 0 && optionKeysInArgs.length !== argKeys.length) {
emitWarning(
'Options found in arguments (' + optionKeysInArgs.join(', ') + '). Did you mean to pass an options ' +
'object? See https://github.com/stripe/stripe-node/wiki/Passing-Options.'
);
}
return {};
},
/**
* Return the options hash from a list of arguments
*/
getOptionsFromArgs: function(args) {
var opts = {
auth: null,
headers: {},
};
if (args.length > 0) {
var arg = args[args.length - 1];
if (utils.isAuthKey(arg)) {
opts.auth = args.pop();
} else if (utils.isOptionsHash(arg)) {
var params = args.pop();
var extraKeys = Object.keys(params).filter(function(key) {
return OPTIONS_KEYS.indexOf(key) == -1;
});
if (extraKeys.length) {
emitWarning('Invalid options found (' + extraKeys.join(', ') + '); ignoring.');
}
if (params.api_key) {
opts.auth = params.api_key;
}
if (params.idempotency_key) {
opts.headers['Idempotency-Key'] = params.idempotency_key;
}
if (params.stripe_account) {
opts.headers['Stripe-Account'] = params.stripe_account;
}
if (params.stripe_version) {
opts.headers['Stripe-Version'] = params.stripe_version;
}
}
}
return opts;
},
/**
* Provide simple "Class" extension mechanism
*/
protoExtend: function(sub) {
var Super = this;
var Constructor = hasOwn.call(sub, 'constructor') ? sub.constructor : function() {
Super.apply(this, arguments);
};
// This initialization logic is somewhat sensitive to be compatible with
// divergent JS implementations like the one found in Qt. See here for more
// context:
//
// https://github.com/stripe/stripe-node/pull/334
Object.assign(Constructor, Super);
Constructor.prototype = Object.create(Super.prototype);
Object.assign(Constructor.prototype, sub);
return Constructor;
},
/**
* Secure compare, from https://github.com/freewil/scmp
*/
secureCompare: function(a, b) {
a = Buffer.from(a);
b = Buffer.from(b);
// return early here if buffer lengths are not equal since timingSafeEqual
// will throw if buffer lengths are not equal
if (a.length !== b.length) {
return false;
}
// use crypto.timingSafeEqual if available (since Node.js v6.6.0),
// otherwise use our own scmp-internal function.
if (crypto.timingSafeEqual) {
return crypto.timingSafeEqual(a, b);
}
var len = a.length;
var result = 0;
for (var i = 0; i < len; ++i) {
result |= a[i] ^ b[i];
}
return result === 0;
},
/**
* Remove empty values from an object
*/
removeEmpty: function(obj) {
if (typeof obj !== 'object') {
throw new Error('Argument must be an object');
}
Object.keys(obj).forEach(function(key) {
if (obj[key] === null || obj[key] === undefined) {
delete obj[key];
}
});
return obj;
},
/**
* Determine if file data is a derivative of EventEmitter class.
* https://nodejs.org/api/events.html#events_events
*/
checkForStream: function (obj) {
if (obj.file && obj.file.data) {
return obj.file.data instanceof EventEmitter;
}
return false;
},
callbackifyPromiseWithTimeout: function(promise, callback) {
if (callback) {
// Ensure callback is called outside of promise stack.
return promise.then(function(res) {
setTimeout(function() { callback(null, res) }, 0);
}, function(err) {
setTimeout(function() { callback(err, null); }, 0);
});
}
return promise;
},
/**
* Allow for special capitalization cases (such as OAuth)
*/
pascalToCamelCase: function(name) {
if (name === 'OAuth') {
return 'oauth';
} else {
return name[0].toLowerCase() + name.substring(1);
}
},
emitWarning: emitWarning,
};
function emitWarning(warning) {
if (typeof process.emitWarning !== 'function') {
return console.warn('Stripe: ' + warning); /* eslint-disable-line no-console */
}
return process.emitWarning(warning, 'Stripe');
}