@prisma/cli 2.20.0 → 3.0.0-alpha.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 (183) hide show
  1. package/LICENSE +158 -0
  2. package/README.md +29 -28
  3. package/dist/adapters/config.js +74 -0
  4. package/dist/adapters/local-state.js +98 -0
  5. package/dist/adapters/mock-api.js +57 -0
  6. package/dist/adapters/token-storage.js +43 -0
  7. package/dist/cli.js +9 -0
  8. package/dist/cli2.js +59 -0
  9. package/dist/commands/app/index.js +223 -0
  10. package/dist/commands/auth/index.js +42 -0
  11. package/dist/commands/branch/index.js +51 -0
  12. package/dist/commands/project/index.js +45 -0
  13. package/dist/controllers/app.js +813 -0
  14. package/dist/controllers/auth.js +107 -0
  15. package/dist/controllers/branch.js +73 -0
  16. package/dist/controllers/project.js +214 -0
  17. package/dist/controllers/select-prompt-port.js +12 -0
  18. package/dist/lib/app/bun-project.js +39 -0
  19. package/dist/lib/app/env-vars.js +24 -0
  20. package/dist/lib/app/local-dev.js +149 -0
  21. package/dist/lib/app/preview-build.js +283 -0
  22. package/dist/lib/app/preview-interaction.js +38 -0
  23. package/dist/lib/app/preview-progress.js +139 -0
  24. package/dist/lib/app/preview-provider.js +232 -0
  25. package/dist/lib/auth/auth-ops.js +57 -0
  26. package/dist/lib/auth/client.js +22 -0
  27. package/dist/lib/auth/guard.js +34 -0
  28. package/dist/lib/auth/login.js +117 -0
  29. package/dist/output/patterns.js +93 -0
  30. package/dist/presenters/app.js +405 -0
  31. package/dist/presenters/auth.js +73 -0
  32. package/dist/presenters/branch.js +111 -0
  33. package/dist/presenters/project.js +84 -0
  34. package/dist/shell/command-meta.js +320 -0
  35. package/dist/shell/command-runner.js +33 -0
  36. package/dist/shell/errors.js +66 -0
  37. package/dist/shell/global-flags.js +25 -0
  38. package/dist/shell/help.js +78 -0
  39. package/dist/shell/output.js +54 -0
  40. package/dist/shell/prompt.js +31 -0
  41. package/dist/shell/runtime.js +51 -0
  42. package/dist/shell/ui.js +59 -0
  43. package/dist/use-cases/auth.js +70 -0
  44. package/dist/use-cases/branch.js +95 -0
  45. package/dist/use-cases/create-cli-gateways.js +93 -0
  46. package/dist/use-cases/project.js +75 -0
  47. package/package.json +49 -137
  48. package/build/child.js +0 -4110
  49. package/build/index.js +0 -104447
  50. package/build/public/demo.html +0 -17
  51. package/build/public/demoChunk.js +0 -2
  52. package/build/public/electron-darwin.html +0 -19
  53. package/build/public/electron-linux.html +0 -18
  54. package/build/public/electron-mac.html +0 -18
  55. package/build/public/electron-win.html +0 -17
  56. package/build/public/electron-win32.html +0 -18
  57. package/build/public/electron.html +0 -17
  58. package/build/public/electronBus.js +0 -2
  59. package/build/public/electronChunk.js +0 -2
  60. package/build/public/favicon/apple-touch-icon.png +0 -0
  61. package/build/public/favicon/favicon-16x16.png +0 -0
  62. package/build/public/favicon/favicon-32x32.png +0 -0
  63. package/build/public/favicon/prisma.png +0 -0
  64. package/build/public/fonts/Inter.ttf +0 -0
  65. package/build/public/fonts/RobotoMono.ttf +0 -0
  66. package/build/public/icons/.DS_Store +0 -0
  67. package/build/public/icons/alert.svg +0 -5
  68. package/build/public/icons/array.svg +0 -4
  69. package/build/public/icons/bin.svg +0 -37
  70. package/build/public/icons/boolean.svg +0 -4
  71. package/build/public/icons/check.svg +0 -3
  72. package/build/public/icons/chevron-down.svg +0 -3
  73. package/build/public/icons/code.svg +0 -4
  74. package/build/public/icons/cross.svg +0 -11
  75. package/build/public/icons/data-tool.svg +0 -5
  76. package/build/public/icons/database.svg +0 -4
  77. package/build/public/icons/datetime.svg +0 -4
  78. package/build/public/icons/double-arrow-right.svg +0 -4
  79. package/build/public/icons/download.svg +0 -4
  80. package/build/public/icons/ellipsis.svg +0 -10
  81. package/build/public/icons/enum.svg +0 -6
  82. package/build/public/icons/expand.svg +0 -4
  83. package/build/public/icons/eye.svg +0 -20
  84. package/build/public/icons/filters.svg +0 -5
  85. package/build/public/icons/folder.svg +0 -6
  86. package/build/public/icons/hamburger.svg +0 -4
  87. package/build/public/icons/icon.svg +0 -199
  88. package/build/public/icons/logo.svg +0 -199
  89. package/build/public/icons/logotype.svg +0 -4
  90. package/build/public/icons/number.svg +0 -7
  91. package/build/public/icons/object.svg +0 -5
  92. package/build/public/icons/play.svg +0 -6
  93. package/build/public/icons/plus.svg +0 -4
  94. package/build/public/icons/refresh.svg +0 -4
  95. package/build/public/icons/search.svg +0 -7
  96. package/build/public/icons/settings.svg +0 -8
  97. package/build/public/icons/string.svg +0 -4
  98. package/build/public/icons/tick-indeterminate.svg +0 -3
  99. package/build/public/icons/tick.svg +0 -4
  100. package/build/public/illustrations/.DS_Store +0 -0
  101. package/build/public/illustrations/empty.svg +0 -1
  102. package/build/public/illustrations/read.svg +0 -1
  103. package/build/public/illustrations/searching.svg +0 -1
  104. package/build/public/images/.DS_Store +0 -0
  105. package/build/public/images/icon-1024.png +0 -0
  106. package/build/public/index.html +0 -49
  107. package/build/public/main.31f688a6254e294d9128.css +0 -118
  108. package/build/public/main.31f688a6254e294d9128.css.map +0 -1
  109. package/build/public/main.364c712f32662ff0e43d.css +0 -116
  110. package/build/public/main.364c712f32662ff0e43d.css.map +0 -1
  111. package/build/public/main.42ef3fe7e97347765c91.css +0 -118
  112. package/build/public/main.42ef3fe7e97347765c91.css.map +0 -1
  113. package/build/public/main.503446defafe7aeca2f3.css +0 -116
  114. package/build/public/main.503446defafe7aeca2f3.css.map +0 -1
  115. package/build/public/main.c50a3b5980fe26f78b65.css +0 -118
  116. package/build/public/main.c50a3b5980fe26f78b65.css.map +0 -1
  117. package/build/public/main.cda25e5813776c2af295.css +0 -116
  118. package/build/public/main.cda25e5813776c2af295.css.map +0 -1
  119. package/build/public/main.dbac3b290f78404ff579.css +0 -116
  120. package/build/public/main.dbac3b290f78404ff579.css.map +0 -1
  121. package/build/public/main.f8ce44e122e5e2b8f778.css +0 -118
  122. package/build/public/main.f8ce44e122e5e2b8f778.css.map +0 -1
  123. package/build/public/main.fc9ea7521a4aecce1a77.css +0 -118
  124. package/build/public/main.fc9ea7521a4aecce1a77.css.map +0 -1
  125. package/build/public/main.js +0 -403
  126. package/build/public/main.js.map +0 -1
  127. package/build/public/mainChunk.0a84f3ba4d2ab481e877.css +0 -116
  128. package/build/public/mainChunk.1b327d58afbddc917bce.css +0 -118
  129. package/build/public/mainChunk.2cdf583b2bd51aa67587.css +0 -118
  130. package/build/public/mainChunk.544af00f7e9ffcbe782c.css +0 -118
  131. package/build/public/mainChunk.56f96a13868b2b4a53be.css +0 -118
  132. package/build/public/mainChunk.5cee429bfbf06e7ecb39.css +0 -118
  133. package/build/public/mainChunk.a862474ed4cdb421ffa2.css +0 -118
  134. package/build/public/mainChunk.ada34153c4911b5ac22b.css +0 -118
  135. package/build/public/mainChunk.c16a8d01b2c49b2f2751.css +0 -118
  136. package/build/public/mainChunk.ca4a878d5478b9320be8.css +0 -116
  137. package/build/public/mainChunk.e3adc8758b4395546cef.css +0 -116
  138. package/build/public/mainChunk.f2c59fcbfc455d8b9de5.css +0 -118
  139. package/build/public/mainChunk.js +0 -396
  140. package/build/public/preview.html +0 -16
  141. package/build/public/previewBus.js +0 -2
  142. package/build/public/previewChunk.js +0 -2
  143. package/build/public/projects.html +0 -86
  144. package/build/public/server.html +0 -16
  145. package/build/public/serverBus.js +0 -2
  146. package/build/public/serverChunk.js +0 -2
  147. package/build/public/splash.html +0 -17
  148. package/build/public/studioBundle.828f34b1781061528841.css +0 -118
  149. package/build/public/studioBundle.bfe9138b2e0293fcb7da.css +0 -118
  150. package/build/public/studioBundle.c5b256eede880e502aac.css +0 -118
  151. package/build/public/studioBundle.e43df511c8e2e368900a.css +0 -118
  152. package/build/public/studioBundle.e69382554c2a2942ae32.css +0 -118
  153. package/build/public/studioBundle.ee21aa56a3999a2b380b.css +0 -118
  154. package/build/public/studioBundle.js +0 -396
  155. package/build/public/vercel.html +0 -16
  156. package/build/public/vercelChunk.js +0 -2
  157. package/build/xdg-open +0 -1066
  158. package/install/index.js +0 -5
  159. package/preinstall/index.js +0 -71
  160. package/prisma-client/README.md +0 -27
  161. package/prisma-client/generator-build/.DS_Store +0 -0
  162. package/prisma-client/generator-build/index.js +0 -79697
  163. package/prisma-client/index-browser.js +0 -3
  164. package/prisma-client/index.d.ts +0 -1
  165. package/prisma-client/index.js +0 -11
  166. package/prisma-client/package.json +0 -138
  167. package/prisma-client/runtime/index-browser.d.ts +0 -267
  168. package/prisma-client/runtime/index-browser.js +0 -2273
  169. package/prisma-client/runtime/index.d.ts +0 -1018
  170. package/prisma-client/runtime/index.js +0 -35028
  171. package/prisma-client/scripts/backup-index-browser.js +0 -3
  172. package/prisma-client/scripts/backup-index.d.ts +0 -1
  173. package/prisma-client/scripts/backup-index.js +0 -11
  174. package/prisma-client/scripts/colors.js +0 -180
  175. package/prisma-client/scripts/default-index-browser.js +0 -12
  176. package/prisma-client/scripts/default-index.d.ts +0 -47
  177. package/prisma-client/scripts/default-index.js +0 -12
  178. package/prisma-client/scripts/get-packed-client.js +0 -12
  179. package/prisma-client/scripts/mock-fs.js +0 -14
  180. package/prisma-client/scripts/postinstall.d.ts +0 -5
  181. package/prisma-client/scripts/postinstall.js +0 -398
  182. package/scripts/install-entry.js +0 -8
  183. package/scripts/preinstall-entry.js +0 -9
package/build/child.js DELETED
@@ -1,4110 +0,0 @@
1
- 'use strict';
2
-
3
- var fs = require('fs');
4
- var path = require('path');
5
- var util = require('util');
6
- var os = require('os');
7
- var crypto = require('crypto');
8
- var Stream = require('stream');
9
- var http = require('http');
10
- var Url = require('url');
11
- var https = require('https');
12
- var zlib = require('zlib');
13
-
14
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15
-
16
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
17
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
18
- var util__default = /*#__PURE__*/_interopDefaultLegacy(util);
19
- var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
20
- var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
21
- var Stream__default = /*#__PURE__*/_interopDefaultLegacy(Stream);
22
- var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
23
- var Url__default = /*#__PURE__*/_interopDefaultLegacy(Url);
24
- var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
25
- var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib);
26
-
27
- const { open, write, close, rename, fsync, unlink } = fs__default['default'];
28
- const { join, dirname } = path__default['default'];
29
-
30
- var counter = 0;
31
-
32
- function cleanup (dest, err, cb) {
33
- unlink(dest, function () {
34
- cb(err);
35
- });
36
- }
37
-
38
- function closeAndCleanup (fd, dest, err, cb) {
39
- close(fd, cleanup.bind(null, dest, err, cb));
40
- }
41
-
42
- function writeLoop (fd, content, contentLength, offset, cb) {
43
- write(fd, content, offset, function (err, bytesWritten) {
44
- if (err) {
45
- cb(err);
46
- return
47
- }
48
-
49
- return (bytesWritten < contentLength - offset)
50
- ? writeLoop(fd, content, contentLength, offset + bytesWritten, cb)
51
- : cb(null)
52
- });
53
- }
54
-
55
- function openLoop (dest, cb) {
56
- open(dest, 'w', function (err, fd) {
57
- if (err) {
58
- return (err.code === 'EMFILE')
59
- ? openLoop(dest, cb)
60
- : cb(err)
61
- }
62
-
63
- cb(null, fd);
64
- });
65
- }
66
-
67
- function writeAtomic (path, content, cb) {
68
- const tmp = join(dirname(path), '.' + process.pid + '.' + counter++);
69
- openLoop(tmp, function (err, fd) {
70
- if (err) {
71
- cb(err);
72
- return
73
- }
74
-
75
- const contentLength = Buffer.byteLength(content);
76
- writeLoop(fd, content, contentLength, 0, function (err) {
77
- if (err) {
78
- closeAndCleanup(fd, tmp, err, cb);
79
- return
80
- }
81
-
82
- fsync(fd, function (err) {
83
- if (err) {
84
- closeAndCleanup(fd, tmp, err, cb);
85
- return
86
- }
87
-
88
- close(fd, function (err) {
89
- if (err) {
90
- // TODO could we possibly be leaking a file descriptor here?
91
- cleanup(tmp, err, cb);
92
- return
93
- }
94
-
95
- rename(tmp, path, (err) => {
96
- if (err) {
97
- cleanup(tmp, err, cb);
98
- return
99
- }
100
-
101
- cb(null);
102
- });
103
- });
104
- });
105
- });
106
-
107
- // clean up after oursevles, this is not needed
108
- // anymore
109
- content = null;
110
- });
111
- }
112
-
113
- var fastWriteAtomic = writeAtomic;
114
-
115
- function createCommonjsModule(fn) {
116
- var module = { exports: {} };
117
- return fn(module, module.exports), module.exports;
118
- }
119
-
120
- var semver = createCommonjsModule(function (module, exports) {
121
- exports = module.exports = SemVer;
122
-
123
- var debug;
124
- /* istanbul ignore next */
125
- if (typeof process === 'object' &&
126
- process.env &&
127
- process.env.NODE_DEBUG &&
128
- /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
129
- debug = function () {
130
- var args = Array.prototype.slice.call(arguments, 0);
131
- args.unshift('SEMVER');
132
- console.log.apply(console, args);
133
- };
134
- } else {
135
- debug = function () {};
136
- }
137
-
138
- // Note: this is the semver.org version of the spec that it implements
139
- // Not necessarily the package version of this code.
140
- exports.SEMVER_SPEC_VERSION = '2.0.0';
141
-
142
- var MAX_LENGTH = 256;
143
- var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
144
- /* istanbul ignore next */ 9007199254740991;
145
-
146
- // Max safe segment length for coercion.
147
- var MAX_SAFE_COMPONENT_LENGTH = 16;
148
-
149
- // The actual regexps go on exports.re
150
- var re = exports.re = [];
151
- var src = exports.src = [];
152
- var t = exports.tokens = {};
153
- var R = 0;
154
-
155
- function tok (n) {
156
- t[n] = R++;
157
- }
158
-
159
- // The following Regular Expressions can be used for tokenizing,
160
- // validating, and parsing SemVer version strings.
161
-
162
- // ## Numeric Identifier
163
- // A single `0`, or a non-zero digit followed by zero or more digits.
164
-
165
- tok('NUMERICIDENTIFIER');
166
- src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*';
167
- tok('NUMERICIDENTIFIERLOOSE');
168
- src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+';
169
-
170
- // ## Non-numeric Identifier
171
- // Zero or more digits, followed by a letter or hyphen, and then zero or
172
- // more letters, digits, or hyphens.
173
-
174
- tok('NONNUMERICIDENTIFIER');
175
- src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
176
-
177
- // ## Main Version
178
- // Three dot-separated numeric identifiers.
179
-
180
- tok('MAINVERSION');
181
- src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
182
- '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
183
- '(' + src[t.NUMERICIDENTIFIER] + ')';
184
-
185
- tok('MAINVERSIONLOOSE');
186
- src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
187
- '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
188
- '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')';
189
-
190
- // ## Pre-release Version Identifier
191
- // A numeric identifier, or a non-numeric identifier.
192
-
193
- tok('PRERELEASEIDENTIFIER');
194
- src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +
195
- '|' + src[t.NONNUMERICIDENTIFIER] + ')';
196
-
197
- tok('PRERELEASEIDENTIFIERLOOSE');
198
- src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +
199
- '|' + src[t.NONNUMERICIDENTIFIER] + ')';
200
-
201
- // ## Pre-release Version
202
- // Hyphen, followed by one or more dot-separated pre-release version
203
- // identifiers.
204
-
205
- tok('PRERELEASE');
206
- src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +
207
- '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))';
208
-
209
- tok('PRERELEASELOOSE');
210
- src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +
211
- '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))';
212
-
213
- // ## Build Metadata Identifier
214
- // Any combination of digits, letters, or hyphens.
215
-
216
- tok('BUILDIDENTIFIER');
217
- src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+';
218
-
219
- // ## Build Metadata
220
- // Plus sign, followed by one or more period-separated build metadata
221
- // identifiers.
222
-
223
- tok('BUILD');
224
- src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] +
225
- '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))';
226
-
227
- // ## Full Version String
228
- // A main version, followed optionally by a pre-release version and
229
- // build metadata.
230
-
231
- // Note that the only major, minor, patch, and pre-release sections of
232
- // the version string are capturing groups. The build metadata is not a
233
- // capturing group, because it should not ever be used in version
234
- // comparison.
235
-
236
- tok('FULL');
237
- tok('FULLPLAIN');
238
- src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +
239
- src[t.PRERELEASE] + '?' +
240
- src[t.BUILD] + '?';
241
-
242
- src[t.FULL] = '^' + src[t.FULLPLAIN] + '$';
243
-
244
- // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
245
- // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
246
- // common in the npm registry.
247
- tok('LOOSEPLAIN');
248
- src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] +
249
- src[t.PRERELEASELOOSE] + '?' +
250
- src[t.BUILD] + '?';
251
-
252
- tok('LOOSE');
253
- src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$';
254
-
255
- tok('GTLT');
256
- src[t.GTLT] = '((?:<|>)?=?)';
257
-
258
- // Something like "2.*" or "1.2.x".
259
- // Note that "x.x" is a valid xRange identifer, meaning "any version"
260
- // Only the first item is strictly required.
261
- tok('XRANGEIDENTIFIERLOOSE');
262
- src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
263
- tok('XRANGEIDENTIFIER');
264
- src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*';
265
-
266
- tok('XRANGEPLAIN');
267
- src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
268
- '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
269
- '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
270
- '(?:' + src[t.PRERELEASE] + ')?' +
271
- src[t.BUILD] + '?' +
272
- ')?)?';
273
-
274
- tok('XRANGEPLAINLOOSE');
275
- src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
276
- '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
277
- '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
278
- '(?:' + src[t.PRERELEASELOOSE] + ')?' +
279
- src[t.BUILD] + '?' +
280
- ')?)?';
281
-
282
- tok('XRANGE');
283
- src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$';
284
- tok('XRANGELOOSE');
285
- src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$';
286
-
287
- // Coercion.
288
- // Extract anything that could conceivably be a part of a valid semver
289
- tok('COERCE');
290
- src[t.COERCE] = '(^|[^\\d])' +
291
- '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
292
- '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
293
- '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
294
- '(?:$|[^\\d])';
295
- tok('COERCERTL');
296
- re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g');
297
-
298
- // Tilde ranges.
299
- // Meaning is "reasonably at or greater than"
300
- tok('LONETILDE');
301
- src[t.LONETILDE] = '(?:~>?)';
302
-
303
- tok('TILDETRIM');
304
- src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+';
305
- re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g');
306
- var tildeTrimReplace = '$1~';
307
-
308
- tok('TILDE');
309
- src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$';
310
- tok('TILDELOOSE');
311
- src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$';
312
-
313
- // Caret ranges.
314
- // Meaning is "at least and backwards compatible with"
315
- tok('LONECARET');
316
- src[t.LONECARET] = '(?:\\^)';
317
-
318
- tok('CARETTRIM');
319
- src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+';
320
- re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g');
321
- var caretTrimReplace = '$1^';
322
-
323
- tok('CARET');
324
- src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$';
325
- tok('CARETLOOSE');
326
- src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$';
327
-
328
- // A simple gt/lt/eq thing, or just "" to indicate "any version"
329
- tok('COMPARATORLOOSE');
330
- src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$';
331
- tok('COMPARATOR');
332
- src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$';
333
-
334
- // An expression to strip any whitespace between the gtlt and the thing
335
- // it modifies, so that `> 1.2.3` ==> `>1.2.3`
336
- tok('COMPARATORTRIM');
337
- src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] +
338
- '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')';
339
-
340
- // this one has to use the /g flag
341
- re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g');
342
- var comparatorTrimReplace = '$1$2$3';
343
-
344
- // Something like `1.2.3 - 1.2.4`
345
- // Note that these all use the loose form, because they'll be
346
- // checked against either the strict or loose comparator form
347
- // later.
348
- tok('HYPHENRANGE');
349
- src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' +
350
- '\\s+-\\s+' +
351
- '(' + src[t.XRANGEPLAIN] + ')' +
352
- '\\s*$';
353
-
354
- tok('HYPHENRANGELOOSE');
355
- src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +
356
- '\\s+-\\s+' +
357
- '(' + src[t.XRANGEPLAINLOOSE] + ')' +
358
- '\\s*$';
359
-
360
- // Star ranges basically just allow anything at all.
361
- tok('STAR');
362
- src[t.STAR] = '(<|>)?=?\\s*\\*';
363
-
364
- // Compile to actual regexp objects.
365
- // All are flag-free, unless they were created above with a flag.
366
- for (var i = 0; i < R; i++) {
367
- debug(i, src[i]);
368
- if (!re[i]) {
369
- re[i] = new RegExp(src[i]);
370
- }
371
- }
372
-
373
- exports.parse = parse;
374
- function parse (version, options) {
375
- if (!options || typeof options !== 'object') {
376
- options = {
377
- loose: !!options,
378
- includePrerelease: false
379
- };
380
- }
381
-
382
- if (version instanceof SemVer) {
383
- return version
384
- }
385
-
386
- if (typeof version !== 'string') {
387
- return null
388
- }
389
-
390
- if (version.length > MAX_LENGTH) {
391
- return null
392
- }
393
-
394
- var r = options.loose ? re[t.LOOSE] : re[t.FULL];
395
- if (!r.test(version)) {
396
- return null
397
- }
398
-
399
- try {
400
- return new SemVer(version, options)
401
- } catch (er) {
402
- return null
403
- }
404
- }
405
-
406
- exports.valid = valid;
407
- function valid (version, options) {
408
- var v = parse(version, options);
409
- return v ? v.version : null
410
- }
411
-
412
- exports.clean = clean;
413
- function clean (version, options) {
414
- var s = parse(version.trim().replace(/^[=v]+/, ''), options);
415
- return s ? s.version : null
416
- }
417
-
418
- exports.SemVer = SemVer;
419
-
420
- function SemVer (version, options) {
421
- if (!options || typeof options !== 'object') {
422
- options = {
423
- loose: !!options,
424
- includePrerelease: false
425
- };
426
- }
427
- if (version instanceof SemVer) {
428
- if (version.loose === options.loose) {
429
- return version
430
- } else {
431
- version = version.version;
432
- }
433
- } else if (typeof version !== 'string') {
434
- throw new TypeError('Invalid Version: ' + version)
435
- }
436
-
437
- if (version.length > MAX_LENGTH) {
438
- throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
439
- }
440
-
441
- if (!(this instanceof SemVer)) {
442
- return new SemVer(version, options)
443
- }
444
-
445
- debug('SemVer', version, options);
446
- this.options = options;
447
- this.loose = !!options.loose;
448
-
449
- var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
450
-
451
- if (!m) {
452
- throw new TypeError('Invalid Version: ' + version)
453
- }
454
-
455
- this.raw = version;
456
-
457
- // these are actually numbers
458
- this.major = +m[1];
459
- this.minor = +m[2];
460
- this.patch = +m[3];
461
-
462
- if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
463
- throw new TypeError('Invalid major version')
464
- }
465
-
466
- if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
467
- throw new TypeError('Invalid minor version')
468
- }
469
-
470
- if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
471
- throw new TypeError('Invalid patch version')
472
- }
473
-
474
- // numberify any prerelease numeric ids
475
- if (!m[4]) {
476
- this.prerelease = [];
477
- } else {
478
- this.prerelease = m[4].split('.').map(function (id) {
479
- if (/^[0-9]+$/.test(id)) {
480
- var num = +id;
481
- if (num >= 0 && num < MAX_SAFE_INTEGER) {
482
- return num
483
- }
484
- }
485
- return id
486
- });
487
- }
488
-
489
- this.build = m[5] ? m[5].split('.') : [];
490
- this.format();
491
- }
492
-
493
- SemVer.prototype.format = function () {
494
- this.version = this.major + '.' + this.minor + '.' + this.patch;
495
- if (this.prerelease.length) {
496
- this.version += '-' + this.prerelease.join('.');
497
- }
498
- return this.version
499
- };
500
-
501
- SemVer.prototype.toString = function () {
502
- return this.version
503
- };
504
-
505
- SemVer.prototype.compare = function (other) {
506
- debug('SemVer.compare', this.version, this.options, other);
507
- if (!(other instanceof SemVer)) {
508
- other = new SemVer(other, this.options);
509
- }
510
-
511
- return this.compareMain(other) || this.comparePre(other)
512
- };
513
-
514
- SemVer.prototype.compareMain = function (other) {
515
- if (!(other instanceof SemVer)) {
516
- other = new SemVer(other, this.options);
517
- }
518
-
519
- return compareIdentifiers(this.major, other.major) ||
520
- compareIdentifiers(this.minor, other.minor) ||
521
- compareIdentifiers(this.patch, other.patch)
522
- };
523
-
524
- SemVer.prototype.comparePre = function (other) {
525
- if (!(other instanceof SemVer)) {
526
- other = new SemVer(other, this.options);
527
- }
528
-
529
- // NOT having a prerelease is > having one
530
- if (this.prerelease.length && !other.prerelease.length) {
531
- return -1
532
- } else if (!this.prerelease.length && other.prerelease.length) {
533
- return 1
534
- } else if (!this.prerelease.length && !other.prerelease.length) {
535
- return 0
536
- }
537
-
538
- var i = 0;
539
- do {
540
- var a = this.prerelease[i];
541
- var b = other.prerelease[i];
542
- debug('prerelease compare', i, a, b);
543
- if (a === undefined && b === undefined) {
544
- return 0
545
- } else if (b === undefined) {
546
- return 1
547
- } else if (a === undefined) {
548
- return -1
549
- } else if (a === b) {
550
- continue
551
- } else {
552
- return compareIdentifiers(a, b)
553
- }
554
- } while (++i)
555
- };
556
-
557
- SemVer.prototype.compareBuild = function (other) {
558
- if (!(other instanceof SemVer)) {
559
- other = new SemVer(other, this.options);
560
- }
561
-
562
- var i = 0;
563
- do {
564
- var a = this.build[i];
565
- var b = other.build[i];
566
- debug('prerelease compare', i, a, b);
567
- if (a === undefined && b === undefined) {
568
- return 0
569
- } else if (b === undefined) {
570
- return 1
571
- } else if (a === undefined) {
572
- return -1
573
- } else if (a === b) {
574
- continue
575
- } else {
576
- return compareIdentifiers(a, b)
577
- }
578
- } while (++i)
579
- };
580
-
581
- // preminor will bump the version up to the next minor release, and immediately
582
- // down to pre-release. premajor and prepatch work the same way.
583
- SemVer.prototype.inc = function (release, identifier) {
584
- switch (release) {
585
- case 'premajor':
586
- this.prerelease.length = 0;
587
- this.patch = 0;
588
- this.minor = 0;
589
- this.major++;
590
- this.inc('pre', identifier);
591
- break
592
- case 'preminor':
593
- this.prerelease.length = 0;
594
- this.patch = 0;
595
- this.minor++;
596
- this.inc('pre', identifier);
597
- break
598
- case 'prepatch':
599
- // If this is already a prerelease, it will bump to the next version
600
- // drop any prereleases that might already exist, since they are not
601
- // relevant at this point.
602
- this.prerelease.length = 0;
603
- this.inc('patch', identifier);
604
- this.inc('pre', identifier);
605
- break
606
- // If the input is a non-prerelease version, this acts the same as
607
- // prepatch.
608
- case 'prerelease':
609
- if (this.prerelease.length === 0) {
610
- this.inc('patch', identifier);
611
- }
612
- this.inc('pre', identifier);
613
- break
614
-
615
- case 'major':
616
- // If this is a pre-major version, bump up to the same major version.
617
- // Otherwise increment major.
618
- // 1.0.0-5 bumps to 1.0.0
619
- // 1.1.0 bumps to 2.0.0
620
- if (this.minor !== 0 ||
621
- this.patch !== 0 ||
622
- this.prerelease.length === 0) {
623
- this.major++;
624
- }
625
- this.minor = 0;
626
- this.patch = 0;
627
- this.prerelease = [];
628
- break
629
- case 'minor':
630
- // If this is a pre-minor version, bump up to the same minor version.
631
- // Otherwise increment minor.
632
- // 1.2.0-5 bumps to 1.2.0
633
- // 1.2.1 bumps to 1.3.0
634
- if (this.patch !== 0 || this.prerelease.length === 0) {
635
- this.minor++;
636
- }
637
- this.patch = 0;
638
- this.prerelease = [];
639
- break
640
- case 'patch':
641
- // If this is not a pre-release version, it will increment the patch.
642
- // If it is a pre-release it will bump up to the same patch version.
643
- // 1.2.0-5 patches to 1.2.0
644
- // 1.2.0 patches to 1.2.1
645
- if (this.prerelease.length === 0) {
646
- this.patch++;
647
- }
648
- this.prerelease = [];
649
- break
650
- // This probably shouldn't be used publicly.
651
- // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
652
- case 'pre':
653
- if (this.prerelease.length === 0) {
654
- this.prerelease = [0];
655
- } else {
656
- var i = this.prerelease.length;
657
- while (--i >= 0) {
658
- if (typeof this.prerelease[i] === 'number') {
659
- this.prerelease[i]++;
660
- i = -2;
661
- }
662
- }
663
- if (i === -1) {
664
- // didn't increment anything
665
- this.prerelease.push(0);
666
- }
667
- }
668
- if (identifier) {
669
- // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
670
- // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
671
- if (this.prerelease[0] === identifier) {
672
- if (isNaN(this.prerelease[1])) {
673
- this.prerelease = [identifier, 0];
674
- }
675
- } else {
676
- this.prerelease = [identifier, 0];
677
- }
678
- }
679
- break
680
-
681
- default:
682
- throw new Error('invalid increment argument: ' + release)
683
- }
684
- this.format();
685
- this.raw = this.version;
686
- return this
687
- };
688
-
689
- exports.inc = inc;
690
- function inc (version, release, loose, identifier) {
691
- if (typeof (loose) === 'string') {
692
- identifier = loose;
693
- loose = undefined;
694
- }
695
-
696
- try {
697
- return new SemVer(version, loose).inc(release, identifier).version
698
- } catch (er) {
699
- return null
700
- }
701
- }
702
-
703
- exports.diff = diff;
704
- function diff (version1, version2) {
705
- if (eq(version1, version2)) {
706
- return null
707
- } else {
708
- var v1 = parse(version1);
709
- var v2 = parse(version2);
710
- var prefix = '';
711
- if (v1.prerelease.length || v2.prerelease.length) {
712
- prefix = 'pre';
713
- var defaultResult = 'prerelease';
714
- }
715
- for (var key in v1) {
716
- if (key === 'major' || key === 'minor' || key === 'patch') {
717
- if (v1[key] !== v2[key]) {
718
- return prefix + key
719
- }
720
- }
721
- }
722
- return defaultResult // may be undefined
723
- }
724
- }
725
-
726
- exports.compareIdentifiers = compareIdentifiers;
727
-
728
- var numeric = /^[0-9]+$/;
729
- function compareIdentifiers (a, b) {
730
- var anum = numeric.test(a);
731
- var bnum = numeric.test(b);
732
-
733
- if (anum && bnum) {
734
- a = +a;
735
- b = +b;
736
- }
737
-
738
- return a === b ? 0
739
- : (anum && !bnum) ? -1
740
- : (bnum && !anum) ? 1
741
- : a < b ? -1
742
- : 1
743
- }
744
-
745
- exports.rcompareIdentifiers = rcompareIdentifiers;
746
- function rcompareIdentifiers (a, b) {
747
- return compareIdentifiers(b, a)
748
- }
749
-
750
- exports.major = major;
751
- function major (a, loose) {
752
- return new SemVer(a, loose).major
753
- }
754
-
755
- exports.minor = minor;
756
- function minor (a, loose) {
757
- return new SemVer(a, loose).minor
758
- }
759
-
760
- exports.patch = patch;
761
- function patch (a, loose) {
762
- return new SemVer(a, loose).patch
763
- }
764
-
765
- exports.compare = compare;
766
- function compare (a, b, loose) {
767
- return new SemVer(a, loose).compare(new SemVer(b, loose))
768
- }
769
-
770
- exports.compareLoose = compareLoose;
771
- function compareLoose (a, b) {
772
- return compare(a, b, true)
773
- }
774
-
775
- exports.compareBuild = compareBuild;
776
- function compareBuild (a, b, loose) {
777
- var versionA = new SemVer(a, loose);
778
- var versionB = new SemVer(b, loose);
779
- return versionA.compare(versionB) || versionA.compareBuild(versionB)
780
- }
781
-
782
- exports.rcompare = rcompare;
783
- function rcompare (a, b, loose) {
784
- return compare(b, a, loose)
785
- }
786
-
787
- exports.sort = sort;
788
- function sort (list, loose) {
789
- return list.sort(function (a, b) {
790
- return exports.compareBuild(a, b, loose)
791
- })
792
- }
793
-
794
- exports.rsort = rsort;
795
- function rsort (list, loose) {
796
- return list.sort(function (a, b) {
797
- return exports.compareBuild(b, a, loose)
798
- })
799
- }
800
-
801
- exports.gt = gt;
802
- function gt (a, b, loose) {
803
- return compare(a, b, loose) > 0
804
- }
805
-
806
- exports.lt = lt;
807
- function lt (a, b, loose) {
808
- return compare(a, b, loose) < 0
809
- }
810
-
811
- exports.eq = eq;
812
- function eq (a, b, loose) {
813
- return compare(a, b, loose) === 0
814
- }
815
-
816
- exports.neq = neq;
817
- function neq (a, b, loose) {
818
- return compare(a, b, loose) !== 0
819
- }
820
-
821
- exports.gte = gte;
822
- function gte (a, b, loose) {
823
- return compare(a, b, loose) >= 0
824
- }
825
-
826
- exports.lte = lte;
827
- function lte (a, b, loose) {
828
- return compare(a, b, loose) <= 0
829
- }
830
-
831
- exports.cmp = cmp;
832
- function cmp (a, op, b, loose) {
833
- switch (op) {
834
- case '===':
835
- if (typeof a === 'object')
836
- a = a.version;
837
- if (typeof b === 'object')
838
- b = b.version;
839
- return a === b
840
-
841
- case '!==':
842
- if (typeof a === 'object')
843
- a = a.version;
844
- if (typeof b === 'object')
845
- b = b.version;
846
- return a !== b
847
-
848
- case '':
849
- case '=':
850
- case '==':
851
- return eq(a, b, loose)
852
-
853
- case '!=':
854
- return neq(a, b, loose)
855
-
856
- case '>':
857
- return gt(a, b, loose)
858
-
859
- case '>=':
860
- return gte(a, b, loose)
861
-
862
- case '<':
863
- return lt(a, b, loose)
864
-
865
- case '<=':
866
- return lte(a, b, loose)
867
-
868
- default:
869
- throw new TypeError('Invalid operator: ' + op)
870
- }
871
- }
872
-
873
- exports.Comparator = Comparator;
874
- function Comparator (comp, options) {
875
- if (!options || typeof options !== 'object') {
876
- options = {
877
- loose: !!options,
878
- includePrerelease: false
879
- };
880
- }
881
-
882
- if (comp instanceof Comparator) {
883
- if (comp.loose === !!options.loose) {
884
- return comp
885
- } else {
886
- comp = comp.value;
887
- }
888
- }
889
-
890
- if (!(this instanceof Comparator)) {
891
- return new Comparator(comp, options)
892
- }
893
-
894
- debug('comparator', comp, options);
895
- this.options = options;
896
- this.loose = !!options.loose;
897
- this.parse(comp);
898
-
899
- if (this.semver === ANY) {
900
- this.value = '';
901
- } else {
902
- this.value = this.operator + this.semver.version;
903
- }
904
-
905
- debug('comp', this);
906
- }
907
-
908
- var ANY = {};
909
- Comparator.prototype.parse = function (comp) {
910
- var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
911
- var m = comp.match(r);
912
-
913
- if (!m) {
914
- throw new TypeError('Invalid comparator: ' + comp)
915
- }
916
-
917
- this.operator = m[1] !== undefined ? m[1] : '';
918
- if (this.operator === '=') {
919
- this.operator = '';
920
- }
921
-
922
- // if it literally is just '>' or '' then allow anything.
923
- if (!m[2]) {
924
- this.semver = ANY;
925
- } else {
926
- this.semver = new SemVer(m[2], this.options.loose);
927
- }
928
- };
929
-
930
- Comparator.prototype.toString = function () {
931
- return this.value
932
- };
933
-
934
- Comparator.prototype.test = function (version) {
935
- debug('Comparator.test', version, this.options.loose);
936
-
937
- if (this.semver === ANY || version === ANY) {
938
- return true
939
- }
940
-
941
- if (typeof version === 'string') {
942
- try {
943
- version = new SemVer(version, this.options);
944
- } catch (er) {
945
- return false
946
- }
947
- }
948
-
949
- return cmp(version, this.operator, this.semver, this.options)
950
- };
951
-
952
- Comparator.prototype.intersects = function (comp, options) {
953
- if (!(comp instanceof Comparator)) {
954
- throw new TypeError('a Comparator is required')
955
- }
956
-
957
- if (!options || typeof options !== 'object') {
958
- options = {
959
- loose: !!options,
960
- includePrerelease: false
961
- };
962
- }
963
-
964
- var rangeTmp;
965
-
966
- if (this.operator === '') {
967
- if (this.value === '') {
968
- return true
969
- }
970
- rangeTmp = new Range(comp.value, options);
971
- return satisfies(this.value, rangeTmp, options)
972
- } else if (comp.operator === '') {
973
- if (comp.value === '') {
974
- return true
975
- }
976
- rangeTmp = new Range(this.value, options);
977
- return satisfies(comp.semver, rangeTmp, options)
978
- }
979
-
980
- var sameDirectionIncreasing =
981
- (this.operator === '>=' || this.operator === '>') &&
982
- (comp.operator === '>=' || comp.operator === '>');
983
- var sameDirectionDecreasing =
984
- (this.operator === '<=' || this.operator === '<') &&
985
- (comp.operator === '<=' || comp.operator === '<');
986
- var sameSemVer = this.semver.version === comp.semver.version;
987
- var differentDirectionsInclusive =
988
- (this.operator === '>=' || this.operator === '<=') &&
989
- (comp.operator === '>=' || comp.operator === '<=');
990
- var oppositeDirectionsLessThan =
991
- cmp(this.semver, '<', comp.semver, options) &&
992
- ((this.operator === '>=' || this.operator === '>') &&
993
- (comp.operator === '<=' || comp.operator === '<'));
994
- var oppositeDirectionsGreaterThan =
995
- cmp(this.semver, '>', comp.semver, options) &&
996
- ((this.operator === '<=' || this.operator === '<') &&
997
- (comp.operator === '>=' || comp.operator === '>'));
998
-
999
- return sameDirectionIncreasing || sameDirectionDecreasing ||
1000
- (sameSemVer && differentDirectionsInclusive) ||
1001
- oppositeDirectionsLessThan || oppositeDirectionsGreaterThan
1002
- };
1003
-
1004
- exports.Range = Range;
1005
- function Range (range, options) {
1006
- if (!options || typeof options !== 'object') {
1007
- options = {
1008
- loose: !!options,
1009
- includePrerelease: false
1010
- };
1011
- }
1012
-
1013
- if (range instanceof Range) {
1014
- if (range.loose === !!options.loose &&
1015
- range.includePrerelease === !!options.includePrerelease) {
1016
- return range
1017
- } else {
1018
- return new Range(range.raw, options)
1019
- }
1020
- }
1021
-
1022
- if (range instanceof Comparator) {
1023
- return new Range(range.value, options)
1024
- }
1025
-
1026
- if (!(this instanceof Range)) {
1027
- return new Range(range, options)
1028
- }
1029
-
1030
- this.options = options;
1031
- this.loose = !!options.loose;
1032
- this.includePrerelease = !!options.includePrerelease;
1033
-
1034
- // First, split based on boolean or ||
1035
- this.raw = range;
1036
- this.set = range.split(/\s*\|\|\s*/).map(function (range) {
1037
- return this.parseRange(range.trim())
1038
- }, this).filter(function (c) {
1039
- // throw out any that are not relevant for whatever reason
1040
- return c.length
1041
- });
1042
-
1043
- if (!this.set.length) {
1044
- throw new TypeError('Invalid SemVer Range: ' + range)
1045
- }
1046
-
1047
- this.format();
1048
- }
1049
-
1050
- Range.prototype.format = function () {
1051
- this.range = this.set.map(function (comps) {
1052
- return comps.join(' ').trim()
1053
- }).join('||').trim();
1054
- return this.range
1055
- };
1056
-
1057
- Range.prototype.toString = function () {
1058
- return this.range
1059
- };
1060
-
1061
- Range.prototype.parseRange = function (range) {
1062
- var loose = this.options.loose;
1063
- range = range.trim();
1064
- // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
1065
- var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
1066
- range = range.replace(hr, hyphenReplace);
1067
- debug('hyphen replace', range);
1068
- // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
1069
- range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
1070
- debug('comparator trim', range, re[t.COMPARATORTRIM]);
1071
-
1072
- // `~ 1.2.3` => `~1.2.3`
1073
- range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
1074
-
1075
- // `^ 1.2.3` => `^1.2.3`
1076
- range = range.replace(re[t.CARETTRIM], caretTrimReplace);
1077
-
1078
- // normalize spaces
1079
- range = range.split(/\s+/).join(' ');
1080
-
1081
- // At this point, the range is completely trimmed and
1082
- // ready to be split into comparators.
1083
-
1084
- var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
1085
- var set = range.split(' ').map(function (comp) {
1086
- return parseComparator(comp, this.options)
1087
- }, this).join(' ').split(/\s+/);
1088
- if (this.options.loose) {
1089
- // in loose mode, throw out any that are not valid comparators
1090
- set = set.filter(function (comp) {
1091
- return !!comp.match(compRe)
1092
- });
1093
- }
1094
- set = set.map(function (comp) {
1095
- return new Comparator(comp, this.options)
1096
- }, this);
1097
-
1098
- return set
1099
- };
1100
-
1101
- Range.prototype.intersects = function (range, options) {
1102
- if (!(range instanceof Range)) {
1103
- throw new TypeError('a Range is required')
1104
- }
1105
-
1106
- return this.set.some(function (thisComparators) {
1107
- return (
1108
- isSatisfiable(thisComparators, options) &&
1109
- range.set.some(function (rangeComparators) {
1110
- return (
1111
- isSatisfiable(rangeComparators, options) &&
1112
- thisComparators.every(function (thisComparator) {
1113
- return rangeComparators.every(function (rangeComparator) {
1114
- return thisComparator.intersects(rangeComparator, options)
1115
- })
1116
- })
1117
- )
1118
- })
1119
- )
1120
- })
1121
- };
1122
-
1123
- // take a set of comparators and determine whether there
1124
- // exists a version which can satisfy it
1125
- function isSatisfiable (comparators, options) {
1126
- var result = true;
1127
- var remainingComparators = comparators.slice();
1128
- var testComparator = remainingComparators.pop();
1129
-
1130
- while (result && remainingComparators.length) {
1131
- result = remainingComparators.every(function (otherComparator) {
1132
- return testComparator.intersects(otherComparator, options)
1133
- });
1134
-
1135
- testComparator = remainingComparators.pop();
1136
- }
1137
-
1138
- return result
1139
- }
1140
-
1141
- // Mostly just for testing and legacy API reasons
1142
- exports.toComparators = toComparators;
1143
- function toComparators (range, options) {
1144
- return new Range(range, options).set.map(function (comp) {
1145
- return comp.map(function (c) {
1146
- return c.value
1147
- }).join(' ').trim().split(' ')
1148
- })
1149
- }
1150
-
1151
- // comprised of xranges, tildes, stars, and gtlt's at this point.
1152
- // already replaced the hyphen ranges
1153
- // turn into a set of JUST comparators.
1154
- function parseComparator (comp, options) {
1155
- debug('comp', comp, options);
1156
- comp = replaceCarets(comp, options);
1157
- debug('caret', comp);
1158
- comp = replaceTildes(comp, options);
1159
- debug('tildes', comp);
1160
- comp = replaceXRanges(comp, options);
1161
- debug('xrange', comp);
1162
- comp = replaceStars(comp, options);
1163
- debug('stars', comp);
1164
- return comp
1165
- }
1166
-
1167
- function isX (id) {
1168
- return !id || id.toLowerCase() === 'x' || id === '*'
1169
- }
1170
-
1171
- // ~, ~> --> * (any, kinda silly)
1172
- // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
1173
- // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
1174
- // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
1175
- // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
1176
- // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
1177
- function replaceTildes (comp, options) {
1178
- return comp.trim().split(/\s+/).map(function (comp) {
1179
- return replaceTilde(comp, options)
1180
- }).join(' ')
1181
- }
1182
-
1183
- function replaceTilde (comp, options) {
1184
- var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
1185
- return comp.replace(r, function (_, M, m, p, pr) {
1186
- debug('tilde', comp, _, M, m, p, pr);
1187
- var ret;
1188
-
1189
- if (isX(M)) {
1190
- ret = '';
1191
- } else if (isX(m)) {
1192
- ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
1193
- } else if (isX(p)) {
1194
- // ~1.2 == >=1.2.0 <1.3.0
1195
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
1196
- } else if (pr) {
1197
- debug('replaceTilde pr', pr);
1198
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
1199
- ' <' + M + '.' + (+m + 1) + '.0';
1200
- } else {
1201
- // ~1.2.3 == >=1.2.3 <1.3.0
1202
- ret = '>=' + M + '.' + m + '.' + p +
1203
- ' <' + M + '.' + (+m + 1) + '.0';
1204
- }
1205
-
1206
- debug('tilde return', ret);
1207
- return ret
1208
- })
1209
- }
1210
-
1211
- // ^ --> * (any, kinda silly)
1212
- // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
1213
- // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
1214
- // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
1215
- // ^1.2.3 --> >=1.2.3 <2.0.0
1216
- // ^1.2.0 --> >=1.2.0 <2.0.0
1217
- function replaceCarets (comp, options) {
1218
- return comp.trim().split(/\s+/).map(function (comp) {
1219
- return replaceCaret(comp, options)
1220
- }).join(' ')
1221
- }
1222
-
1223
- function replaceCaret (comp, options) {
1224
- debug('caret', comp, options);
1225
- var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
1226
- return comp.replace(r, function (_, M, m, p, pr) {
1227
- debug('caret', comp, _, M, m, p, pr);
1228
- var ret;
1229
-
1230
- if (isX(M)) {
1231
- ret = '';
1232
- } else if (isX(m)) {
1233
- ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
1234
- } else if (isX(p)) {
1235
- if (M === '0') {
1236
- ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
1237
- } else {
1238
- ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
1239
- }
1240
- } else if (pr) {
1241
- debug('replaceCaret pr', pr);
1242
- if (M === '0') {
1243
- if (m === '0') {
1244
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
1245
- ' <' + M + '.' + m + '.' + (+p + 1);
1246
- } else {
1247
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
1248
- ' <' + M + '.' + (+m + 1) + '.0';
1249
- }
1250
- } else {
1251
- ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
1252
- ' <' + (+M + 1) + '.0.0';
1253
- }
1254
- } else {
1255
- debug('no pr');
1256
- if (M === '0') {
1257
- if (m === '0') {
1258
- ret = '>=' + M + '.' + m + '.' + p +
1259
- ' <' + M + '.' + m + '.' + (+p + 1);
1260
- } else {
1261
- ret = '>=' + M + '.' + m + '.' + p +
1262
- ' <' + M + '.' + (+m + 1) + '.0';
1263
- }
1264
- } else {
1265
- ret = '>=' + M + '.' + m + '.' + p +
1266
- ' <' + (+M + 1) + '.0.0';
1267
- }
1268
- }
1269
-
1270
- debug('caret return', ret);
1271
- return ret
1272
- })
1273
- }
1274
-
1275
- function replaceXRanges (comp, options) {
1276
- debug('replaceXRanges', comp, options);
1277
- return comp.split(/\s+/).map(function (comp) {
1278
- return replaceXRange(comp, options)
1279
- }).join(' ')
1280
- }
1281
-
1282
- function replaceXRange (comp, options) {
1283
- comp = comp.trim();
1284
- var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
1285
- return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
1286
- debug('xRange', comp, ret, gtlt, M, m, p, pr);
1287
- var xM = isX(M);
1288
- var xm = xM || isX(m);
1289
- var xp = xm || isX(p);
1290
- var anyX = xp;
1291
-
1292
- if (gtlt === '=' && anyX) {
1293
- gtlt = '';
1294
- }
1295
-
1296
- // if we're including prereleases in the match, then we need
1297
- // to fix this to -0, the lowest possible prerelease value
1298
- pr = options.includePrerelease ? '-0' : '';
1299
-
1300
- if (xM) {
1301
- if (gtlt === '>' || gtlt === '<') {
1302
- // nothing is allowed
1303
- ret = '<0.0.0-0';
1304
- } else {
1305
- // nothing is forbidden
1306
- ret = '*';
1307
- }
1308
- } else if (gtlt && anyX) {
1309
- // we know patch is an x, because we have any x at all.
1310
- // replace X with 0
1311
- if (xm) {
1312
- m = 0;
1313
- }
1314
- p = 0;
1315
-
1316
- if (gtlt === '>') {
1317
- // >1 => >=2.0.0
1318
- // >1.2 => >=1.3.0
1319
- // >1.2.3 => >= 1.2.4
1320
- gtlt = '>=';
1321
- if (xm) {
1322
- M = +M + 1;
1323
- m = 0;
1324
- p = 0;
1325
- } else {
1326
- m = +m + 1;
1327
- p = 0;
1328
- }
1329
- } else if (gtlt === '<=') {
1330
- // <=0.7.x is actually <0.8.0, since any 0.7.x should
1331
- // pass. Similarly, <=7.x is actually <8.0.0, etc.
1332
- gtlt = '<';
1333
- if (xm) {
1334
- M = +M + 1;
1335
- } else {
1336
- m = +m + 1;
1337
- }
1338
- }
1339
-
1340
- ret = gtlt + M + '.' + m + '.' + p + pr;
1341
- } else if (xm) {
1342
- ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr;
1343
- } else if (xp) {
1344
- ret = '>=' + M + '.' + m + '.0' + pr +
1345
- ' <' + M + '.' + (+m + 1) + '.0' + pr;
1346
- }
1347
-
1348
- debug('xRange return', ret);
1349
-
1350
- return ret
1351
- })
1352
- }
1353
-
1354
- // Because * is AND-ed with everything else in the comparator,
1355
- // and '' means "any version", just remove the *s entirely.
1356
- function replaceStars (comp, options) {
1357
- debug('replaceStars', comp, options);
1358
- // Looseness is ignored here. star is always as loose as it gets!
1359
- return comp.trim().replace(re[t.STAR], '')
1360
- }
1361
-
1362
- // This function is passed to string.replace(re[t.HYPHENRANGE])
1363
- // M, m, patch, prerelease, build
1364
- // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
1365
- // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
1366
- // 1.2 - 3.4 => >=1.2.0 <3.5.0
1367
- function hyphenReplace ($0,
1368
- from, fM, fm, fp, fpr, fb,
1369
- to, tM, tm, tp, tpr, tb) {
1370
- if (isX(fM)) {
1371
- from = '';
1372
- } else if (isX(fm)) {
1373
- from = '>=' + fM + '.0.0';
1374
- } else if (isX(fp)) {
1375
- from = '>=' + fM + '.' + fm + '.0';
1376
- } else {
1377
- from = '>=' + from;
1378
- }
1379
-
1380
- if (isX(tM)) {
1381
- to = '';
1382
- } else if (isX(tm)) {
1383
- to = '<' + (+tM + 1) + '.0.0';
1384
- } else if (isX(tp)) {
1385
- to = '<' + tM + '.' + (+tm + 1) + '.0';
1386
- } else if (tpr) {
1387
- to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
1388
- } else {
1389
- to = '<=' + to;
1390
- }
1391
-
1392
- return (from + ' ' + to).trim()
1393
- }
1394
-
1395
- // if ANY of the sets match ALL of its comparators, then pass
1396
- Range.prototype.test = function (version) {
1397
- if (!version) {
1398
- return false
1399
- }
1400
-
1401
- if (typeof version === 'string') {
1402
- try {
1403
- version = new SemVer(version, this.options);
1404
- } catch (er) {
1405
- return false
1406
- }
1407
- }
1408
-
1409
- for (var i = 0; i < this.set.length; i++) {
1410
- if (testSet(this.set[i], version, this.options)) {
1411
- return true
1412
- }
1413
- }
1414
- return false
1415
- };
1416
-
1417
- function testSet (set, version, options) {
1418
- for (var i = 0; i < set.length; i++) {
1419
- if (!set[i].test(version)) {
1420
- return false
1421
- }
1422
- }
1423
-
1424
- if (version.prerelease.length && !options.includePrerelease) {
1425
- // Find the set of versions that are allowed to have prereleases
1426
- // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
1427
- // That should allow `1.2.3-pr.2` to pass.
1428
- // However, `1.2.4-alpha.notready` should NOT be allowed,
1429
- // even though it's within the range set by the comparators.
1430
- for (i = 0; i < set.length; i++) {
1431
- debug(set[i].semver);
1432
- if (set[i].semver === ANY) {
1433
- continue
1434
- }
1435
-
1436
- if (set[i].semver.prerelease.length > 0) {
1437
- var allowed = set[i].semver;
1438
- if (allowed.major === version.major &&
1439
- allowed.minor === version.minor &&
1440
- allowed.patch === version.patch) {
1441
- return true
1442
- }
1443
- }
1444
- }
1445
-
1446
- // Version has a -pre, but it's not one of the ones we like.
1447
- return false
1448
- }
1449
-
1450
- return true
1451
- }
1452
-
1453
- exports.satisfies = satisfies;
1454
- function satisfies (version, range, options) {
1455
- try {
1456
- range = new Range(range, options);
1457
- } catch (er) {
1458
- return false
1459
- }
1460
- return range.test(version)
1461
- }
1462
-
1463
- exports.maxSatisfying = maxSatisfying;
1464
- function maxSatisfying (versions, range, options) {
1465
- var max = null;
1466
- var maxSV = null;
1467
- try {
1468
- var rangeObj = new Range(range, options);
1469
- } catch (er) {
1470
- return null
1471
- }
1472
- versions.forEach(function (v) {
1473
- if (rangeObj.test(v)) {
1474
- // satisfies(v, range, options)
1475
- if (!max || maxSV.compare(v) === -1) {
1476
- // compare(max, v, true)
1477
- max = v;
1478
- maxSV = new SemVer(max, options);
1479
- }
1480
- }
1481
- });
1482
- return max
1483
- }
1484
-
1485
- exports.minSatisfying = minSatisfying;
1486
- function minSatisfying (versions, range, options) {
1487
- var min = null;
1488
- var minSV = null;
1489
- try {
1490
- var rangeObj = new Range(range, options);
1491
- } catch (er) {
1492
- return null
1493
- }
1494
- versions.forEach(function (v) {
1495
- if (rangeObj.test(v)) {
1496
- // satisfies(v, range, options)
1497
- if (!min || minSV.compare(v) === 1) {
1498
- // compare(min, v, true)
1499
- min = v;
1500
- minSV = new SemVer(min, options);
1501
- }
1502
- }
1503
- });
1504
- return min
1505
- }
1506
-
1507
- exports.minVersion = minVersion;
1508
- function minVersion (range, loose) {
1509
- range = new Range(range, loose);
1510
-
1511
- var minver = new SemVer('0.0.0');
1512
- if (range.test(minver)) {
1513
- return minver
1514
- }
1515
-
1516
- minver = new SemVer('0.0.0-0');
1517
- if (range.test(minver)) {
1518
- return minver
1519
- }
1520
-
1521
- minver = null;
1522
- for (var i = 0; i < range.set.length; ++i) {
1523
- var comparators = range.set[i];
1524
-
1525
- comparators.forEach(function (comparator) {
1526
- // Clone to avoid manipulating the comparator's semver object.
1527
- var compver = new SemVer(comparator.semver.version);
1528
- switch (comparator.operator) {
1529
- case '>':
1530
- if (compver.prerelease.length === 0) {
1531
- compver.patch++;
1532
- } else {
1533
- compver.prerelease.push(0);
1534
- }
1535
- compver.raw = compver.format();
1536
- /* fallthrough */
1537
- case '':
1538
- case '>=':
1539
- if (!minver || gt(minver, compver)) {
1540
- minver = compver;
1541
- }
1542
- break
1543
- case '<':
1544
- case '<=':
1545
- /* Ignore maximum versions */
1546
- break
1547
- /* istanbul ignore next */
1548
- default:
1549
- throw new Error('Unexpected operation: ' + comparator.operator)
1550
- }
1551
- });
1552
- }
1553
-
1554
- if (minver && range.test(minver)) {
1555
- return minver
1556
- }
1557
-
1558
- return null
1559
- }
1560
-
1561
- exports.validRange = validRange;
1562
- function validRange (range, options) {
1563
- try {
1564
- // Return '*' instead of '' so that truthiness works.
1565
- // This will throw if it's invalid anyway
1566
- return new Range(range, options).range || '*'
1567
- } catch (er) {
1568
- return null
1569
- }
1570
- }
1571
-
1572
- // Determine if version is less than all the versions possible in the range
1573
- exports.ltr = ltr;
1574
- function ltr (version, range, options) {
1575
- return outside(version, range, '<', options)
1576
- }
1577
-
1578
- // Determine if version is greater than all the versions possible in the range.
1579
- exports.gtr = gtr;
1580
- function gtr (version, range, options) {
1581
- return outside(version, range, '>', options)
1582
- }
1583
-
1584
- exports.outside = outside;
1585
- function outside (version, range, hilo, options) {
1586
- version = new SemVer(version, options);
1587
- range = new Range(range, options);
1588
-
1589
- var gtfn, ltefn, ltfn, comp, ecomp;
1590
- switch (hilo) {
1591
- case '>':
1592
- gtfn = gt;
1593
- ltefn = lte;
1594
- ltfn = lt;
1595
- comp = '>';
1596
- ecomp = '>=';
1597
- break
1598
- case '<':
1599
- gtfn = lt;
1600
- ltefn = gte;
1601
- ltfn = gt;
1602
- comp = '<';
1603
- ecomp = '<=';
1604
- break
1605
- default:
1606
- throw new TypeError('Must provide a hilo val of "<" or ">"')
1607
- }
1608
-
1609
- // If it satisifes the range it is not outside
1610
- if (satisfies(version, range, options)) {
1611
- return false
1612
- }
1613
-
1614
- // From now on, variable terms are as if we're in "gtr" mode.
1615
- // but note that everything is flipped for the "ltr" function.
1616
-
1617
- for (var i = 0; i < range.set.length; ++i) {
1618
- var comparators = range.set[i];
1619
-
1620
- var high = null;
1621
- var low = null;
1622
-
1623
- comparators.forEach(function (comparator) {
1624
- if (comparator.semver === ANY) {
1625
- comparator = new Comparator('>=0.0.0');
1626
- }
1627
- high = high || comparator;
1628
- low = low || comparator;
1629
- if (gtfn(comparator.semver, high.semver, options)) {
1630
- high = comparator;
1631
- } else if (ltfn(comparator.semver, low.semver, options)) {
1632
- low = comparator;
1633
- }
1634
- });
1635
-
1636
- // If the edge version comparator has a operator then our version
1637
- // isn't outside it
1638
- if (high.operator === comp || high.operator === ecomp) {
1639
- return false
1640
- }
1641
-
1642
- // If the lowest version comparator has an operator and our version
1643
- // is less than it then it isn't higher than the range
1644
- if ((!low.operator || low.operator === comp) &&
1645
- ltefn(version, low.semver)) {
1646
- return false
1647
- } else if (low.operator === ecomp && ltfn(version, low.semver)) {
1648
- return false
1649
- }
1650
- }
1651
- return true
1652
- }
1653
-
1654
- exports.prerelease = prerelease;
1655
- function prerelease (version, options) {
1656
- var parsed = parse(version, options);
1657
- return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
1658
- }
1659
-
1660
- exports.intersects = intersects;
1661
- function intersects (r1, r2, options) {
1662
- r1 = new Range(r1, options);
1663
- r2 = new Range(r2, options);
1664
- return r1.intersects(r2)
1665
- }
1666
-
1667
- exports.coerce = coerce;
1668
- function coerce (version, options) {
1669
- if (version instanceof SemVer) {
1670
- return version
1671
- }
1672
-
1673
- if (typeof version === 'number') {
1674
- version = String(version);
1675
- }
1676
-
1677
- if (typeof version !== 'string') {
1678
- return null
1679
- }
1680
-
1681
- options = options || {};
1682
-
1683
- var match = null;
1684
- if (!options.rtl) {
1685
- match = version.match(re[t.COERCE]);
1686
- } else {
1687
- // Find the right-most coercible string that does not share
1688
- // a terminus with a more left-ward coercible string.
1689
- // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
1690
- //
1691
- // Walk through the string checking with a /g regexp
1692
- // Manually set the index so as to pick up overlapping matches.
1693
- // Stop when we get a match that ends at the string end, since no
1694
- // coercible string can be more right-ward without the same terminus.
1695
- var next;
1696
- while ((next = re[t.COERCERTL].exec(version)) &&
1697
- (!match || match.index + match[0].length !== version.length)
1698
- ) {
1699
- if (!match ||
1700
- next.index + next[0].length !== match.index + match[0].length) {
1701
- match = next;
1702
- }
1703
- re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
1704
- }
1705
- // leave it in a clean state
1706
- re[t.COERCERTL].lastIndex = -1;
1707
- }
1708
-
1709
- if (match === null) {
1710
- return null
1711
- }
1712
-
1713
- return parse(match[2] +
1714
- '.' + (match[3] || '0') +
1715
- '.' + (match[4] || '0'), options)
1716
- }
1717
- });
1718
-
1719
- const {promisify} = util__default['default'];
1720
-
1721
-
1722
- const useNativeRecursiveOption = semver.satisfies(process.version, '>=10.12.0');
1723
-
1724
- // https://github.com/nodejs/node/issues/8987
1725
- // https://github.com/libuv/libuv/pull/1088
1726
- const checkPath = pth => {
1727
- if (process.platform === 'win32') {
1728
- const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path__default['default'].parse(pth).root, ''));
1729
-
1730
- if (pathHasInvalidWinCharacters) {
1731
- const error = new Error(`Path contains invalid characters: ${pth}`);
1732
- error.code = 'EINVAL';
1733
- throw error;
1734
- }
1735
- }
1736
- };
1737
-
1738
- const processOptions = options => {
1739
- // https://github.com/sindresorhus/make-dir/issues/18
1740
- const defaults = {
1741
- mode: 0o777,
1742
- fs: fs__default['default']
1743
- };
1744
-
1745
- return {
1746
- ...defaults,
1747
- ...options
1748
- };
1749
- };
1750
-
1751
- const permissionError = pth => {
1752
- // This replicates the exception of `fs.mkdir` with native the
1753
- // `recusive` option when run on an invalid drive under Windows.
1754
- const error = new Error(`operation not permitted, mkdir '${pth}'`);
1755
- error.code = 'EPERM';
1756
- error.errno = -4048;
1757
- error.path = pth;
1758
- error.syscall = 'mkdir';
1759
- return error;
1760
- };
1761
-
1762
- const makeDir = async (input, options) => {
1763
- checkPath(input);
1764
- options = processOptions(options);
1765
-
1766
- const mkdir = promisify(options.fs.mkdir);
1767
- const stat = promisify(options.fs.stat);
1768
-
1769
- if (useNativeRecursiveOption && options.fs.mkdir === fs__default['default'].mkdir) {
1770
- const pth = path__default['default'].resolve(input);
1771
-
1772
- await mkdir(pth, {
1773
- mode: options.mode,
1774
- recursive: true
1775
- });
1776
-
1777
- return pth;
1778
- }
1779
-
1780
- const make = async pth => {
1781
- try {
1782
- await mkdir(pth, options.mode);
1783
-
1784
- return pth;
1785
- } catch (error) {
1786
- if (error.code === 'EPERM') {
1787
- throw error;
1788
- }
1789
-
1790
- if (error.code === 'ENOENT') {
1791
- if (path__default['default'].dirname(pth) === pth) {
1792
- throw permissionError(pth);
1793
- }
1794
-
1795
- if (error.message.includes('null bytes')) {
1796
- throw error;
1797
- }
1798
-
1799
- await make(path__default['default'].dirname(pth));
1800
-
1801
- return make(pth);
1802
- }
1803
-
1804
- try {
1805
- const stats = await stat(pth);
1806
- if (!stats.isDirectory()) {
1807
- throw new Error('The path is not a directory');
1808
- }
1809
- } catch (_) {
1810
- throw error;
1811
- }
1812
-
1813
- return pth;
1814
- }
1815
- };
1816
-
1817
- return make(path__default['default'].resolve(input));
1818
- };
1819
-
1820
- var makeDir_1 = makeDir;
1821
-
1822
- var sync = (input, options) => {
1823
- checkPath(input);
1824
- options = processOptions(options);
1825
-
1826
- if (useNativeRecursiveOption && options.fs.mkdirSync === fs__default['default'].mkdirSync) {
1827
- const pth = path__default['default'].resolve(input);
1828
-
1829
- fs__default['default'].mkdirSync(pth, {
1830
- mode: options.mode,
1831
- recursive: true
1832
- });
1833
-
1834
- return pth;
1835
- }
1836
-
1837
- const make = pth => {
1838
- try {
1839
- options.fs.mkdirSync(pth, options.mode);
1840
- } catch (error) {
1841
- if (error.code === 'EPERM') {
1842
- throw error;
1843
- }
1844
-
1845
- if (error.code === 'ENOENT') {
1846
- if (path__default['default'].dirname(pth) === pth) {
1847
- throw permissionError(pth);
1848
- }
1849
-
1850
- if (error.message.includes('null bytes')) {
1851
- throw error;
1852
- }
1853
-
1854
- make(path__default['default'].dirname(pth));
1855
- return make(pth);
1856
- }
1857
-
1858
- try {
1859
- if (!options.fs.statSync(pth).isDirectory()) {
1860
- throw new Error('The path is not a directory');
1861
- }
1862
- } catch (_) {
1863
- throw error;
1864
- }
1865
- }
1866
-
1867
- return pth;
1868
- };
1869
-
1870
- return make(path__default['default'].resolve(input));
1871
- };
1872
- makeDir_1.sync = sync;
1873
-
1874
- // imports
1875
-
1876
- // promisify
1877
- const writeFile = util__default['default'].promisify(fastWriteAtomic);
1878
- const readFile = util__default['default'].promisify(fs__default['default'].readFile);
1879
- const unlink$1 = util__default['default'].promisify(fs__default['default'].unlink);
1880
-
1881
- // U is the subset of T, not sure why
1882
- // this works or why _T is necessary
1883
-
1884
-
1885
-
1886
-
1887
-
1888
-
1889
-
1890
-
1891
-
1892
-
1893
- // valid default schema
1894
- const defaultSchema = {
1895
- last_reminder: 0,
1896
- cached_at: 0,
1897
- version: '',
1898
- cli_path: '',
1899
- // User output
1900
- output: {
1901
- client_event_id: '',
1902
- previous_client_event_id: '',
1903
- product: '',
1904
- cli_path_hash: '',
1905
- local_timestamp: '',
1906
- previous_version: '',
1907
- current_version: '',
1908
- current_release_date: 0,
1909
- current_download_url: '',
1910
- current_changelog_url: '',
1911
- package: '',
1912
- release_tag: '',
1913
- install_command: '',
1914
- project_website: '',
1915
- outdated: false,
1916
- alerts: [],
1917
- },
1918
- };
1919
-
1920
- // initialize the configuration
1921
- class Config {
1922
- static async new(state, schema = defaultSchema) {
1923
- await makeDir_1(path__default['default'].dirname(state.cache_file));
1924
- return new Config(state, schema)
1925
- }
1926
-
1927
- constructor( state, defaultSchema) {this.state = state;this.defaultSchema = defaultSchema;}
1928
-
1929
- // check and return the cache if (matches version or hasn't expired)
1930
- async checkCache(newState) {
1931
- const now = newState.now();
1932
- // fetch the data from the cache
1933
- const cache = await this.all();
1934
-
1935
- if (!cache) {
1936
- return { cache: undefined, stale: true }
1937
- }
1938
- // version has been upgraded or changed
1939
- // TODO: define this behaviour more clearly.
1940
- if (newState.version !== cache.version) {
1941
- return { cache, stale: true }
1942
- }
1943
- // cache expired
1944
- if (now - cache.cached_at > newState.cache_duration) {
1945
- return { cache, stale: true }
1946
- }
1947
- return { cache, stale: false }
1948
- }
1949
-
1950
- // set the configuration
1951
- async set(update) {
1952
- const existing = (await this.all()) || {};
1953
- const schema = Object.assign(existing, update);
1954
- // TODO: figure out how to type this
1955
- for (let k in this.defaultSchema) {
1956
- // @ts-ignore
1957
- if (typeof schema[k] === 'undefined') {
1958
- // @ts-ignore
1959
- schema[k] = this.defaultSchema[k];
1960
- }
1961
- }
1962
- await writeFile(this.state.cache_file, JSON.stringify(schema, null, ' '));
1963
- }
1964
-
1965
- // get the entire schema
1966
- async all() {
1967
- try {
1968
- const data = await readFile(this.state.cache_file, 'utf8');
1969
- return JSON.parse(data)
1970
- } catch (err) {
1971
- return
1972
- }
1973
- }
1974
-
1975
- // get a value from the schema
1976
- async get(key) {
1977
- const schema = await this.all();
1978
- if (typeof schema === 'undefined') {
1979
- return
1980
- }
1981
- return schema[key]
1982
- }
1983
-
1984
- // reset the configuration
1985
- async reset() {
1986
- await writeFile(this.state.cache_file, JSON.stringify(this.defaultSchema, null, ' '));
1987
- return
1988
- }
1989
-
1990
- // delete the configuration, ignoring any errors
1991
- async delete() {
1992
- try {
1993
- await unlink$1(this.state.cache_file);
1994
- return
1995
- } catch (err) {
1996
- return
1997
- }
1998
- }
1999
- }
2000
-
2001
- const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
2002
-
2003
- let poolPtr = rnds8Pool.length;
2004
- function rng() {
2005
- if (poolPtr > rnds8Pool.length - 16) {
2006
- crypto__default['default'].randomFillSync(rnds8Pool);
2007
- poolPtr = 0;
2008
- }
2009
-
2010
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
2011
- }
2012
-
2013
- var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
2014
-
2015
- function validate(uuid) {
2016
- return typeof uuid === 'string' && REGEX.test(uuid);
2017
- }
2018
-
2019
- /**
2020
- * Convert array of 16 byte values to UUID string format of the form:
2021
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
2022
- */
2023
-
2024
- const byteToHex = [];
2025
-
2026
- for (let i = 0; i < 256; ++i) {
2027
- byteToHex.push((i + 0x100).toString(16).substr(1));
2028
- }
2029
-
2030
- function stringify(arr, offset = 0) {
2031
- // Note: Be careful editing this code! It's been tuned for performance
2032
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
2033
- const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
2034
- // of the following:
2035
- // - One or more input array values don't map to a hex octet (leading to
2036
- // "undefined" in the uuid)
2037
- // - Invalid input values for the RFC `version` or `variant` fields
2038
-
2039
- if (!validate(uuid)) {
2040
- throw TypeError('Stringified UUID is invalid');
2041
- }
2042
-
2043
- return uuid;
2044
- }
2045
-
2046
- function v4(options, buf, offset) {
2047
- options = options || {};
2048
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
2049
-
2050
- rnds[6] = rnds[6] & 0x0f | 0x40;
2051
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
2052
-
2053
- if (buf) {
2054
- offset = offset || 0;
2055
-
2056
- for (let i = 0; i < 16; ++i) {
2057
- buf[offset + i] = rnds[i];
2058
- }
2059
-
2060
- return buf;
2061
- }
2062
-
2063
- return stringify(rnds);
2064
- }
2065
-
2066
- const homedir = os__default['default'].homedir();
2067
- const tmpdir = os__default['default'].tmpdir();
2068
- const {env} = process;
2069
-
2070
- const macos = name => {
2071
- const library = path__default['default'].join(homedir, 'Library');
2072
-
2073
- return {
2074
- data: path__default['default'].join(library, 'Application Support', name),
2075
- config: path__default['default'].join(library, 'Preferences', name),
2076
- cache: path__default['default'].join(library, 'Caches', name),
2077
- log: path__default['default'].join(library, 'Logs', name),
2078
- temp: path__default['default'].join(tmpdir, name)
2079
- };
2080
- };
2081
-
2082
- const windows = name => {
2083
- const appData = env.APPDATA || path__default['default'].join(homedir, 'AppData', 'Roaming');
2084
- const localAppData = env.LOCALAPPDATA || path__default['default'].join(homedir, 'AppData', 'Local');
2085
-
2086
- return {
2087
- // Data/config/cache/log are invented by me as Windows isn't opinionated about this
2088
- data: path__default['default'].join(localAppData, name, 'Data'),
2089
- config: path__default['default'].join(appData, name, 'Config'),
2090
- cache: path__default['default'].join(localAppData, name, 'Cache'),
2091
- log: path__default['default'].join(localAppData, name, 'Log'),
2092
- temp: path__default['default'].join(tmpdir, name)
2093
- };
2094
- };
2095
-
2096
- // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
2097
- const linux = name => {
2098
- const username = path__default['default'].basename(homedir);
2099
-
2100
- return {
2101
- data: path__default['default'].join(env.XDG_DATA_HOME || path__default['default'].join(homedir, '.local', 'share'), name),
2102
- config: path__default['default'].join(env.XDG_CONFIG_HOME || path__default['default'].join(homedir, '.config'), name),
2103
- cache: path__default['default'].join(env.XDG_CACHE_HOME || path__default['default'].join(homedir, '.cache'), name),
2104
- // https://wiki.debian.org/XDGBaseDirectorySpecification#state
2105
- log: path__default['default'].join(env.XDG_STATE_HOME || path__default['default'].join(homedir, '.local', 'state'), name),
2106
- temp: path__default['default'].join(tmpdir, username, name)
2107
- };
2108
- };
2109
-
2110
- const envPaths = (name, options) => {
2111
- if (typeof name !== 'string') {
2112
- throw new TypeError(`Expected string, got ${typeof name}`);
2113
- }
2114
-
2115
- options = Object.assign({suffix: 'nodejs'}, options);
2116
-
2117
- if (options.suffix) {
2118
- // Add suffix to prevent possible conflict with native apps
2119
- name += `-${options.suffix}`;
2120
- }
2121
-
2122
- if (process.platform === 'darwin') {
2123
- return macos(name);
2124
- }
2125
-
2126
- if (process.platform === 'win32') {
2127
- return windows(name);
2128
- }
2129
-
2130
- return linux(name);
2131
- };
2132
-
2133
- var envPaths_1 = envPaths;
2134
- // TODO: Remove this for the next major release
2135
- var _default = envPaths;
2136
- envPaths_1.default = _default;
2137
-
2138
- // Signature is a random signature that is stored and used
2139
-
2140
- const exists = util.promisify(fs__default['default'].exists);
2141
- const readFile$1 = util.promisify(fs__default['default'].readFile);
2142
- const writeFile$1 = util.promisify(fastWriteAtomic);
2143
-
2144
-
2145
-
2146
-
2147
-
2148
- // File identifier for the new global signature file
2149
- const PRISMA_SIGNATURE = 'signature';
2150
- const PRISMA_CACHE_FILE = 'prisma';
2151
-
2152
- // IMPORTANT: this is part of the public API
2153
- async function getSignature(signatureFile, cacheFile) {
2154
- const dirs = envPaths_1(`checkpoint`);
2155
- cacheFile = cacheFile || path__default['default'].join(dirs.cache, PRISMA_CACHE_FILE); // Old schema file
2156
- signatureFile = signatureFile || path__default['default'].join(dirs.cache, PRISMA_SIGNATURE); // new file for signature
2157
-
2158
- if (await exists(signatureFile)) {
2159
- // The signatureFile replaces cacheFile as the source of turth and therefore takes precedence
2160
- const signature = await readSignature(signatureFile);
2161
- if (signature) {
2162
- return signature
2163
- }
2164
- }
2165
-
2166
- if (await exists(cacheFile)) {
2167
- const signature = await readSignature(cacheFile);
2168
- if (signature) {
2169
- // Found config file with valid signature – migrate signature to new file
2170
- await createSignatureFile(signatureFile, signature);
2171
- return signature
2172
- }
2173
- }
2174
-
2175
- return await createSignatureFile(signatureFile)
2176
- }
2177
-
2178
- function isSignatureValid(signature) {
2179
- return typeof signature === 'string' && signature.length === 36
2180
- }
2181
-
2182
- /**
2183
- * Parse a file containing json and return the `signature` key from it
2184
- * @returns string empty if invalid or not found
2185
- */
2186
- async function readSignature(file) {
2187
- try {
2188
- const data = await readFile$1(file, 'utf8');
2189
- const { signature } = JSON.parse(data);
2190
- if (isSignatureValid(signature)) {
2191
- return signature
2192
- }
2193
- return ''
2194
- } catch (err) {
2195
- return ''
2196
- }
2197
- }
2198
-
2199
- async function createSignatureFile(signatureFile, signature) {
2200
- // Use passed signature or generate new
2201
- const signatureState = {
2202
- signature: signature || v4(),
2203
- };
2204
- await makeDir_1(path__default['default'].dirname(signatureFile));
2205
- await writeFile$1(signatureFile, JSON.stringify(signatureState, null, ' '));
2206
- return signatureState.signature
2207
- }
2208
-
2209
- // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
2210
-
2211
- // fix for "Readable" isn't a named export issue
2212
- const Readable = Stream__default['default'].Readable;
2213
-
2214
- const BUFFER = Symbol('buffer');
2215
- const TYPE = Symbol('type');
2216
-
2217
- class Blob {
2218
- constructor() {
2219
- this[TYPE] = '';
2220
-
2221
- const blobParts = arguments[0];
2222
- const options = arguments[1];
2223
-
2224
- const buffers = [];
2225
- let size = 0;
2226
-
2227
- if (blobParts) {
2228
- const a = blobParts;
2229
- const length = Number(a.length);
2230
- for (let i = 0; i < length; i++) {
2231
- const element = a[i];
2232
- let buffer;
2233
- if (element instanceof Buffer) {
2234
- buffer = element;
2235
- } else if (ArrayBuffer.isView(element)) {
2236
- buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
2237
- } else if (element instanceof ArrayBuffer) {
2238
- buffer = Buffer.from(element);
2239
- } else if (element instanceof Blob) {
2240
- buffer = element[BUFFER];
2241
- } else {
2242
- buffer = Buffer.from(typeof element === 'string' ? element : String(element));
2243
- }
2244
- size += buffer.length;
2245
- buffers.push(buffer);
2246
- }
2247
- }
2248
-
2249
- this[BUFFER] = Buffer.concat(buffers);
2250
-
2251
- let type = options && options.type !== undefined && String(options.type).toLowerCase();
2252
- if (type && !/[^\u0020-\u007E]/.test(type)) {
2253
- this[TYPE] = type;
2254
- }
2255
- }
2256
- get size() {
2257
- return this[BUFFER].length;
2258
- }
2259
- get type() {
2260
- return this[TYPE];
2261
- }
2262
- text() {
2263
- return Promise.resolve(this[BUFFER].toString());
2264
- }
2265
- arrayBuffer() {
2266
- const buf = this[BUFFER];
2267
- const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
2268
- return Promise.resolve(ab);
2269
- }
2270
- stream() {
2271
- const readable = new Readable();
2272
- readable._read = function () {};
2273
- readable.push(this[BUFFER]);
2274
- readable.push(null);
2275
- return readable;
2276
- }
2277
- toString() {
2278
- return '[object Blob]';
2279
- }
2280
- slice() {
2281
- const size = this.size;
2282
-
2283
- const start = arguments[0];
2284
- const end = arguments[1];
2285
- let relativeStart, relativeEnd;
2286
- if (start === undefined) {
2287
- relativeStart = 0;
2288
- } else if (start < 0) {
2289
- relativeStart = Math.max(size + start, 0);
2290
- } else {
2291
- relativeStart = Math.min(start, size);
2292
- }
2293
- if (end === undefined) {
2294
- relativeEnd = size;
2295
- } else if (end < 0) {
2296
- relativeEnd = Math.max(size + end, 0);
2297
- } else {
2298
- relativeEnd = Math.min(end, size);
2299
- }
2300
- const span = Math.max(relativeEnd - relativeStart, 0);
2301
-
2302
- const buffer = this[BUFFER];
2303
- const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
2304
- const blob = new Blob([], { type: arguments[2] });
2305
- blob[BUFFER] = slicedBuffer;
2306
- return blob;
2307
- }
2308
- }
2309
-
2310
- Object.defineProperties(Blob.prototype, {
2311
- size: { enumerable: true },
2312
- type: { enumerable: true },
2313
- slice: { enumerable: true }
2314
- });
2315
-
2316
- Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
2317
- value: 'Blob',
2318
- writable: false,
2319
- enumerable: false,
2320
- configurable: true
2321
- });
2322
-
2323
- /**
2324
- * fetch-error.js
2325
- *
2326
- * FetchError interface for operational errors
2327
- */
2328
-
2329
- /**
2330
- * Create FetchError instance
2331
- *
2332
- * @param String message Error message for human
2333
- * @param String type Error type for machine
2334
- * @param String systemError For Node.js system error
2335
- * @return FetchError
2336
- */
2337
- function FetchError(message, type, systemError) {
2338
- Error.call(this, message);
2339
-
2340
- this.message = message;
2341
- this.type = type;
2342
-
2343
- // when err.type is `system`, err.code contains system error code
2344
- if (systemError) {
2345
- this.code = this.errno = systemError.code;
2346
- }
2347
-
2348
- // hide custom error implementation details from end-users
2349
- Error.captureStackTrace(this, this.constructor);
2350
- }
2351
-
2352
- FetchError.prototype = Object.create(Error.prototype);
2353
- FetchError.prototype.constructor = FetchError;
2354
- FetchError.prototype.name = 'FetchError';
2355
-
2356
- let convert;
2357
- try {
2358
- convert = require('encoding').convert;
2359
- } catch (e) {}
2360
-
2361
- const INTERNALS = Symbol('Body internals');
2362
-
2363
- // fix an issue where "PassThrough" isn't a named export for node <10
2364
- const PassThrough = Stream__default['default'].PassThrough;
2365
-
2366
- /**
2367
- * Body mixin
2368
- *
2369
- * Ref: https://fetch.spec.whatwg.org/#body
2370
- *
2371
- * @param Stream body Readable stream
2372
- * @param Object opts Response options
2373
- * @return Void
2374
- */
2375
- function Body(body) {
2376
- var _this = this;
2377
-
2378
- var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
2379
- _ref$size = _ref.size;
2380
-
2381
- let size = _ref$size === undefined ? 0 : _ref$size;
2382
- var _ref$timeout = _ref.timeout;
2383
- let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
2384
-
2385
- if (body == null) {
2386
- // body is undefined or null
2387
- body = null;
2388
- } else if (isURLSearchParams(body)) {
2389
- // body is a URLSearchParams
2390
- body = Buffer.from(body.toString());
2391
- } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
2392
- // body is ArrayBuffer
2393
- body = Buffer.from(body);
2394
- } else if (ArrayBuffer.isView(body)) {
2395
- // body is ArrayBufferView
2396
- body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
2397
- } else if (body instanceof Stream__default['default']) ; else {
2398
- // none of the above
2399
- // coerce to string then buffer
2400
- body = Buffer.from(String(body));
2401
- }
2402
- this[INTERNALS] = {
2403
- body,
2404
- disturbed: false,
2405
- error: null
2406
- };
2407
- this.size = size;
2408
- this.timeout = timeout;
2409
-
2410
- if (body instanceof Stream__default['default']) {
2411
- body.on('error', function (err) {
2412
- const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
2413
- _this[INTERNALS].error = error;
2414
- });
2415
- }
2416
- }
2417
-
2418
- Body.prototype = {
2419
- get body() {
2420
- return this[INTERNALS].body;
2421
- },
2422
-
2423
- get bodyUsed() {
2424
- return this[INTERNALS].disturbed;
2425
- },
2426
-
2427
- /**
2428
- * Decode response as ArrayBuffer
2429
- *
2430
- * @return Promise
2431
- */
2432
- arrayBuffer() {
2433
- return consumeBody.call(this).then(function (buf) {
2434
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
2435
- });
2436
- },
2437
-
2438
- /**
2439
- * Return raw response as Blob
2440
- *
2441
- * @return Promise
2442
- */
2443
- blob() {
2444
- let ct = this.headers && this.headers.get('content-type') || '';
2445
- return consumeBody.call(this).then(function (buf) {
2446
- return Object.assign(
2447
- // Prevent copying
2448
- new Blob([], {
2449
- type: ct.toLowerCase()
2450
- }), {
2451
- [BUFFER]: buf
2452
- });
2453
- });
2454
- },
2455
-
2456
- /**
2457
- * Decode response as json
2458
- *
2459
- * @return Promise
2460
- */
2461
- json() {
2462
- var _this2 = this;
2463
-
2464
- return consumeBody.call(this).then(function (buffer) {
2465
- try {
2466
- return JSON.parse(buffer.toString());
2467
- } catch (err) {
2468
- return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
2469
- }
2470
- });
2471
- },
2472
-
2473
- /**
2474
- * Decode response as text
2475
- *
2476
- * @return Promise
2477
- */
2478
- text() {
2479
- return consumeBody.call(this).then(function (buffer) {
2480
- return buffer.toString();
2481
- });
2482
- },
2483
-
2484
- /**
2485
- * Decode response as buffer (non-spec api)
2486
- *
2487
- * @return Promise
2488
- */
2489
- buffer() {
2490
- return consumeBody.call(this);
2491
- },
2492
-
2493
- /**
2494
- * Decode response as text, while automatically detecting the encoding and
2495
- * trying to decode to UTF-8 (non-spec api)
2496
- *
2497
- * @return Promise
2498
- */
2499
- textConverted() {
2500
- var _this3 = this;
2501
-
2502
- return consumeBody.call(this).then(function (buffer) {
2503
- return convertBody(buffer, _this3.headers);
2504
- });
2505
- }
2506
- };
2507
-
2508
- // In browsers, all properties are enumerable.
2509
- Object.defineProperties(Body.prototype, {
2510
- body: { enumerable: true },
2511
- bodyUsed: { enumerable: true },
2512
- arrayBuffer: { enumerable: true },
2513
- blob: { enumerable: true },
2514
- json: { enumerable: true },
2515
- text: { enumerable: true }
2516
- });
2517
-
2518
- Body.mixIn = function (proto) {
2519
- for (const name of Object.getOwnPropertyNames(Body.prototype)) {
2520
- // istanbul ignore else: future proof
2521
- if (!(name in proto)) {
2522
- const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
2523
- Object.defineProperty(proto, name, desc);
2524
- }
2525
- }
2526
- };
2527
-
2528
- /**
2529
- * Consume and convert an entire Body to a Buffer.
2530
- *
2531
- * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
2532
- *
2533
- * @return Promise
2534
- */
2535
- function consumeBody() {
2536
- var _this4 = this;
2537
-
2538
- if (this[INTERNALS].disturbed) {
2539
- return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
2540
- }
2541
-
2542
- this[INTERNALS].disturbed = true;
2543
-
2544
- if (this[INTERNALS].error) {
2545
- return Body.Promise.reject(this[INTERNALS].error);
2546
- }
2547
-
2548
- let body = this.body;
2549
-
2550
- // body is null
2551
- if (body === null) {
2552
- return Body.Promise.resolve(Buffer.alloc(0));
2553
- }
2554
-
2555
- // body is blob
2556
- if (isBlob(body)) {
2557
- body = body.stream();
2558
- }
2559
-
2560
- // body is buffer
2561
- if (Buffer.isBuffer(body)) {
2562
- return Body.Promise.resolve(body);
2563
- }
2564
-
2565
- // istanbul ignore if: should never happen
2566
- if (!(body instanceof Stream__default['default'])) {
2567
- return Body.Promise.resolve(Buffer.alloc(0));
2568
- }
2569
-
2570
- // body is stream
2571
- // get ready to actually consume the body
2572
- let accum = [];
2573
- let accumBytes = 0;
2574
- let abort = false;
2575
-
2576
- return new Body.Promise(function (resolve, reject) {
2577
- let resTimeout;
2578
-
2579
- // allow timeout on slow response body
2580
- if (_this4.timeout) {
2581
- resTimeout = setTimeout(function () {
2582
- abort = true;
2583
- reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
2584
- }, _this4.timeout);
2585
- }
2586
-
2587
- // handle stream errors
2588
- body.on('error', function (err) {
2589
- if (err.name === 'AbortError') {
2590
- // if the request was aborted, reject with this Error
2591
- abort = true;
2592
- reject(err);
2593
- } else {
2594
- // other errors, such as incorrect content-encoding
2595
- reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
2596
- }
2597
- });
2598
-
2599
- body.on('data', function (chunk) {
2600
- if (abort || chunk === null) {
2601
- return;
2602
- }
2603
-
2604
- if (_this4.size && accumBytes + chunk.length > _this4.size) {
2605
- abort = true;
2606
- reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
2607
- return;
2608
- }
2609
-
2610
- accumBytes += chunk.length;
2611
- accum.push(chunk);
2612
- });
2613
-
2614
- body.on('end', function () {
2615
- if (abort) {
2616
- return;
2617
- }
2618
-
2619
- clearTimeout(resTimeout);
2620
-
2621
- try {
2622
- resolve(Buffer.concat(accum, accumBytes));
2623
- } catch (err) {
2624
- // handle streams that have accumulated too much data (issue #414)
2625
- reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
2626
- }
2627
- });
2628
- });
2629
- }
2630
-
2631
- /**
2632
- * Detect buffer encoding and convert to target encoding
2633
- * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
2634
- *
2635
- * @param Buffer buffer Incoming buffer
2636
- * @param String encoding Target encoding
2637
- * @return String
2638
- */
2639
- function convertBody(buffer, headers) {
2640
- if (typeof convert !== 'function') {
2641
- throw new Error('The package `encoding` must be installed to use the textConverted() function');
2642
- }
2643
-
2644
- const ct = headers.get('content-type');
2645
- let charset = 'utf-8';
2646
- let res, str;
2647
-
2648
- // header
2649
- if (ct) {
2650
- res = /charset=([^;]*)/i.exec(ct);
2651
- }
2652
-
2653
- // no charset in content type, peek at response body for at most 1024 bytes
2654
- str = buffer.slice(0, 1024).toString();
2655
-
2656
- // html5
2657
- if (!res && str) {
2658
- res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
2659
- }
2660
-
2661
- // html4
2662
- if (!res && str) {
2663
- res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
2664
- if (!res) {
2665
- res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
2666
- if (res) {
2667
- res.pop(); // drop last quote
2668
- }
2669
- }
2670
-
2671
- if (res) {
2672
- res = /charset=(.*)/i.exec(res.pop());
2673
- }
2674
- }
2675
-
2676
- // xml
2677
- if (!res && str) {
2678
- res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
2679
- }
2680
-
2681
- // found charset
2682
- if (res) {
2683
- charset = res.pop();
2684
-
2685
- // prevent decode issues when sites use incorrect encoding
2686
- // ref: https://hsivonen.fi/encoding-menu/
2687
- if (charset === 'gb2312' || charset === 'gbk') {
2688
- charset = 'gb18030';
2689
- }
2690
- }
2691
-
2692
- // turn raw buffers into a single utf-8 buffer
2693
- return convert(buffer, 'UTF-8', charset).toString();
2694
- }
2695
-
2696
- /**
2697
- * Detect a URLSearchParams object
2698
- * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
2699
- *
2700
- * @param Object obj Object to detect by type or brand
2701
- * @return String
2702
- */
2703
- function isURLSearchParams(obj) {
2704
- // Duck-typing as a necessary condition.
2705
- if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
2706
- return false;
2707
- }
2708
-
2709
- // Brand-checking and more duck-typing as optional condition.
2710
- return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
2711
- }
2712
-
2713
- /**
2714
- * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
2715
- * @param {*} obj
2716
- * @return {boolean}
2717
- */
2718
- function isBlob(obj) {
2719
- return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
2720
- }
2721
-
2722
- /**
2723
- * Clone body given Res/Req instance
2724
- *
2725
- * @param Mixed instance Response or Request instance
2726
- * @return Mixed
2727
- */
2728
- function clone(instance) {
2729
- let p1, p2;
2730
- let body = instance.body;
2731
-
2732
- // don't allow cloning a used body
2733
- if (instance.bodyUsed) {
2734
- throw new Error('cannot clone body after it is used');
2735
- }
2736
-
2737
- // check that body is a stream and not form-data object
2738
- // note: we can't clone the form-data object without having it as a dependency
2739
- if (body instanceof Stream__default['default'] && typeof body.getBoundary !== 'function') {
2740
- // tee instance body
2741
- p1 = new PassThrough();
2742
- p2 = new PassThrough();
2743
- body.pipe(p1);
2744
- body.pipe(p2);
2745
- // set instance body to teed body and return the other teed body
2746
- instance[INTERNALS].body = p1;
2747
- body = p2;
2748
- }
2749
-
2750
- return body;
2751
- }
2752
-
2753
- /**
2754
- * Performs the operation "extract a `Content-Type` value from |object|" as
2755
- * specified in the specification:
2756
- * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
2757
- *
2758
- * This function assumes that instance.body is present.
2759
- *
2760
- * @param Mixed instance Any options.body input
2761
- */
2762
- function extractContentType(body) {
2763
- if (body === null) {
2764
- // body is null
2765
- return null;
2766
- } else if (typeof body === 'string') {
2767
- // body is string
2768
- return 'text/plain;charset=UTF-8';
2769
- } else if (isURLSearchParams(body)) {
2770
- // body is a URLSearchParams
2771
- return 'application/x-www-form-urlencoded;charset=UTF-8';
2772
- } else if (isBlob(body)) {
2773
- // body is blob
2774
- return body.type || null;
2775
- } else if (Buffer.isBuffer(body)) {
2776
- // body is buffer
2777
- return null;
2778
- } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
2779
- // body is ArrayBuffer
2780
- return null;
2781
- } else if (ArrayBuffer.isView(body)) {
2782
- // body is ArrayBufferView
2783
- return null;
2784
- } else if (typeof body.getBoundary === 'function') {
2785
- // detect form data input from form-data module
2786
- return `multipart/form-data;boundary=${body.getBoundary()}`;
2787
- } else if (body instanceof Stream__default['default']) {
2788
- // body is stream
2789
- // can't really do much about this
2790
- return null;
2791
- } else {
2792
- // Body constructor defaults other things to string
2793
- return 'text/plain;charset=UTF-8';
2794
- }
2795
- }
2796
-
2797
- /**
2798
- * The Fetch Standard treats this as if "total bytes" is a property on the body.
2799
- * For us, we have to explicitly get it with a function.
2800
- *
2801
- * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
2802
- *
2803
- * @param Body instance Instance of Body
2804
- * @return Number? Number of bytes, or null if not possible
2805
- */
2806
- function getTotalBytes(instance) {
2807
- const body = instance.body;
2808
-
2809
-
2810
- if (body === null) {
2811
- // body is null
2812
- return 0;
2813
- } else if (isBlob(body)) {
2814
- return body.size;
2815
- } else if (Buffer.isBuffer(body)) {
2816
- // body is buffer
2817
- return body.length;
2818
- } else if (body && typeof body.getLengthSync === 'function') {
2819
- // detect form data input from form-data module
2820
- if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
2821
- body.hasKnownLength && body.hasKnownLength()) {
2822
- // 2.x
2823
- return body.getLengthSync();
2824
- }
2825
- return null;
2826
- } else {
2827
- // body is stream
2828
- return null;
2829
- }
2830
- }
2831
-
2832
- /**
2833
- * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
2834
- *
2835
- * @param Body instance Instance of Body
2836
- * @return Void
2837
- */
2838
- function writeToStream(dest, instance) {
2839
- const body = instance.body;
2840
-
2841
-
2842
- if (body === null) {
2843
- // body is null
2844
- dest.end();
2845
- } else if (isBlob(body)) {
2846
- body.stream().pipe(dest);
2847
- } else if (Buffer.isBuffer(body)) {
2848
- // body is buffer
2849
- dest.write(body);
2850
- dest.end();
2851
- } else {
2852
- // body is stream
2853
- body.pipe(dest);
2854
- }
2855
- }
2856
-
2857
- // expose Promise
2858
- Body.Promise = global.Promise;
2859
-
2860
- /**
2861
- * headers.js
2862
- *
2863
- * Headers class offers convenient helpers
2864
- */
2865
-
2866
- const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
2867
- const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
2868
-
2869
- function validateName(name) {
2870
- name = `${name}`;
2871
- if (invalidTokenRegex.test(name) || name === '') {
2872
- throw new TypeError(`${name} is not a legal HTTP header name`);
2873
- }
2874
- }
2875
-
2876
- function validateValue(value) {
2877
- value = `${value}`;
2878
- if (invalidHeaderCharRegex.test(value)) {
2879
- throw new TypeError(`${value} is not a legal HTTP header value`);
2880
- }
2881
- }
2882
-
2883
- /**
2884
- * Find the key in the map object given a header name.
2885
- *
2886
- * Returns undefined if not found.
2887
- *
2888
- * @param String name Header name
2889
- * @return String|Undefined
2890
- */
2891
- function find(map, name) {
2892
- name = name.toLowerCase();
2893
- for (const key in map) {
2894
- if (key.toLowerCase() === name) {
2895
- return key;
2896
- }
2897
- }
2898
- return undefined;
2899
- }
2900
-
2901
- const MAP = Symbol('map');
2902
- class Headers {
2903
- /**
2904
- * Headers class
2905
- *
2906
- * @param Object headers Response headers
2907
- * @return Void
2908
- */
2909
- constructor() {
2910
- let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
2911
-
2912
- this[MAP] = Object.create(null);
2913
-
2914
- if (init instanceof Headers) {
2915
- const rawHeaders = init.raw();
2916
- const headerNames = Object.keys(rawHeaders);
2917
-
2918
- for (const headerName of headerNames) {
2919
- for (const value of rawHeaders[headerName]) {
2920
- this.append(headerName, value);
2921
- }
2922
- }
2923
-
2924
- return;
2925
- }
2926
-
2927
- // We don't worry about converting prop to ByteString here as append()
2928
- // will handle it.
2929
- if (init == null) ; else if (typeof init === 'object') {
2930
- const method = init[Symbol.iterator];
2931
- if (method != null) {
2932
- if (typeof method !== 'function') {
2933
- throw new TypeError('Header pairs must be iterable');
2934
- }
2935
-
2936
- // sequence<sequence<ByteString>>
2937
- // Note: per spec we have to first exhaust the lists then process them
2938
- const pairs = [];
2939
- for (const pair of init) {
2940
- if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
2941
- throw new TypeError('Each header pair must be iterable');
2942
- }
2943
- pairs.push(Array.from(pair));
2944
- }
2945
-
2946
- for (const pair of pairs) {
2947
- if (pair.length !== 2) {
2948
- throw new TypeError('Each header pair must be a name/value tuple');
2949
- }
2950
- this.append(pair[0], pair[1]);
2951
- }
2952
- } else {
2953
- // record<ByteString, ByteString>
2954
- for (const key of Object.keys(init)) {
2955
- const value = init[key];
2956
- this.append(key, value);
2957
- }
2958
- }
2959
- } else {
2960
- throw new TypeError('Provided initializer must be an object');
2961
- }
2962
- }
2963
-
2964
- /**
2965
- * Return combined header value given name
2966
- *
2967
- * @param String name Header name
2968
- * @return Mixed
2969
- */
2970
- get(name) {
2971
- name = `${name}`;
2972
- validateName(name);
2973
- const key = find(this[MAP], name);
2974
- if (key === undefined) {
2975
- return null;
2976
- }
2977
-
2978
- return this[MAP][key].join(', ');
2979
- }
2980
-
2981
- /**
2982
- * Iterate over all headers
2983
- *
2984
- * @param Function callback Executed for each item with parameters (value, name, thisArg)
2985
- * @param Boolean thisArg `this` context for callback function
2986
- * @return Void
2987
- */
2988
- forEach(callback) {
2989
- let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
2990
-
2991
- let pairs = getHeaders(this);
2992
- let i = 0;
2993
- while (i < pairs.length) {
2994
- var _pairs$i = pairs[i];
2995
- const name = _pairs$i[0],
2996
- value = _pairs$i[1];
2997
-
2998
- callback.call(thisArg, value, name, this);
2999
- pairs = getHeaders(this);
3000
- i++;
3001
- }
3002
- }
3003
-
3004
- /**
3005
- * Overwrite header values given name
3006
- *
3007
- * @param String name Header name
3008
- * @param String value Header value
3009
- * @return Void
3010
- */
3011
- set(name, value) {
3012
- name = `${name}`;
3013
- value = `${value}`;
3014
- validateName(name);
3015
- validateValue(value);
3016
- const key = find(this[MAP], name);
3017
- this[MAP][key !== undefined ? key : name] = [value];
3018
- }
3019
-
3020
- /**
3021
- * Append a value onto existing header
3022
- *
3023
- * @param String name Header name
3024
- * @param String value Header value
3025
- * @return Void
3026
- */
3027
- append(name, value) {
3028
- name = `${name}`;
3029
- value = `${value}`;
3030
- validateName(name);
3031
- validateValue(value);
3032
- const key = find(this[MAP], name);
3033
- if (key !== undefined) {
3034
- this[MAP][key].push(value);
3035
- } else {
3036
- this[MAP][name] = [value];
3037
- }
3038
- }
3039
-
3040
- /**
3041
- * Check for header name existence
3042
- *
3043
- * @param String name Header name
3044
- * @return Boolean
3045
- */
3046
- has(name) {
3047
- name = `${name}`;
3048
- validateName(name);
3049
- return find(this[MAP], name) !== undefined;
3050
- }
3051
-
3052
- /**
3053
- * Delete all header values given name
3054
- *
3055
- * @param String name Header name
3056
- * @return Void
3057
- */
3058
- delete(name) {
3059
- name = `${name}`;
3060
- validateName(name);
3061
- const key = find(this[MAP], name);
3062
- if (key !== undefined) {
3063
- delete this[MAP][key];
3064
- }
3065
- }
3066
-
3067
- /**
3068
- * Return raw headers (non-spec api)
3069
- *
3070
- * @return Object
3071
- */
3072
- raw() {
3073
- return this[MAP];
3074
- }
3075
-
3076
- /**
3077
- * Get an iterator on keys.
3078
- *
3079
- * @return Iterator
3080
- */
3081
- keys() {
3082
- return createHeadersIterator(this, 'key');
3083
- }
3084
-
3085
- /**
3086
- * Get an iterator on values.
3087
- *
3088
- * @return Iterator
3089
- */
3090
- values() {
3091
- return createHeadersIterator(this, 'value');
3092
- }
3093
-
3094
- /**
3095
- * Get an iterator on entries.
3096
- *
3097
- * This is the default iterator of the Headers object.
3098
- *
3099
- * @return Iterator
3100
- */
3101
- [Symbol.iterator]() {
3102
- return createHeadersIterator(this, 'key+value');
3103
- }
3104
- }
3105
- Headers.prototype.entries = Headers.prototype[Symbol.iterator];
3106
-
3107
- Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
3108
- value: 'Headers',
3109
- writable: false,
3110
- enumerable: false,
3111
- configurable: true
3112
- });
3113
-
3114
- Object.defineProperties(Headers.prototype, {
3115
- get: { enumerable: true },
3116
- forEach: { enumerable: true },
3117
- set: { enumerable: true },
3118
- append: { enumerable: true },
3119
- has: { enumerable: true },
3120
- delete: { enumerable: true },
3121
- keys: { enumerable: true },
3122
- values: { enumerable: true },
3123
- entries: { enumerable: true }
3124
- });
3125
-
3126
- function getHeaders(headers) {
3127
- let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
3128
-
3129
- const keys = Object.keys(headers[MAP]).sort();
3130
- return keys.map(kind === 'key' ? function (k) {
3131
- return k.toLowerCase();
3132
- } : kind === 'value' ? function (k) {
3133
- return headers[MAP][k].join(', ');
3134
- } : function (k) {
3135
- return [k.toLowerCase(), headers[MAP][k].join(', ')];
3136
- });
3137
- }
3138
-
3139
- const INTERNAL = Symbol('internal');
3140
-
3141
- function createHeadersIterator(target, kind) {
3142
- const iterator = Object.create(HeadersIteratorPrototype);
3143
- iterator[INTERNAL] = {
3144
- target,
3145
- kind,
3146
- index: 0
3147
- };
3148
- return iterator;
3149
- }
3150
-
3151
- const HeadersIteratorPrototype = Object.setPrototypeOf({
3152
- next() {
3153
- // istanbul ignore if
3154
- if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
3155
- throw new TypeError('Value of `this` is not a HeadersIterator');
3156
- }
3157
-
3158
- var _INTERNAL = this[INTERNAL];
3159
- const target = _INTERNAL.target,
3160
- kind = _INTERNAL.kind,
3161
- index = _INTERNAL.index;
3162
-
3163
- const values = getHeaders(target, kind);
3164
- const len = values.length;
3165
- if (index >= len) {
3166
- return {
3167
- value: undefined,
3168
- done: true
3169
- };
3170
- }
3171
-
3172
- this[INTERNAL].index = index + 1;
3173
-
3174
- return {
3175
- value: values[index],
3176
- done: false
3177
- };
3178
- }
3179
- }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
3180
-
3181
- Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
3182
- value: 'HeadersIterator',
3183
- writable: false,
3184
- enumerable: false,
3185
- configurable: true
3186
- });
3187
-
3188
- /**
3189
- * Export the Headers object in a form that Node.js can consume.
3190
- *
3191
- * @param Headers headers
3192
- * @return Object
3193
- */
3194
- function exportNodeCompatibleHeaders(headers) {
3195
- const obj = Object.assign({ __proto__: null }, headers[MAP]);
3196
-
3197
- // http.request() only supports string as Host header. This hack makes
3198
- // specifying custom Host header possible.
3199
- const hostHeaderKey = find(headers[MAP], 'Host');
3200
- if (hostHeaderKey !== undefined) {
3201
- obj[hostHeaderKey] = obj[hostHeaderKey][0];
3202
- }
3203
-
3204
- return obj;
3205
- }
3206
-
3207
- /**
3208
- * Create a Headers object from an object of headers, ignoring those that do
3209
- * not conform to HTTP grammar productions.
3210
- *
3211
- * @param Object obj Object of headers
3212
- * @return Headers
3213
- */
3214
- function createHeadersLenient(obj) {
3215
- const headers = new Headers();
3216
- for (const name of Object.keys(obj)) {
3217
- if (invalidTokenRegex.test(name)) {
3218
- continue;
3219
- }
3220
- if (Array.isArray(obj[name])) {
3221
- for (const val of obj[name]) {
3222
- if (invalidHeaderCharRegex.test(val)) {
3223
- continue;
3224
- }
3225
- if (headers[MAP][name] === undefined) {
3226
- headers[MAP][name] = [val];
3227
- } else {
3228
- headers[MAP][name].push(val);
3229
- }
3230
- }
3231
- } else if (!invalidHeaderCharRegex.test(obj[name])) {
3232
- headers[MAP][name] = [obj[name]];
3233
- }
3234
- }
3235
- return headers;
3236
- }
3237
-
3238
- const INTERNALS$1 = Symbol('Response internals');
3239
-
3240
- // fix an issue where "STATUS_CODES" aren't a named export for node <10
3241
- const STATUS_CODES = http__default['default'].STATUS_CODES;
3242
-
3243
- /**
3244
- * Response class
3245
- *
3246
- * @param Stream body Readable stream
3247
- * @param Object opts Response options
3248
- * @return Void
3249
- */
3250
- class Response {
3251
- constructor() {
3252
- let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
3253
- let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3254
-
3255
- Body.call(this, body, opts);
3256
-
3257
- const status = opts.status || 200;
3258
- const headers = new Headers(opts.headers);
3259
-
3260
- if (body != null && !headers.has('Content-Type')) {
3261
- const contentType = extractContentType(body);
3262
- if (contentType) {
3263
- headers.append('Content-Type', contentType);
3264
- }
3265
- }
3266
-
3267
- this[INTERNALS$1] = {
3268
- url: opts.url,
3269
- status,
3270
- statusText: opts.statusText || STATUS_CODES[status],
3271
- headers,
3272
- counter: opts.counter
3273
- };
3274
- }
3275
-
3276
- get url() {
3277
- return this[INTERNALS$1].url || '';
3278
- }
3279
-
3280
- get status() {
3281
- return this[INTERNALS$1].status;
3282
- }
3283
-
3284
- /**
3285
- * Convenience property representing if the request ended normally
3286
- */
3287
- get ok() {
3288
- return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
3289
- }
3290
-
3291
- get redirected() {
3292
- return this[INTERNALS$1].counter > 0;
3293
- }
3294
-
3295
- get statusText() {
3296
- return this[INTERNALS$1].statusText;
3297
- }
3298
-
3299
- get headers() {
3300
- return this[INTERNALS$1].headers;
3301
- }
3302
-
3303
- /**
3304
- * Clone this response
3305
- *
3306
- * @return Response
3307
- */
3308
- clone() {
3309
- return new Response(clone(this), {
3310
- url: this.url,
3311
- status: this.status,
3312
- statusText: this.statusText,
3313
- headers: this.headers,
3314
- ok: this.ok,
3315
- redirected: this.redirected
3316
- });
3317
- }
3318
- }
3319
-
3320
- Body.mixIn(Response.prototype);
3321
-
3322
- Object.defineProperties(Response.prototype, {
3323
- url: { enumerable: true },
3324
- status: { enumerable: true },
3325
- ok: { enumerable: true },
3326
- redirected: { enumerable: true },
3327
- statusText: { enumerable: true },
3328
- headers: { enumerable: true },
3329
- clone: { enumerable: true }
3330
- });
3331
-
3332
- Object.defineProperty(Response.prototype, Symbol.toStringTag, {
3333
- value: 'Response',
3334
- writable: false,
3335
- enumerable: false,
3336
- configurable: true
3337
- });
3338
-
3339
- const INTERNALS$2 = Symbol('Request internals');
3340
-
3341
- // fix an issue where "format", "parse" aren't a named export for node <10
3342
- const parse_url = Url__default['default'].parse;
3343
- const format_url = Url__default['default'].format;
3344
-
3345
- const streamDestructionSupported = 'destroy' in Stream__default['default'].Readable.prototype;
3346
-
3347
- /**
3348
- * Check if a value is an instance of Request.
3349
- *
3350
- * @param Mixed input
3351
- * @return Boolean
3352
- */
3353
- function isRequest(input) {
3354
- return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
3355
- }
3356
-
3357
- function isAbortSignal(signal) {
3358
- const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
3359
- return !!(proto && proto.constructor.name === 'AbortSignal');
3360
- }
3361
-
3362
- /**
3363
- * Request class
3364
- *
3365
- * @param Mixed input Url or Request instance
3366
- * @param Object init Custom options
3367
- * @return Void
3368
- */
3369
- class Request {
3370
- constructor(input) {
3371
- let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3372
-
3373
- let parsedURL;
3374
-
3375
- // normalize input
3376
- if (!isRequest(input)) {
3377
- if (input && input.href) {
3378
- // in order to support Node.js' Url objects; though WHATWG's URL objects
3379
- // will fall into this branch also (since their `toString()` will return
3380
- // `href` property anyway)
3381
- parsedURL = parse_url(input.href);
3382
- } else {
3383
- // coerce input to a string before attempting to parse
3384
- parsedURL = parse_url(`${input}`);
3385
- }
3386
- input = {};
3387
- } else {
3388
- parsedURL = parse_url(input.url);
3389
- }
3390
-
3391
- let method = init.method || input.method || 'GET';
3392
- method = method.toUpperCase();
3393
-
3394
- if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
3395
- throw new TypeError('Request with GET/HEAD method cannot have body');
3396
- }
3397
-
3398
- let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
3399
-
3400
- Body.call(this, inputBody, {
3401
- timeout: init.timeout || input.timeout || 0,
3402
- size: init.size || input.size || 0
3403
- });
3404
-
3405
- const headers = new Headers(init.headers || input.headers || {});
3406
-
3407
- if (inputBody != null && !headers.has('Content-Type')) {
3408
- const contentType = extractContentType(inputBody);
3409
- if (contentType) {
3410
- headers.append('Content-Type', contentType);
3411
- }
3412
- }
3413
-
3414
- let signal = isRequest(input) ? input.signal : null;
3415
- if ('signal' in init) signal = init.signal;
3416
-
3417
- if (signal != null && !isAbortSignal(signal)) {
3418
- throw new TypeError('Expected signal to be an instanceof AbortSignal');
3419
- }
3420
-
3421
- this[INTERNALS$2] = {
3422
- method,
3423
- redirect: init.redirect || input.redirect || 'follow',
3424
- headers,
3425
- parsedURL,
3426
- signal
3427
- };
3428
-
3429
- // node-fetch-only options
3430
- this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
3431
- this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
3432
- this.counter = init.counter || input.counter || 0;
3433
- this.agent = init.agent || input.agent;
3434
- }
3435
-
3436
- get method() {
3437
- return this[INTERNALS$2].method;
3438
- }
3439
-
3440
- get url() {
3441
- return format_url(this[INTERNALS$2].parsedURL);
3442
- }
3443
-
3444
- get headers() {
3445
- return this[INTERNALS$2].headers;
3446
- }
3447
-
3448
- get redirect() {
3449
- return this[INTERNALS$2].redirect;
3450
- }
3451
-
3452
- get signal() {
3453
- return this[INTERNALS$2].signal;
3454
- }
3455
-
3456
- /**
3457
- * Clone this request
3458
- *
3459
- * @return Request
3460
- */
3461
- clone() {
3462
- return new Request(this);
3463
- }
3464
- }
3465
-
3466
- Body.mixIn(Request.prototype);
3467
-
3468
- Object.defineProperty(Request.prototype, Symbol.toStringTag, {
3469
- value: 'Request',
3470
- writable: false,
3471
- enumerable: false,
3472
- configurable: true
3473
- });
3474
-
3475
- Object.defineProperties(Request.prototype, {
3476
- method: { enumerable: true },
3477
- url: { enumerable: true },
3478
- headers: { enumerable: true },
3479
- redirect: { enumerable: true },
3480
- clone: { enumerable: true },
3481
- signal: { enumerable: true }
3482
- });
3483
-
3484
- /**
3485
- * Convert a Request to Node.js http request options.
3486
- *
3487
- * @param Request A Request instance
3488
- * @return Object The options object to be passed to http.request
3489
- */
3490
- function getNodeRequestOptions(request) {
3491
- const parsedURL = request[INTERNALS$2].parsedURL;
3492
- const headers = new Headers(request[INTERNALS$2].headers);
3493
-
3494
- // fetch step 1.3
3495
- if (!headers.has('Accept')) {
3496
- headers.set('Accept', '*/*');
3497
- }
3498
-
3499
- // Basic fetch
3500
- if (!parsedURL.protocol || !parsedURL.hostname) {
3501
- throw new TypeError('Only absolute URLs are supported');
3502
- }
3503
-
3504
- if (!/^https?:$/.test(parsedURL.protocol)) {
3505
- throw new TypeError('Only HTTP(S) protocols are supported');
3506
- }
3507
-
3508
- if (request.signal && request.body instanceof Stream__default['default'].Readable && !streamDestructionSupported) {
3509
- throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
3510
- }
3511
-
3512
- // HTTP-network-or-cache fetch steps 2.4-2.7
3513
- let contentLengthValue = null;
3514
- if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
3515
- contentLengthValue = '0';
3516
- }
3517
- if (request.body != null) {
3518
- const totalBytes = getTotalBytes(request);
3519
- if (typeof totalBytes === 'number') {
3520
- contentLengthValue = String(totalBytes);
3521
- }
3522
- }
3523
- if (contentLengthValue) {
3524
- headers.set('Content-Length', contentLengthValue);
3525
- }
3526
-
3527
- // HTTP-network-or-cache fetch step 2.11
3528
- if (!headers.has('User-Agent')) {
3529
- headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
3530
- }
3531
-
3532
- // HTTP-network-or-cache fetch step 2.15
3533
- if (request.compress && !headers.has('Accept-Encoding')) {
3534
- headers.set('Accept-Encoding', 'gzip,deflate');
3535
- }
3536
-
3537
- let agent = request.agent;
3538
- if (typeof agent === 'function') {
3539
- agent = agent(parsedURL);
3540
- }
3541
-
3542
- if (!headers.has('Connection') && !agent) {
3543
- headers.set('Connection', 'close');
3544
- }
3545
-
3546
- // HTTP-network fetch step 4.2
3547
- // chunked encoding is handled by Node.js
3548
-
3549
- return Object.assign({}, parsedURL, {
3550
- method: request.method,
3551
- headers: exportNodeCompatibleHeaders(headers),
3552
- agent
3553
- });
3554
- }
3555
-
3556
- /**
3557
- * abort-error.js
3558
- *
3559
- * AbortError interface for cancelled requests
3560
- */
3561
-
3562
- /**
3563
- * Create AbortError instance
3564
- *
3565
- * @param String message Error message for human
3566
- * @return AbortError
3567
- */
3568
- function AbortError(message) {
3569
- Error.call(this, message);
3570
-
3571
- this.type = 'aborted';
3572
- this.message = message;
3573
-
3574
- // hide custom error implementation details from end-users
3575
- Error.captureStackTrace(this, this.constructor);
3576
- }
3577
-
3578
- AbortError.prototype = Object.create(Error.prototype);
3579
- AbortError.prototype.constructor = AbortError;
3580
- AbortError.prototype.name = 'AbortError';
3581
-
3582
- // fix an issue where "PassThrough", "resolve" aren't a named export for node <10
3583
- const PassThrough$1 = Stream__default['default'].PassThrough;
3584
- const resolve_url = Url__default['default'].resolve;
3585
-
3586
- /**
3587
- * Fetch function
3588
- *
3589
- * @param Mixed url Absolute url or Request instance
3590
- * @param Object opts Fetch options
3591
- * @return Promise
3592
- */
3593
- function fetch(url, opts) {
3594
-
3595
- // allow custom promise
3596
- if (!fetch.Promise) {
3597
- throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
3598
- }
3599
-
3600
- Body.Promise = fetch.Promise;
3601
-
3602
- // wrap http.request into fetch
3603
- return new fetch.Promise(function (resolve, reject) {
3604
- // build request object
3605
- const request = new Request(url, opts);
3606
- const options = getNodeRequestOptions(request);
3607
-
3608
- const send = (options.protocol === 'https:' ? https__default['default'] : http__default['default']).request;
3609
- const signal = request.signal;
3610
-
3611
- let response = null;
3612
-
3613
- const abort = function abort() {
3614
- let error = new AbortError('The user aborted a request.');
3615
- reject(error);
3616
- if (request.body && request.body instanceof Stream__default['default'].Readable) {
3617
- request.body.destroy(error);
3618
- }
3619
- if (!response || !response.body) return;
3620
- response.body.emit('error', error);
3621
- };
3622
-
3623
- if (signal && signal.aborted) {
3624
- abort();
3625
- return;
3626
- }
3627
-
3628
- const abortAndFinalize = function abortAndFinalize() {
3629
- abort();
3630
- finalize();
3631
- };
3632
-
3633
- // send request
3634
- const req = send(options);
3635
- let reqTimeout;
3636
-
3637
- if (signal) {
3638
- signal.addEventListener('abort', abortAndFinalize);
3639
- }
3640
-
3641
- function finalize() {
3642
- req.abort();
3643
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
3644
- clearTimeout(reqTimeout);
3645
- }
3646
-
3647
- if (request.timeout) {
3648
- req.once('socket', function (socket) {
3649
- reqTimeout = setTimeout(function () {
3650
- reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
3651
- finalize();
3652
- }, request.timeout);
3653
- });
3654
- }
3655
-
3656
- req.on('error', function (err) {
3657
- reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
3658
- finalize();
3659
- });
3660
-
3661
- req.on('response', function (res) {
3662
- clearTimeout(reqTimeout);
3663
-
3664
- const headers = createHeadersLenient(res.headers);
3665
-
3666
- // HTTP fetch step 5
3667
- if (fetch.isRedirect(res.statusCode)) {
3668
- // HTTP fetch step 5.2
3669
- const location = headers.get('Location');
3670
-
3671
- // HTTP fetch step 5.3
3672
- const locationURL = location === null ? null : resolve_url(request.url, location);
3673
-
3674
- // HTTP fetch step 5.5
3675
- switch (request.redirect) {
3676
- case 'error':
3677
- reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
3678
- finalize();
3679
- return;
3680
- case 'manual':
3681
- // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
3682
- if (locationURL !== null) {
3683
- // handle corrupted header
3684
- try {
3685
- headers.set('Location', locationURL);
3686
- } catch (err) {
3687
- // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
3688
- reject(err);
3689
- }
3690
- }
3691
- break;
3692
- case 'follow':
3693
- // HTTP-redirect fetch step 2
3694
- if (locationURL === null) {
3695
- break;
3696
- }
3697
-
3698
- // HTTP-redirect fetch step 5
3699
- if (request.counter >= request.follow) {
3700
- reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
3701
- finalize();
3702
- return;
3703
- }
3704
-
3705
- // HTTP-redirect fetch step 6 (counter increment)
3706
- // Create a new Request object.
3707
- const requestOpts = {
3708
- headers: new Headers(request.headers),
3709
- follow: request.follow,
3710
- counter: request.counter + 1,
3711
- agent: request.agent,
3712
- compress: request.compress,
3713
- method: request.method,
3714
- body: request.body,
3715
- signal: request.signal,
3716
- timeout: request.timeout,
3717
- size: request.size
3718
- };
3719
-
3720
- // HTTP-redirect fetch step 9
3721
- if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
3722
- reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
3723
- finalize();
3724
- return;
3725
- }
3726
-
3727
- // HTTP-redirect fetch step 11
3728
- if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
3729
- requestOpts.method = 'GET';
3730
- requestOpts.body = undefined;
3731
- requestOpts.headers.delete('content-length');
3732
- }
3733
-
3734
- // HTTP-redirect fetch step 15
3735
- resolve(fetch(new Request(locationURL, requestOpts)));
3736
- finalize();
3737
- return;
3738
- }
3739
- }
3740
-
3741
- // prepare response
3742
- res.once('end', function () {
3743
- if (signal) signal.removeEventListener('abort', abortAndFinalize);
3744
- });
3745
- let body = res.pipe(new PassThrough$1());
3746
-
3747
- const response_options = {
3748
- url: request.url,
3749
- status: res.statusCode,
3750
- statusText: res.statusMessage,
3751
- headers: headers,
3752
- size: request.size,
3753
- timeout: request.timeout,
3754
- counter: request.counter
3755
- };
3756
-
3757
- // HTTP-network fetch step 12.1.1.3
3758
- const codings = headers.get('Content-Encoding');
3759
-
3760
- // HTTP-network fetch step 12.1.1.4: handle content codings
3761
-
3762
- // in following scenarios we ignore compression support
3763
- // 1. compression support is disabled
3764
- // 2. HEAD request
3765
- // 3. no Content-Encoding header
3766
- // 4. no content response (204)
3767
- // 5. content not modified response (304)
3768
- if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
3769
- response = new Response(body, response_options);
3770
- resolve(response);
3771
- return;
3772
- }
3773
-
3774
- // For Node v6+
3775
- // Be less strict when decoding compressed responses, since sometimes
3776
- // servers send slightly invalid responses that are still accepted
3777
- // by common browsers.
3778
- // Always using Z_SYNC_FLUSH is what cURL does.
3779
- const zlibOptions = {
3780
- flush: zlib__default['default'].Z_SYNC_FLUSH,
3781
- finishFlush: zlib__default['default'].Z_SYNC_FLUSH
3782
- };
3783
-
3784
- // for gzip
3785
- if (codings == 'gzip' || codings == 'x-gzip') {
3786
- body = body.pipe(zlib__default['default'].createGunzip(zlibOptions));
3787
- response = new Response(body, response_options);
3788
- resolve(response);
3789
- return;
3790
- }
3791
-
3792
- // for deflate
3793
- if (codings == 'deflate' || codings == 'x-deflate') {
3794
- // handle the infamous raw deflate response from old servers
3795
- // a hack for old IIS and Apache servers
3796
- const raw = res.pipe(new PassThrough$1());
3797
- raw.once('data', function (chunk) {
3798
- // see http://stackoverflow.com/questions/37519828
3799
- if ((chunk[0] & 0x0F) === 0x08) {
3800
- body = body.pipe(zlib__default['default'].createInflate());
3801
- } else {
3802
- body = body.pipe(zlib__default['default'].createInflateRaw());
3803
- }
3804
- response = new Response(body, response_options);
3805
- resolve(response);
3806
- });
3807
- return;
3808
- }
3809
-
3810
- // for br
3811
- if (codings == 'br' && typeof zlib__default['default'].createBrotliDecompress === 'function') {
3812
- body = body.pipe(zlib__default['default'].createBrotliDecompress());
3813
- response = new Response(body, response_options);
3814
- resolve(response);
3815
- return;
3816
- }
3817
-
3818
- // otherwise, use response as-is
3819
- response = new Response(body, response_options);
3820
- resolve(response);
3821
- });
3822
-
3823
- writeToStream(req, request);
3824
- });
3825
- }
3826
- /**
3827
- * Redirect code matching
3828
- *
3829
- * @param Number code Status code
3830
- * @return Boolean
3831
- */
3832
- fetch.isRedirect = function (code) {
3833
- return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
3834
- };
3835
-
3836
- // expose Promise
3837
- fetch.Promise = global.Promise;
3838
-
3839
- /**
3840
- * Helpers.
3841
- */
3842
- var s = 1000;
3843
- var m = s * 60;
3844
- var h = m * 60;
3845
- var d = h * 24;
3846
- var w = d * 7;
3847
- var y = d * 365.25;
3848
-
3849
- /**
3850
- * Parse or format the given `val`.
3851
- *
3852
- * Options:
3853
- *
3854
- * - `long` verbose formatting [false]
3855
- *
3856
- * @param {String|Number} val
3857
- * @param {Object} [options]
3858
- * @throws {Error} throw an error if val is not a non-empty string or a number
3859
- * @return {String|Number}
3860
- * @api public
3861
- */
3862
-
3863
- var ms = function (val, options) {
3864
- options = options || {};
3865
- var type = typeof val;
3866
- if (type === 'string' && val.length > 0) {
3867
- return parse(val);
3868
- } else if (type === 'number' && isFinite(val)) {
3869
- return options.long ? fmtLong(val) : fmtShort(val);
3870
- }
3871
- throw new Error(
3872
- 'val is not a non-empty string or a valid number. val=' +
3873
- JSON.stringify(val)
3874
- );
3875
- };
3876
-
3877
- /**
3878
- * Parse the given `str` and return milliseconds.
3879
- *
3880
- * @param {String} str
3881
- * @return {Number}
3882
- * @api private
3883
- */
3884
-
3885
- function parse(str) {
3886
- str = String(str);
3887
- if (str.length > 100) {
3888
- return;
3889
- }
3890
- var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
3891
- str
3892
- );
3893
- if (!match) {
3894
- return;
3895
- }
3896
- var n = parseFloat(match[1]);
3897
- var type = (match[2] || 'ms').toLowerCase();
3898
- switch (type) {
3899
- case 'years':
3900
- case 'year':
3901
- case 'yrs':
3902
- case 'yr':
3903
- case 'y':
3904
- return n * y;
3905
- case 'weeks':
3906
- case 'week':
3907
- case 'w':
3908
- return n * w;
3909
- case 'days':
3910
- case 'day':
3911
- case 'd':
3912
- return n * d;
3913
- case 'hours':
3914
- case 'hour':
3915
- case 'hrs':
3916
- case 'hr':
3917
- case 'h':
3918
- return n * h;
3919
- case 'minutes':
3920
- case 'minute':
3921
- case 'mins':
3922
- case 'min':
3923
- case 'm':
3924
- return n * m;
3925
- case 'seconds':
3926
- case 'second':
3927
- case 'secs':
3928
- case 'sec':
3929
- case 's':
3930
- return n * s;
3931
- case 'milliseconds':
3932
- case 'millisecond':
3933
- case 'msecs':
3934
- case 'msec':
3935
- case 'ms':
3936
- return n;
3937
- default:
3938
- return undefined;
3939
- }
3940
- }
3941
-
3942
- /**
3943
- * Short format for `ms`.
3944
- *
3945
- * @param {Number} ms
3946
- * @return {String}
3947
- * @api private
3948
- */
3949
-
3950
- function fmtShort(ms) {
3951
- var msAbs = Math.abs(ms);
3952
- if (msAbs >= d) {
3953
- return Math.round(ms / d) + 'd';
3954
- }
3955
- if (msAbs >= h) {
3956
- return Math.round(ms / h) + 'h';
3957
- }
3958
- if (msAbs >= m) {
3959
- return Math.round(ms / m) + 'm';
3960
- }
3961
- if (msAbs >= s) {
3962
- return Math.round(ms / s) + 's';
3963
- }
3964
- return ms + 'ms';
3965
- }
3966
-
3967
- /**
3968
- * Long format for `ms`.
3969
- *
3970
- * @param {Number} ms
3971
- * @return {String}
3972
- * @api private
3973
- */
3974
-
3975
- function fmtLong(ms) {
3976
- var msAbs = Math.abs(ms);
3977
- if (msAbs >= d) {
3978
- return plural(ms, msAbs, d, 'day');
3979
- }
3980
- if (msAbs >= h) {
3981
- return plural(ms, msAbs, h, 'hour');
3982
- }
3983
- if (msAbs >= m) {
3984
- return plural(ms, msAbs, m, 'minute');
3985
- }
3986
- if (msAbs >= s) {
3987
- return plural(ms, msAbs, s, 'second');
3988
- }
3989
- return ms + ' ms';
3990
- }
3991
-
3992
- /**
3993
- * Pluralization helper.
3994
- */
3995
-
3996
- function plural(ms, msAbs, n, name) {
3997
- var isPlural = msAbs >= n * 1.5;
3998
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
3999
- }
4000
-
4001
- async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// imports
4002
-
4003
- // CHECK_VERSION is a hardcoded version of the current data structure.
4004
- // If something is breaking, this needs to be manually adapted.
4005
- const CHECK_VERSION = 4;
4006
-
4007
- // run main
4008
- main()
4009
- .then(() => process.exit(0))
4010
- .catch((err) => {
4011
- console.error(err);
4012
- process.exit(1);
4013
- });
4014
-
4015
- // main function
4016
- async function main() {
4017
- const state = JSON.parse(process.argv[2]);
4018
- await Promise.race([check(state), timeout(state.timeout)]);
4019
- }
4020
-
4021
- // check function
4022
- async function check(state) {
4023
- // make the cache file if we haven't already
4024
- const config = await Config.new(state);
4025
- // get the signature
4026
- const signature = await getSignature();
4027
-
4028
- const clientEventID = state.client_event_id || v4();
4029
-
4030
- // format the URL
4031
- const u = Url__default['default'].parse(state.endpoint, true);
4032
- const basepath = (u.pathname || '').replace(/\/$/, '');
4033
- u.pathname = `${basepath}/v1/check/${state.product}`;
4034
- u.query = {
4035
- checkpoint_version: CHECK_VERSION.toString(),
4036
- local_timestamp: state.local_timestamp,
4037
- information: state.information,
4038
- schema_providers: state.schema_providers,
4039
- schema_preview_features: state.schema_preview_features,
4040
- schema_generators_providers: state.schema_generators_providers,
4041
- command: state.command,
4042
- client_event_id: clientEventID,
4043
- signature,
4044
- project_hash: state.project_hash,
4045
- cli_path_hash: state.cli_path_hash,
4046
- arch: state.arch,
4047
- os: state.os,
4048
- node_version: state.node_version,
4049
- version: state.version,
4050
- ci: typeof state.ci !== 'undefined' ? String(state.ci) : undefined,
4051
- ci_name: state.ci_name || '',
4052
- cli_install_type: state.cli_install_type,
4053
- previous_client_event_id: await _asyncOptionalChain([(await config.get('output')), 'optionalAccess', async _ => _.client_event_id]),
4054
- check_if_update_available: String(state.check_if_update_available),
4055
- };
4056
-
4057
- // When env.CHECKPOINT_DEBUG_STDOUT !== undefined,
4058
- // print what would be sent to the telemetry server without actually sending it
4059
- if (process.env.CHECKPOINT_DEBUG_STDOUT !== undefined) {
4060
- process.stdout.write('[checkpoint-client] debug\n');
4061
- process.stdout.write(JSON.stringify(u, null, ' '));
4062
- return
4063
- }
4064
-
4065
- // send the request
4066
- const response = await fetch(Url__default['default'].format(u), {
4067
- method: 'get',
4068
- timeout: state.timeout,
4069
- headers: {
4070
- Accept: 'application/json',
4071
- 'User-Agent': 'prisma/js-checkpoint',
4072
- },
4073
- });
4074
- if (!response.ok) {
4075
- throw new Error(`checkpoint response error: ${response.status} ${response.statusText}`)
4076
- }
4077
- // read the response body
4078
- const output = await response.json();
4079
-
4080
- // create or update the configuration
4081
- // Only do so if there's a need to check if an update is available
4082
- // That is to say, if the cache is stale or doesn't exist
4083
- if (state.check_if_update_available) {
4084
- await config.set({
4085
- last_reminder: 0,
4086
- cached_at: Date.now(),
4087
- version: state.version,
4088
- cli_path: state.cli_path,
4089
- output,
4090
- });
4091
- }
4092
-
4093
- // write to process.stdout
4094
- process.stdout.write(JSON.stringify(output, null, ' '));
4095
- }
4096
-
4097
- // this should take a maximum of 5 seconds
4098
- async function timeout(millis) {
4099
- await sleep(millis);
4100
- throw new Error(`checkpoint-client: process timed out after ${ms(millis)}`)
4101
- }
4102
-
4103
- // sleep helper method
4104
- function sleep(ms) {
4105
- return new Promise((resolve) => {
4106
- // we want to unreference this timeout to ensure
4107
- // that it doesn't hold up the process from exiting
4108
- setTimeout(resolve, ms).unref();
4109
- })
4110
- }