@sveltejs/kit 1.0.0-next.35 → 1.0.0-next.352

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 (69) hide show
  1. package/README.md +12 -9
  2. package/assets/app/env.js +16 -0
  3. package/assets/app/navigation.js +24 -0
  4. package/assets/app/paths.js +1 -0
  5. package/assets/app/stores.js +97 -0
  6. package/assets/client/singletons.js +13 -0
  7. package/assets/client/start.js +1787 -0
  8. package/assets/components/error.svelte +18 -2
  9. package/assets/env.js +8 -0
  10. package/assets/paths.js +13 -0
  11. package/assets/server/index.js +3380 -0
  12. package/dist/chunks/constants.js +663 -0
  13. package/dist/chunks/filesystem.js +110 -0
  14. package/dist/chunks/index.js +1363 -0
  15. package/dist/chunks/index2.js +120 -0
  16. package/dist/chunks/index3.js +183 -0
  17. package/dist/chunks/index4.js +215 -0
  18. package/dist/chunks/index5.js +15748 -0
  19. package/dist/chunks/misc.js +78 -0
  20. package/dist/chunks/multipart-parser.js +444 -0
  21. package/dist/chunks/object.js +83 -0
  22. package/dist/chunks/plugin.js +558 -0
  23. package/dist/chunks/sync.js +856 -0
  24. package/dist/chunks/write_tsconfig.js +169 -0
  25. package/dist/cli.js +1028 -87
  26. package/dist/hooks.js +28 -0
  27. package/dist/node/polyfills.js +6654 -0
  28. package/dist/node.js +301 -0
  29. package/package.json +95 -55
  30. package/types/ambient.d.ts +307 -0
  31. package/types/index.d.ts +294 -0
  32. package/types/internal.d.ts +326 -0
  33. package/types/private.d.ts +235 -0
  34. package/CHANGELOG.md +0 -371
  35. package/assets/runtime/app/navigation.js +0 -23
  36. package/assets/runtime/app/navigation.js.map +0 -1
  37. package/assets/runtime/app/paths.js +0 -2
  38. package/assets/runtime/app/paths.js.map +0 -1
  39. package/assets/runtime/app/stores.js +0 -78
  40. package/assets/runtime/app/stores.js.map +0 -1
  41. package/assets/runtime/internal/singletons.js +0 -15
  42. package/assets/runtime/internal/singletons.js.map +0 -1
  43. package/assets/runtime/internal/start.js +0 -614
  44. package/assets/runtime/internal/start.js.map +0 -1
  45. package/assets/runtime/utils-85ebcc60.js +0 -18
  46. package/assets/runtime/utils-85ebcc60.js.map +0 -1
  47. package/dist/api.js +0 -28
  48. package/dist/api.js.map +0 -1
  49. package/dist/cli.js.map +0 -1
  50. package/dist/create_app.js +0 -502
  51. package/dist/create_app.js.map +0 -1
  52. package/dist/index.js +0 -327
  53. package/dist/index.js.map +0 -1
  54. package/dist/index2.js +0 -3497
  55. package/dist/index2.js.map +0 -1
  56. package/dist/index3.js +0 -296
  57. package/dist/index3.js.map +0 -1
  58. package/dist/index4.js +0 -311
  59. package/dist/index4.js.map +0 -1
  60. package/dist/index5.js +0 -221
  61. package/dist/index5.js.map +0 -1
  62. package/dist/index6.js +0 -730
  63. package/dist/index6.js.map +0 -1
  64. package/dist/renderer.js +0 -2429
  65. package/dist/renderer.js.map +0 -1
  66. package/dist/standard.js +0 -100
  67. package/dist/standard.js.map +0 -1
  68. package/dist/utils.js +0 -61
  69. package/dist/utils.js.map +0 -1
package/dist/index2.js DELETED
@@ -1,3497 +0,0 @@
1
- import http from 'http';
2
- import fs, { writeFileSync, readFileSync } from 'fs';
3
- import path, { resolve as resolve$1, join } from 'path';
4
- import { parse, URLSearchParams } from 'url';
5
- import require$$0, { EventEmitter } from 'events';
6
- import CheapWatch from 'cheap-watch';
7
- import util from 'util';
8
- import os from 'os';
9
- import https from 'https';
10
- import require$$1 from 'child_process';
11
- import require$$0$1 from 'domain';
12
- import 'querystring';
13
- import vm from 'vm';
14
- import vite from 'vite';
15
- import { c as create_manifest_data, a as create_app } from './create_app.js';
16
- import { r as rimraf, c as copy_assets } from './utils.js';
17
- import { render } from './renderer.js';
18
- import { g as get_body } from './index5.js';
19
- import svelte from '@sveltejs/vite-plugin-svelte';
20
- import './standard.js';
21
- import './index.js';
22
- import 'crypto';
23
- import 'stream';
24
- import 'zlib';
25
-
26
- function createCommonjsModule(fn) {
27
- var module = { exports: {} };
28
- return fn(module, module.exports), module.exports;
29
- }
30
-
31
- /*
32
- The MIT License (MIT)
33
-
34
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
35
-
36
- Permission is hereby granted, free of charge, to any person obtaining a copy
37
- of this software and associated documentation files (the "Software"), to deal
38
- in the Software without restriction, including without limitation the rights
39
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
40
- copies of the Software, and to permit persons to whom the Software is
41
- furnished to do so, subject to the following conditions:
42
-
43
- The above copyright notice and this permission notice shall be included in
44
- all copies or substantial portions of the Software.
45
-
46
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
47
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
48
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
49
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
50
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
51
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
52
- THE SOFTWARE.
53
-
54
- */
55
-
56
- var styles_1 = createCommonjsModule(function (module) {
57
- var styles = {};
58
- module['exports'] = styles;
59
-
60
- var codes = {
61
- reset: [0, 0],
62
-
63
- bold: [1, 22],
64
- dim: [2, 22],
65
- italic: [3, 23],
66
- underline: [4, 24],
67
- inverse: [7, 27],
68
- hidden: [8, 28],
69
- strikethrough: [9, 29],
70
-
71
- black: [30, 39],
72
- red: [31, 39],
73
- green: [32, 39],
74
- yellow: [33, 39],
75
- blue: [34, 39],
76
- magenta: [35, 39],
77
- cyan: [36, 39],
78
- white: [37, 39],
79
- gray: [90, 39],
80
- grey: [90, 39],
81
-
82
- brightRed: [91, 39],
83
- brightGreen: [92, 39],
84
- brightYellow: [93, 39],
85
- brightBlue: [94, 39],
86
- brightMagenta: [95, 39],
87
- brightCyan: [96, 39],
88
- brightWhite: [97, 39],
89
-
90
- bgBlack: [40, 49],
91
- bgRed: [41, 49],
92
- bgGreen: [42, 49],
93
- bgYellow: [43, 49],
94
- bgBlue: [44, 49],
95
- bgMagenta: [45, 49],
96
- bgCyan: [46, 49],
97
- bgWhite: [47, 49],
98
- bgGray: [100, 49],
99
- bgGrey: [100, 49],
100
-
101
- bgBrightRed: [101, 49],
102
- bgBrightGreen: [102, 49],
103
- bgBrightYellow: [103, 49],
104
- bgBrightBlue: [104, 49],
105
- bgBrightMagenta: [105, 49],
106
- bgBrightCyan: [106, 49],
107
- bgBrightWhite: [107, 49],
108
-
109
- // legacy styles for colors pre v1.0.0
110
- blackBG: [40, 49],
111
- redBG: [41, 49],
112
- greenBG: [42, 49],
113
- yellowBG: [43, 49],
114
- blueBG: [44, 49],
115
- magentaBG: [45, 49],
116
- cyanBG: [46, 49],
117
- whiteBG: [47, 49],
118
-
119
- };
120
-
121
- Object.keys(codes).forEach(function(key) {
122
- var val = codes[key];
123
- var style = styles[key] = [];
124
- style.open = '\u001b[' + val[0] + 'm';
125
- style.close = '\u001b[' + val[1] + 'm';
126
- });
127
- });
128
-
129
- /*
130
- MIT License
131
-
132
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
133
-
134
- Permission is hereby granted, free of charge, to any person obtaining a copy of
135
- this software and associated documentation files (the "Software"), to deal in
136
- the Software without restriction, including without limitation the rights to
137
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
138
- of the Software, and to permit persons to whom the Software is furnished to do
139
- so, subject to the following conditions:
140
-
141
- The above copyright notice and this permission notice shall be included in all
142
- copies or substantial portions of the Software.
143
-
144
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
145
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
146
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
147
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
148
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
149
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
150
- SOFTWARE.
151
- */
152
-
153
- var hasFlag = function(flag, argv) {
154
- argv = argv || process.argv;
155
-
156
- var terminatorPos = argv.indexOf('--');
157
- var prefix = /^-{1,2}/.test(flag) ? '' : '--';
158
- var pos = argv.indexOf(prefix + flag);
159
-
160
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
161
- };
162
-
163
- /*
164
- The MIT License (MIT)
165
-
166
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
167
-
168
- Permission is hereby granted, free of charge, to any person obtaining a copy
169
- of this software and associated documentation files (the "Software"), to deal
170
- in the Software without restriction, including without limitation the rights
171
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
172
- copies of the Software, and to permit persons to whom the Software is
173
- furnished to do so, subject to the following conditions:
174
-
175
- The above copyright notice and this permission notice shall be included in
176
- all copies or substantial portions of the Software.
177
-
178
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
179
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
180
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
181
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
182
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
183
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
184
- THE SOFTWARE.
185
-
186
- */
187
-
188
-
189
-
190
-
191
- var env = process.env;
192
-
193
- var forceColor = void 0;
194
- if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
195
- forceColor = false;
196
- } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
197
- || hasFlag('color=always')) {
198
- forceColor = true;
199
- }
200
- if ('FORCE_COLOR' in env) {
201
- forceColor = env.FORCE_COLOR.length === 0
202
- || parseInt(env.FORCE_COLOR, 10) !== 0;
203
- }
204
-
205
- function translateLevel(level) {
206
- if (level === 0) {
207
- return false;
208
- }
209
-
210
- return {
211
- level: level,
212
- hasBasic: true,
213
- has256: level >= 2,
214
- has16m: level >= 3,
215
- };
216
- }
217
-
218
- function supportsColor(stream) {
219
- if (forceColor === false) {
220
- return 0;
221
- }
222
-
223
- if (hasFlag('color=16m') || hasFlag('color=full')
224
- || hasFlag('color=truecolor')) {
225
- return 3;
226
- }
227
-
228
- if (hasFlag('color=256')) {
229
- return 2;
230
- }
231
-
232
- if (stream && !stream.isTTY && forceColor !== true) {
233
- return 0;
234
- }
235
-
236
- var min = forceColor ? 1 : 0;
237
-
238
- if (process.platform === 'win32') {
239
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
240
- // libuv that enables 256 color output on Windows. Anything earlier and it
241
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
242
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first
243
- // Windows release that supports 256 colors. Windows 10 build 14931 is the
244
- // first release that supports 16m/TrueColor.
245
- var osRelease = os.release().split('.');
246
- if (Number(process.versions.node.split('.')[0]) >= 8
247
- && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
248
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
249
- }
250
-
251
- return 1;
252
- }
253
-
254
- if ('CI' in env) {
255
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
256
- return sign in env;
257
- }) || env.CI_NAME === 'codeship') {
258
- return 1;
259
- }
260
-
261
- return min;
262
- }
263
-
264
- if ('TEAMCITY_VERSION' in env) {
265
- return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
266
- );
267
- }
268
-
269
- if ('TERM_PROGRAM' in env) {
270
- var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
271
-
272
- switch (env.TERM_PROGRAM) {
273
- case 'iTerm.app':
274
- return version >= 3 ? 3 : 2;
275
- case 'Hyper':
276
- return 3;
277
- case 'Apple_Terminal':
278
- return 2;
279
- // No default
280
- }
281
- }
282
-
283
- if (/-256(color)?$/i.test(env.TERM)) {
284
- return 2;
285
- }
286
-
287
- if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
288
- return 1;
289
- }
290
-
291
- if ('COLORTERM' in env) {
292
- return 1;
293
- }
294
-
295
- if (env.TERM === 'dumb') {
296
- return min;
297
- }
298
-
299
- return min;
300
- }
301
-
302
- function getSupportLevel(stream) {
303
- var level = supportsColor(stream);
304
- return translateLevel(level);
305
- }
306
-
307
- var supportsColors = {
308
- supportsColor: getSupportLevel,
309
- stdout: getSupportLevel(process.stdout),
310
- stderr: getSupportLevel(process.stderr),
311
- };
312
-
313
- var trap = createCommonjsModule(function (module) {
314
- module['exports'] = function runTheTrap(text, options) {
315
- var result = '';
316
- text = text || 'Run the trap, drop the bass';
317
- text = text.split('');
318
- var trap = {
319
- a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
320
- b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
321
- c: ['\u00a9', '\u023b', '\u03fe'],
322
- d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
323
- e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
324
- '\u0a6c'],
325
- f: ['\u04fa'],
326
- g: ['\u0262'],
327
- h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
328
- i: ['\u0f0f'],
329
- j: ['\u0134'],
330
- k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
331
- l: ['\u0139'],
332
- m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
333
- n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
334
- o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
335
- '\u06dd', '\u0e4f'],
336
- p: ['\u01f7', '\u048e'],
337
- q: ['\u09cd'],
338
- r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
339
- s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
340
- t: ['\u0141', '\u0166', '\u0373'],
341
- u: ['\u01b1', '\u054d'],
342
- v: ['\u05d8'],
343
- w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
344
- x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
345
- y: ['\u00a5', '\u04b0', '\u04cb'],
346
- z: ['\u01b5', '\u0240'],
347
- };
348
- text.forEach(function(c) {
349
- c = c.toLowerCase();
350
- var chars = trap[c] || [' '];
351
- var rand = Math.floor(Math.random() * chars.length);
352
- if (typeof trap[c] !== 'undefined') {
353
- result += trap[c][rand];
354
- } else {
355
- result += c;
356
- }
357
- });
358
- return result;
359
- };
360
- });
361
-
362
- var zalgo = createCommonjsModule(function (module) {
363
- // please no
364
- module['exports'] = function zalgo(text, options) {
365
- text = text || ' he is here ';
366
- var soul = {
367
- 'up': [
368
- '̍', '̎', '̄', '̅',
369
- '̿', '̑', '̆', '̐',
370
- '͒', '͗', '͑', '̇',
371
- '̈', '̊', '͂', '̓',
372
- '̈', '͊', '͋', '͌',
373
- '̃', '̂', '̌', '͐',
374
- '̀', '́', '̋', '̏',
375
- '̒', '̓', '̔', '̽',
376
- '̉', 'ͣ', 'ͤ', 'ͥ',
377
- 'ͦ', 'ͧ', 'ͨ', 'ͩ',
378
- 'ͪ', 'ͫ', 'ͬ', 'ͭ',
379
- 'ͮ', 'ͯ', '̾', '͛',
380
- '͆', '̚',
381
- ],
382
- 'down': [
383
- '̖', '̗', '̘', '̙',
384
- '̜', '̝', '̞', '̟',
385
- '̠', '̤', '̥', '̦',
386
- '̩', '̪', '̫', '̬',
387
- '̭', '̮', '̯', '̰',
388
- '̱', '̲', '̳', '̹',
389
- '̺', '̻', '̼', 'ͅ',
390
- '͇', '͈', '͉', '͍',
391
- '͎', '͓', '͔', '͕',
392
- '͖', '͙', '͚', '̣',
393
- ],
394
- 'mid': [
395
- '̕', '̛', '̀', '́',
396
- '͘', '̡', '̢', '̧',
397
- '̨', '̴', '̵', '̶',
398
- '͜', '͝', '͞',
399
- '͟', '͠', '͢', '̸',
400
- '̷', '͡', ' ҉',
401
- ],
402
- };
403
- var all = [].concat(soul.up, soul.down, soul.mid);
404
-
405
- function randomNumber(range) {
406
- var r = Math.floor(Math.random() * range);
407
- return r;
408
- }
409
-
410
- function isChar(character) {
411
- var bool = false;
412
- all.filter(function(i) {
413
- bool = (i === character);
414
- });
415
- return bool;
416
- }
417
-
418
-
419
- function heComes(text, options) {
420
- var result = '';
421
- var counts;
422
- var l;
423
- options = options || {};
424
- options['up'] =
425
- typeof options['up'] !== 'undefined' ? options['up'] : true;
426
- options['mid'] =
427
- typeof options['mid'] !== 'undefined' ? options['mid'] : true;
428
- options['down'] =
429
- typeof options['down'] !== 'undefined' ? options['down'] : true;
430
- options['size'] =
431
- typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
432
- text = text.split('');
433
- for (l in text) {
434
- if (isChar(l)) {
435
- continue;
436
- }
437
- result = result + text[l];
438
- counts = {'up': 0, 'down': 0, 'mid': 0};
439
- switch (options.size) {
440
- case 'mini':
441
- counts.up = randomNumber(8);
442
- counts.mid = randomNumber(2);
443
- counts.down = randomNumber(8);
444
- break;
445
- case 'maxi':
446
- counts.up = randomNumber(16) + 3;
447
- counts.mid = randomNumber(4) + 1;
448
- counts.down = randomNumber(64) + 3;
449
- break;
450
- default:
451
- counts.up = randomNumber(8) + 1;
452
- counts.mid = randomNumber(6) / 2;
453
- counts.down = randomNumber(8) + 1;
454
- break;
455
- }
456
-
457
- var arr = ['up', 'mid', 'down'];
458
- for (var d in arr) {
459
- var index = arr[d];
460
- for (var i = 0; i <= counts[index]; i++) {
461
- if (options[index]) {
462
- result = result + soul[index][randomNumber(soul[index].length)];
463
- }
464
- }
465
- }
466
- }
467
- return result;
468
- }
469
- // don't summon him
470
- return heComes(text, options);
471
- };
472
- });
473
-
474
- var america = createCommonjsModule(function (module) {
475
- module['exports'] = function(colors) {
476
- return function(letter, i, exploded) {
477
- if (letter === ' ') return letter;
478
- switch (i%3) {
479
- case 0: return colors.red(letter);
480
- case 1: return colors.white(letter);
481
- case 2: return colors.blue(letter);
482
- }
483
- };
484
- };
485
- });
486
-
487
- var zebra = createCommonjsModule(function (module) {
488
- module['exports'] = function(colors) {
489
- return function(letter, i, exploded) {
490
- return i % 2 === 0 ? letter : colors.inverse(letter);
491
- };
492
- };
493
- });
494
-
495
- var rainbow = createCommonjsModule(function (module) {
496
- module['exports'] = function(colors) {
497
- // RoY G BiV
498
- var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
499
- return function(letter, i, exploded) {
500
- if (letter === ' ') {
501
- return letter;
502
- } else {
503
- return colors[rainbowColors[i++ % rainbowColors.length]](letter);
504
- }
505
- };
506
- };
507
- });
508
-
509
- var random = createCommonjsModule(function (module) {
510
- module['exports'] = function(colors) {
511
- var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
512
- 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
513
- 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
514
- return function(letter, i, exploded) {
515
- return letter === ' ' ? letter :
516
- colors[
517
- available[Math.round(Math.random() * (available.length - 2))]
518
- ](letter);
519
- };
520
- };
521
- });
522
-
523
- /*
524
-
525
- The MIT License (MIT)
526
-
527
- Original Library
528
- - Copyright (c) Marak Squires
529
-
530
- Additional functionality
531
- - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
532
-
533
- Permission is hereby granted, free of charge, to any person obtaining a copy
534
- of this software and associated documentation files (the "Software"), to deal
535
- in the Software without restriction, including without limitation the rights
536
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
537
- copies of the Software, and to permit persons to whom the Software is
538
- furnished to do so, subject to the following conditions:
539
-
540
- The above copyright notice and this permission notice shall be included in
541
- all copies or substantial portions of the Software.
542
-
543
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
544
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
545
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
546
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
547
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
548
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
549
- THE SOFTWARE.
550
-
551
- */
552
-
553
- var colors_1 = createCommonjsModule(function (module) {
554
- var colors = {};
555
- module['exports'] = colors;
556
-
557
- colors.themes = {};
558
-
559
-
560
- var ansiStyles = colors.styles = styles_1;
561
- var defineProps = Object.defineProperties;
562
- var newLineRegex = new RegExp(/[\r\n]+/g);
563
-
564
- colors.supportsColor = supportsColors.supportsColor;
565
-
566
- if (typeof colors.enabled === 'undefined') {
567
- colors.enabled = colors.supportsColor() !== false;
568
- }
569
-
570
- colors.enable = function() {
571
- colors.enabled = true;
572
- };
573
-
574
- colors.disable = function() {
575
- colors.enabled = false;
576
- };
577
-
578
- colors.stripColors = colors.strip = function(str) {
579
- return ('' + str).replace(/\x1B\[\d+m/g, '');
580
- };
581
-
582
- // eslint-disable-next-line no-unused-vars
583
- colors.stylize = function stylize(str, style) {
584
- if (!colors.enabled) {
585
- return str+'';
586
- }
587
-
588
- var styleMap = ansiStyles[style];
589
-
590
- // Stylize should work for non-ANSI styles, too
591
- if(!styleMap && style in colors){
592
- // Style maps like trap operate as functions on strings;
593
- // they don't have properties like open or close.
594
- return colors[style](str);
595
- }
596
-
597
- return styleMap.open + str + styleMap.close;
598
- };
599
-
600
- var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
601
- var escapeStringRegexp = function(str) {
602
- if (typeof str !== 'string') {
603
- throw new TypeError('Expected a string');
604
- }
605
- return str.replace(matchOperatorsRe, '\\$&');
606
- };
607
-
608
- function build(_styles) {
609
- var builder = function builder() {
610
- return applyStyle.apply(builder, arguments);
611
- };
612
- builder._styles = _styles;
613
- // __proto__ is used because we must return a function, but there is
614
- // no way to create a function with a different prototype.
615
- builder.__proto__ = proto;
616
- return builder;
617
- }
618
-
619
- var styles = (function() {
620
- var ret = {};
621
- ansiStyles.grey = ansiStyles.gray;
622
- Object.keys(ansiStyles).forEach(function(key) {
623
- ansiStyles[key].closeRe =
624
- new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
625
- ret[key] = {
626
- get: function() {
627
- return build(this._styles.concat(key));
628
- },
629
- };
630
- });
631
- return ret;
632
- })();
633
-
634
- var proto = defineProps(function colors() {}, styles);
635
-
636
- function applyStyle() {
637
- var args = Array.prototype.slice.call(arguments);
638
-
639
- var str = args.map(function(arg) {
640
- // Use weak equality check so we can colorize null/undefined in safe mode
641
- if (arg != null && arg.constructor === String) {
642
- return arg;
643
- } else {
644
- return util.inspect(arg);
645
- }
646
- }).join(' ');
647
-
648
- if (!colors.enabled || !str) {
649
- return str;
650
- }
651
-
652
- var newLinesPresent = str.indexOf('\n') != -1;
653
-
654
- var nestedStyles = this._styles;
655
-
656
- var i = nestedStyles.length;
657
- while (i--) {
658
- var code = ansiStyles[nestedStyles[i]];
659
- str = code.open + str.replace(code.closeRe, code.open) + code.close;
660
- if (newLinesPresent) {
661
- str = str.replace(newLineRegex, function(match) {
662
- return code.close + match + code.open;
663
- });
664
- }
665
- }
666
-
667
- return str;
668
- }
669
-
670
- colors.setTheme = function(theme) {
671
- if (typeof theme === 'string') {
672
- console.log('colors.setTheme now only accepts an object, not a string. ' +
673
- 'If you are trying to set a theme from a file, it is now your (the ' +
674
- 'caller\'s) responsibility to require the file. The old syntax ' +
675
- 'looked like colors.setTheme(__dirname + ' +
676
- '\'/../themes/generic-logging.js\'); The new syntax looks like '+
677
- 'colors.setTheme(require(__dirname + ' +
678
- '\'/../themes/generic-logging.js\'));');
679
- return;
680
- }
681
- for (var style in theme) {
682
- (function(style) {
683
- colors[style] = function(str) {
684
- if (typeof theme[style] === 'object') {
685
- var out = str;
686
- for (var i in theme[style]) {
687
- out = colors[theme[style][i]](out);
688
- }
689
- return out;
690
- }
691
- return colors[theme[style]](str);
692
- };
693
- })(style);
694
- }
695
- };
696
-
697
- function init() {
698
- var ret = {};
699
- Object.keys(styles).forEach(function(name) {
700
- ret[name] = {
701
- get: function() {
702
- return build([name]);
703
- },
704
- };
705
- });
706
- return ret;
707
- }
708
-
709
- var sequencer = function sequencer(map, str) {
710
- var exploded = str.split('');
711
- exploded = exploded.map(map);
712
- return exploded.join('');
713
- };
714
-
715
- // custom formatter methods
716
- colors.trap = trap;
717
- colors.zalgo = zalgo;
718
-
719
- // maps
720
- colors.maps = {};
721
- colors.maps.america = america(colors);
722
- colors.maps.zebra = zebra(colors);
723
- colors.maps.rainbow = rainbow(colors);
724
- colors.maps.random = random(colors);
725
-
726
- for (var map in colors.maps) {
727
- (function(map) {
728
- colors[map] = function(str) {
729
- return sequencer(colors.maps[map], str);
730
- };
731
- })(map);
732
- }
733
-
734
- defineProps(colors, init());
735
- });
736
-
737
- var safe = createCommonjsModule(function (module) {
738
- //
739
- // Remark: Requiring this file will use the "safe" colors API,
740
- // which will not touch String.prototype.
741
- //
742
- // var colors = require('colors/safe');
743
- // colors.red("foo")
744
- //
745
- //
746
-
747
- module['exports'] = colors_1;
748
- });
749
-
750
- /**
751
- * Module dependencies.
752
- */
753
-
754
- var commander = createCommonjsModule(function (module, exports) {
755
- var EventEmitter = require$$0.EventEmitter;
756
- var spawn = require$$1.spawn;
757
-
758
- var dirname = path.dirname;
759
- var basename = path.basename;
760
-
761
-
762
- /**
763
- * Inherit `Command` from `EventEmitter.prototype`.
764
- */
765
-
766
- util.inherits(Command, EventEmitter);
767
-
768
- /**
769
- * Expose the root command.
770
- */
771
-
772
- exports = module.exports = new Command();
773
-
774
- /**
775
- * Expose `Command`.
776
- */
777
-
778
- exports.Command = Command;
779
-
780
- /**
781
- * Expose `Option`.
782
- */
783
-
784
- exports.Option = Option;
785
-
786
- /**
787
- * Initialize a new `Option` with the given `flags` and `description`.
788
- *
789
- * @param {String} flags
790
- * @param {String} description
791
- * @api public
792
- */
793
-
794
- function Option(flags, description) {
795
- this.flags = flags;
796
- this.required = ~flags.indexOf('<');
797
- this.optional = ~flags.indexOf('[');
798
- this.bool = !~flags.indexOf('-no-');
799
- flags = flags.split(/[ ,|]+/);
800
- if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
801
- this.long = flags.shift();
802
- this.description = description || '';
803
- }
804
-
805
- /**
806
- * Return option name.
807
- *
808
- * @return {String}
809
- * @api private
810
- */
811
-
812
- Option.prototype.name = function() {
813
- return this.long
814
- .replace('--', '')
815
- .replace('no-', '');
816
- };
817
-
818
- /**
819
- * Return option name, in a camelcase format that can be used
820
- * as a object attribute key.
821
- *
822
- * @return {String}
823
- * @api private
824
- */
825
-
826
- Option.prototype.attributeName = function() {
827
- return camelcase(this.name());
828
- };
829
-
830
- /**
831
- * Check if `arg` matches the short or long flag.
832
- *
833
- * @param {String} arg
834
- * @return {Boolean}
835
- * @api private
836
- */
837
-
838
- Option.prototype.is = function(arg) {
839
- return this.short === arg || this.long === arg;
840
- };
841
-
842
- /**
843
- * Initialize a new `Command`.
844
- *
845
- * @param {String} name
846
- * @api public
847
- */
848
-
849
- function Command(name) {
850
- this.commands = [];
851
- this.options = [];
852
- this._execs = {};
853
- this._allowUnknownOption = false;
854
- this._args = [];
855
- this._name = name || '';
856
- }
857
-
858
- /**
859
- * Add command `name`.
860
- *
861
- * The `.action()` callback is invoked when the
862
- * command `name` is specified via __ARGV__,
863
- * and the remaining arguments are applied to the
864
- * function for access.
865
- *
866
- * When the `name` is "*" an un-matched command
867
- * will be passed as the first arg, followed by
868
- * the rest of __ARGV__ remaining.
869
- *
870
- * Examples:
871
- *
872
- * program
873
- * .version('0.0.1')
874
- * .option('-C, --chdir <path>', 'change the working directory')
875
- * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
876
- * .option('-T, --no-tests', 'ignore test hook')
877
- *
878
- * program
879
- * .command('setup')
880
- * .description('run remote setup commands')
881
- * .action(function() {
882
- * console.log('setup');
883
- * });
884
- *
885
- * program
886
- * .command('exec <cmd>')
887
- * .description('run the given remote command')
888
- * .action(function(cmd) {
889
- * console.log('exec "%s"', cmd);
890
- * });
891
- *
892
- * program
893
- * .command('teardown <dir> [otherDirs...]')
894
- * .description('run teardown commands')
895
- * .action(function(dir, otherDirs) {
896
- * console.log('dir "%s"', dir);
897
- * if (otherDirs) {
898
- * otherDirs.forEach(function (oDir) {
899
- * console.log('dir "%s"', oDir);
900
- * });
901
- * }
902
- * });
903
- *
904
- * program
905
- * .command('*')
906
- * .description('deploy the given env')
907
- * .action(function(env) {
908
- * console.log('deploying "%s"', env);
909
- * });
910
- *
911
- * program.parse(process.argv);
912
- *
913
- * @param {String} name
914
- * @param {String} [desc] for git-style sub-commands
915
- * @return {Command} the new command
916
- * @api public
917
- */
918
-
919
- Command.prototype.command = function(name, desc, opts) {
920
- if (typeof desc === 'object' && desc !== null) {
921
- opts = desc;
922
- desc = null;
923
- }
924
- opts = opts || {};
925
- var args = name.split(/ +/);
926
- var cmd = new Command(args.shift());
927
-
928
- if (desc) {
929
- cmd.description(desc);
930
- this.executables = true;
931
- this._execs[cmd._name] = true;
932
- if (opts.isDefault) this.defaultExecutable = cmd._name;
933
- }
934
- cmd._noHelp = !!opts.noHelp;
935
- this.commands.push(cmd);
936
- cmd.parseExpectedArgs(args);
937
- cmd.parent = this;
938
-
939
- if (desc) return this;
940
- return cmd;
941
- };
942
-
943
- /**
944
- * Define argument syntax for the top-level command.
945
- *
946
- * @api public
947
- */
948
-
949
- Command.prototype.arguments = function(desc) {
950
- return this.parseExpectedArgs(desc.split(/ +/));
951
- };
952
-
953
- /**
954
- * Add an implicit `help [cmd]` subcommand
955
- * which invokes `--help` for the given command.
956
- *
957
- * @api private
958
- */
959
-
960
- Command.prototype.addImplicitHelpCommand = function() {
961
- this.command('help [cmd]', 'display help for [cmd]');
962
- };
963
-
964
- /**
965
- * Parse expected `args`.
966
- *
967
- * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
968
- *
969
- * @param {Array} args
970
- * @return {Command} for chaining
971
- * @api public
972
- */
973
-
974
- Command.prototype.parseExpectedArgs = function(args) {
975
- if (!args.length) return;
976
- var self = this;
977
- args.forEach(function(arg) {
978
- var argDetails = {
979
- required: false,
980
- name: '',
981
- variadic: false
982
- };
983
-
984
- switch (arg[0]) {
985
- case '<':
986
- argDetails.required = true;
987
- argDetails.name = arg.slice(1, -1);
988
- break;
989
- case '[':
990
- argDetails.name = arg.slice(1, -1);
991
- break;
992
- }
993
-
994
- if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
995
- argDetails.variadic = true;
996
- argDetails.name = argDetails.name.slice(0, -3);
997
- }
998
- if (argDetails.name) {
999
- self._args.push(argDetails);
1000
- }
1001
- });
1002
- return this;
1003
- };
1004
-
1005
- /**
1006
- * Register callback `fn` for the command.
1007
- *
1008
- * Examples:
1009
- *
1010
- * program
1011
- * .command('help')
1012
- * .description('display verbose help')
1013
- * .action(function() {
1014
- * // output help here
1015
- * });
1016
- *
1017
- * @param {Function} fn
1018
- * @return {Command} for chaining
1019
- * @api public
1020
- */
1021
-
1022
- Command.prototype.action = function(fn) {
1023
- var self = this;
1024
- var listener = function(args, unknown) {
1025
- // Parse any so-far unknown options
1026
- args = args || [];
1027
- unknown = unknown || [];
1028
-
1029
- var parsed = self.parseOptions(unknown);
1030
-
1031
- // Output help if necessary
1032
- outputHelpIfNecessary(self, parsed.unknown);
1033
-
1034
- // If there are still any unknown options, then we simply
1035
- // die, unless someone asked for help, in which case we give it
1036
- // to them, and then we die.
1037
- if (parsed.unknown.length > 0) {
1038
- self.unknownOption(parsed.unknown[0]);
1039
- }
1040
-
1041
- // Leftover arguments need to be pushed back. Fixes issue #56
1042
- if (parsed.args.length) args = parsed.args.concat(args);
1043
-
1044
- self._args.forEach(function(arg, i) {
1045
- if (arg.required && args[i] == null) {
1046
- self.missingArgument(arg.name);
1047
- } else if (arg.variadic) {
1048
- if (i !== self._args.length - 1) {
1049
- self.variadicArgNotLast(arg.name);
1050
- }
1051
-
1052
- args[i] = args.splice(i);
1053
- }
1054
- });
1055
-
1056
- // Always append ourselves to the end of the arguments,
1057
- // to make sure we match the number of arguments the user
1058
- // expects
1059
- if (self._args.length) {
1060
- args[self._args.length] = self;
1061
- } else {
1062
- args.push(self);
1063
- }
1064
-
1065
- fn.apply(self, args);
1066
- };
1067
- var parent = this.parent || this;
1068
- var name = parent === this ? '*' : this._name;
1069
- parent.on('command:' + name, listener);
1070
- if (this._alias) parent.on('command:' + this._alias, listener);
1071
- return this;
1072
- };
1073
-
1074
- /**
1075
- * Define option with `flags`, `description` and optional
1076
- * coercion `fn`.
1077
- *
1078
- * The `flags` string should contain both the short and long flags,
1079
- * separated by comma, a pipe or space. The following are all valid
1080
- * all will output this way when `--help` is used.
1081
- *
1082
- * "-p, --pepper"
1083
- * "-p|--pepper"
1084
- * "-p --pepper"
1085
- *
1086
- * Examples:
1087
- *
1088
- * // simple boolean defaulting to false
1089
- * program.option('-p, --pepper', 'add pepper');
1090
- *
1091
- * --pepper
1092
- * program.pepper
1093
- * // => Boolean
1094
- *
1095
- * // simple boolean defaulting to true
1096
- * program.option('-C, --no-cheese', 'remove cheese');
1097
- *
1098
- * program.cheese
1099
- * // => true
1100
- *
1101
- * --no-cheese
1102
- * program.cheese
1103
- * // => false
1104
- *
1105
- * // required argument
1106
- * program.option('-C, --chdir <path>', 'change the working directory');
1107
- *
1108
- * --chdir /tmp
1109
- * program.chdir
1110
- * // => "/tmp"
1111
- *
1112
- * // optional argument
1113
- * program.option('-c, --cheese [type]', 'add cheese [marble]');
1114
- *
1115
- * @param {String} flags
1116
- * @param {String} description
1117
- * @param {Function|*} [fn] or default
1118
- * @param {*} [defaultValue]
1119
- * @return {Command} for chaining
1120
- * @api public
1121
- */
1122
-
1123
- Command.prototype.option = function(flags, description, fn, defaultValue) {
1124
- var self = this,
1125
- option = new Option(flags, description),
1126
- oname = option.name(),
1127
- name = option.attributeName();
1128
-
1129
- // default as 3rd arg
1130
- if (typeof fn !== 'function') {
1131
- if (fn instanceof RegExp) {
1132
- var regex = fn;
1133
- fn = function(val, def) {
1134
- var m = regex.exec(val);
1135
- return m ? m[0] : def;
1136
- };
1137
- } else {
1138
- defaultValue = fn;
1139
- fn = null;
1140
- }
1141
- }
1142
-
1143
- // preassign default value only for --no-*, [optional], or <required>
1144
- if (!option.bool || option.optional || option.required) {
1145
- // when --no-* we make sure default is true
1146
- if (!option.bool) defaultValue = true;
1147
- // preassign only if we have a default
1148
- if (defaultValue !== undefined) {
1149
- self[name] = defaultValue;
1150
- option.defaultValue = defaultValue;
1151
- }
1152
- }
1153
-
1154
- // register the option
1155
- this.options.push(option);
1156
-
1157
- // when it's passed assign the value
1158
- // and conditionally invoke the callback
1159
- this.on('option:' + oname, function(val) {
1160
- // coercion
1161
- if (val !== null && fn) {
1162
- val = fn(val, self[name] === undefined ? defaultValue : self[name]);
1163
- }
1164
-
1165
- // unassigned or bool
1166
- if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {
1167
- // if no value, bool true, and we have a default, then use it!
1168
- if (val == null) {
1169
- self[name] = option.bool
1170
- ? defaultValue || true
1171
- : false;
1172
- } else {
1173
- self[name] = val;
1174
- }
1175
- } else if (val !== null) {
1176
- // reassign
1177
- self[name] = val;
1178
- }
1179
- });
1180
-
1181
- return this;
1182
- };
1183
-
1184
- /**
1185
- * Allow unknown options on the command line.
1186
- *
1187
- * @param {Boolean} arg if `true` or omitted, no error will be thrown
1188
- * for unknown options.
1189
- * @api public
1190
- */
1191
- Command.prototype.allowUnknownOption = function(arg) {
1192
- this._allowUnknownOption = arguments.length === 0 || arg;
1193
- return this;
1194
- };
1195
-
1196
- /**
1197
- * Parse `argv`, settings options and invoking commands when defined.
1198
- *
1199
- * @param {Array} argv
1200
- * @return {Command} for chaining
1201
- * @api public
1202
- */
1203
-
1204
- Command.prototype.parse = function(argv) {
1205
- // implicit help
1206
- if (this.executables) this.addImplicitHelpCommand();
1207
-
1208
- // store raw args
1209
- this.rawArgs = argv;
1210
-
1211
- // guess name
1212
- this._name = this._name || basename(argv[1], '.js');
1213
-
1214
- // github-style sub-commands with no sub-command
1215
- if (this.executables && argv.length < 3 && !this.defaultExecutable) {
1216
- // this user needs help
1217
- argv.push('--help');
1218
- }
1219
-
1220
- // process argv
1221
- var parsed = this.parseOptions(this.normalize(argv.slice(2)));
1222
- var args = this.args = parsed.args;
1223
-
1224
- var result = this.parseArgs(this.args, parsed.unknown);
1225
-
1226
- // executable sub-commands
1227
- var name = result.args[0];
1228
-
1229
- var aliasCommand = null;
1230
- // check alias of sub commands
1231
- if (name) {
1232
- aliasCommand = this.commands.filter(function(command) {
1233
- return command.alias() === name;
1234
- })[0];
1235
- }
1236
-
1237
- if (this._execs[name] && typeof this._execs[name] !== 'function') {
1238
- return this.executeSubCommand(argv, args, parsed.unknown);
1239
- } else if (aliasCommand) {
1240
- // is alias of a subCommand
1241
- args[0] = aliasCommand._name;
1242
- return this.executeSubCommand(argv, args, parsed.unknown);
1243
- } else if (this.defaultExecutable) {
1244
- // use the default subcommand
1245
- args.unshift(this.defaultExecutable);
1246
- return this.executeSubCommand(argv, args, parsed.unknown);
1247
- }
1248
-
1249
- return result;
1250
- };
1251
-
1252
- /**
1253
- * Execute a sub-command executable.
1254
- *
1255
- * @param {Array} argv
1256
- * @param {Array} args
1257
- * @param {Array} unknown
1258
- * @api private
1259
- */
1260
-
1261
- Command.prototype.executeSubCommand = function(argv, args, unknown) {
1262
- args = args.concat(unknown);
1263
-
1264
- if (!args.length) this.help();
1265
- if (args[0] === 'help' && args.length === 1) this.help();
1266
-
1267
- // <cmd> --help
1268
- if (args[0] === 'help') {
1269
- args[0] = args[1];
1270
- args[1] = '--help';
1271
- }
1272
-
1273
- // executable
1274
- var f = argv[1];
1275
- // name of the subcommand, link `pm-install`
1276
- var bin = basename(f, '.js') + '-' + args[0];
1277
-
1278
- // In case of globally installed, get the base dir where executable
1279
- // subcommand file should be located at
1280
- var baseDir,
1281
- link = fs.lstatSync(f).isSymbolicLink() ? fs.readlinkSync(f) : f;
1282
-
1283
- // when symbolink is relative path
1284
- if (link !== f && link.charAt(0) !== '/') {
1285
- link = path.join(dirname(f), link);
1286
- }
1287
- baseDir = dirname(link);
1288
-
1289
- // prefer local `./<bin>` to bin in the $PATH
1290
- var localBin = path.join(baseDir, bin);
1291
-
1292
- // whether bin file is a js script with explicit `.js` extension
1293
- var isExplicitJS = false;
1294
- if (exists(localBin + '.js')) {
1295
- bin = localBin + '.js';
1296
- isExplicitJS = true;
1297
- } else if (exists(localBin)) {
1298
- bin = localBin;
1299
- }
1300
-
1301
- args = args.slice(1);
1302
-
1303
- var proc;
1304
- if (process.platform !== 'win32') {
1305
- if (isExplicitJS) {
1306
- args.unshift(bin);
1307
- // add executable arguments to spawn
1308
- args = (process.execArgv || []).concat(args);
1309
-
1310
- proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });
1311
- } else {
1312
- proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });
1313
- }
1314
- } else {
1315
- args.unshift(bin);
1316
- proc = spawn(process.execPath, args, { stdio: 'inherit' });
1317
- }
1318
-
1319
- var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
1320
- signals.forEach(function(signal) {
1321
- process.on(signal, function() {
1322
- if (proc.killed === false && proc.exitCode === null) {
1323
- proc.kill(signal);
1324
- }
1325
- });
1326
- });
1327
- proc.on('close', process.exit.bind(process));
1328
- proc.on('error', function(err) {
1329
- if (err.code === 'ENOENT') {
1330
- console.error('\n %s(1) does not exist, try --help\n', bin);
1331
- } else if (err.code === 'EACCES') {
1332
- console.error('\n %s(1) not executable. try chmod or run with root\n', bin);
1333
- }
1334
- process.exit(1);
1335
- });
1336
-
1337
- // Store the reference to the child process
1338
- this.runningCommand = proc;
1339
- };
1340
-
1341
- /**
1342
- * Normalize `args`, splitting joined short flags. For example
1343
- * the arg "-abc" is equivalent to "-a -b -c".
1344
- * This also normalizes equal sign and splits "--abc=def" into "--abc def".
1345
- *
1346
- * @param {Array} args
1347
- * @return {Array}
1348
- * @api private
1349
- */
1350
-
1351
- Command.prototype.normalize = function(args) {
1352
- var ret = [],
1353
- arg,
1354
- lastOpt,
1355
- index;
1356
-
1357
- for (var i = 0, len = args.length; i < len; ++i) {
1358
- arg = args[i];
1359
- if (i > 0) {
1360
- lastOpt = this.optionFor(args[i - 1]);
1361
- }
1362
-
1363
- if (arg === '--') {
1364
- // Honor option terminator
1365
- ret = ret.concat(args.slice(i));
1366
- break;
1367
- } else if (lastOpt && lastOpt.required) {
1368
- ret.push(arg);
1369
- } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') {
1370
- arg.slice(1).split('').forEach(function(c) {
1371
- ret.push('-' + c);
1372
- });
1373
- } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
1374
- ret.push(arg.slice(0, index), arg.slice(index + 1));
1375
- } else {
1376
- ret.push(arg);
1377
- }
1378
- }
1379
-
1380
- return ret;
1381
- };
1382
-
1383
- /**
1384
- * Parse command `args`.
1385
- *
1386
- * When listener(s) are available those
1387
- * callbacks are invoked, otherwise the "*"
1388
- * event is emitted and those actions are invoked.
1389
- *
1390
- * @param {Array} args
1391
- * @return {Command} for chaining
1392
- * @api private
1393
- */
1394
-
1395
- Command.prototype.parseArgs = function(args, unknown) {
1396
- var name;
1397
-
1398
- if (args.length) {
1399
- name = args[0];
1400
- if (this.listeners('command:' + name).length) {
1401
- this.emit('command:' + args.shift(), args, unknown);
1402
- } else {
1403
- this.emit('command:*', args);
1404
- }
1405
- } else {
1406
- outputHelpIfNecessary(this, unknown);
1407
-
1408
- // If there were no args and we have unknown options,
1409
- // then they are extraneous and we need to error.
1410
- if (unknown.length > 0) {
1411
- this.unknownOption(unknown[0]);
1412
- }
1413
- }
1414
-
1415
- return this;
1416
- };
1417
-
1418
- /**
1419
- * Return an option matching `arg` if any.
1420
- *
1421
- * @param {String} arg
1422
- * @return {Option}
1423
- * @api private
1424
- */
1425
-
1426
- Command.prototype.optionFor = function(arg) {
1427
- for (var i = 0, len = this.options.length; i < len; ++i) {
1428
- if (this.options[i].is(arg)) {
1429
- return this.options[i];
1430
- }
1431
- }
1432
- };
1433
-
1434
- /**
1435
- * Parse options from `argv` returning `argv`
1436
- * void of these options.
1437
- *
1438
- * @param {Array} argv
1439
- * @return {Array}
1440
- * @api public
1441
- */
1442
-
1443
- Command.prototype.parseOptions = function(argv) {
1444
- var args = [],
1445
- len = argv.length,
1446
- literal,
1447
- option,
1448
- arg;
1449
-
1450
- var unknownOptions = [];
1451
-
1452
- // parse options
1453
- for (var i = 0; i < len; ++i) {
1454
- arg = argv[i];
1455
-
1456
- // literal args after --
1457
- if (literal) {
1458
- args.push(arg);
1459
- continue;
1460
- }
1461
-
1462
- if (arg === '--') {
1463
- literal = true;
1464
- continue;
1465
- }
1466
-
1467
- // find matching Option
1468
- option = this.optionFor(arg);
1469
-
1470
- // option is defined
1471
- if (option) {
1472
- // requires arg
1473
- if (option.required) {
1474
- arg = argv[++i];
1475
- if (arg == null) return this.optionMissingArgument(option);
1476
- this.emit('option:' + option.name(), arg);
1477
- // optional arg
1478
- } else if (option.optional) {
1479
- arg = argv[i + 1];
1480
- if (arg == null || (arg[0] === '-' && arg !== '-')) {
1481
- arg = null;
1482
- } else {
1483
- ++i;
1484
- }
1485
- this.emit('option:' + option.name(), arg);
1486
- // bool
1487
- } else {
1488
- this.emit('option:' + option.name());
1489
- }
1490
- continue;
1491
- }
1492
-
1493
- // looks like an option
1494
- if (arg.length > 1 && arg[0] === '-') {
1495
- unknownOptions.push(arg);
1496
-
1497
- // If the next argument looks like it might be
1498
- // an argument for this option, we pass it on.
1499
- // If it isn't, then it'll simply be ignored
1500
- if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {
1501
- unknownOptions.push(argv[++i]);
1502
- }
1503
- continue;
1504
- }
1505
-
1506
- // arg
1507
- args.push(arg);
1508
- }
1509
-
1510
- return { args: args, unknown: unknownOptions };
1511
- };
1512
-
1513
- /**
1514
- * Return an object containing options as key-value pairs
1515
- *
1516
- * @return {Object}
1517
- * @api public
1518
- */
1519
- Command.prototype.opts = function() {
1520
- var result = {},
1521
- len = this.options.length;
1522
-
1523
- for (var i = 0; i < len; i++) {
1524
- var key = this.options[i].attributeName();
1525
- result[key] = key === this._versionOptionName ? this._version : this[key];
1526
- }
1527
- return result;
1528
- };
1529
-
1530
- /**
1531
- * Argument `name` is missing.
1532
- *
1533
- * @param {String} name
1534
- * @api private
1535
- */
1536
-
1537
- Command.prototype.missingArgument = function(name) {
1538
- console.error();
1539
- console.error(" error: missing required argument `%s'", name);
1540
- console.error();
1541
- process.exit(1);
1542
- };
1543
-
1544
- /**
1545
- * `Option` is missing an argument, but received `flag` or nothing.
1546
- *
1547
- * @param {String} option
1548
- * @param {String} flag
1549
- * @api private
1550
- */
1551
-
1552
- Command.prototype.optionMissingArgument = function(option, flag) {
1553
- console.error();
1554
- if (flag) {
1555
- console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag);
1556
- } else {
1557
- console.error(" error: option `%s' argument missing", option.flags);
1558
- }
1559
- console.error();
1560
- process.exit(1);
1561
- };
1562
-
1563
- /**
1564
- * Unknown option `flag`.
1565
- *
1566
- * @param {String} flag
1567
- * @api private
1568
- */
1569
-
1570
- Command.prototype.unknownOption = function(flag) {
1571
- if (this._allowUnknownOption) return;
1572
- console.error();
1573
- console.error(" error: unknown option `%s'", flag);
1574
- console.error();
1575
- process.exit(1);
1576
- };
1577
-
1578
- /**
1579
- * Variadic argument with `name` is not the last argument as required.
1580
- *
1581
- * @param {String} name
1582
- * @api private
1583
- */
1584
-
1585
- Command.prototype.variadicArgNotLast = function(name) {
1586
- console.error();
1587
- console.error(" error: variadic arguments must be last `%s'", name);
1588
- console.error();
1589
- process.exit(1);
1590
- };
1591
-
1592
- /**
1593
- * Set the program version to `str`.
1594
- *
1595
- * This method auto-registers the "-V, --version" flag
1596
- * which will print the version number when passed.
1597
- *
1598
- * @param {String} str
1599
- * @param {String} [flags]
1600
- * @return {Command} for chaining
1601
- * @api public
1602
- */
1603
-
1604
- Command.prototype.version = function(str, flags) {
1605
- if (arguments.length === 0) return this._version;
1606
- this._version = str;
1607
- flags = flags || '-V, --version';
1608
- var versionOption = new Option(flags, 'output the version number');
1609
- this._versionOptionName = versionOption.long.substr(2) || 'version';
1610
- this.options.push(versionOption);
1611
- this.on('option:' + this._versionOptionName, function() {
1612
- process.stdout.write(str + '\n');
1613
- process.exit(0);
1614
- });
1615
- return this;
1616
- };
1617
-
1618
- /**
1619
- * Set the description to `str`.
1620
- *
1621
- * @param {String} str
1622
- * @param {Object} argsDescription
1623
- * @return {String|Command}
1624
- * @api public
1625
- */
1626
-
1627
- Command.prototype.description = function(str, argsDescription) {
1628
- if (arguments.length === 0) return this._description;
1629
- this._description = str;
1630
- this._argsDescription = argsDescription;
1631
- return this;
1632
- };
1633
-
1634
- /**
1635
- * Set an alias for the command
1636
- *
1637
- * @param {String} alias
1638
- * @return {String|Command}
1639
- * @api public
1640
- */
1641
-
1642
- Command.prototype.alias = function(alias) {
1643
- var command = this;
1644
- if (this.commands.length !== 0) {
1645
- command = this.commands[this.commands.length - 1];
1646
- }
1647
-
1648
- if (arguments.length === 0) return command._alias;
1649
-
1650
- if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
1651
-
1652
- command._alias = alias;
1653
- return this;
1654
- };
1655
-
1656
- /**
1657
- * Set / get the command usage `str`.
1658
- *
1659
- * @param {String} str
1660
- * @return {String|Command}
1661
- * @api public
1662
- */
1663
-
1664
- Command.prototype.usage = function(str) {
1665
- var args = this._args.map(function(arg) {
1666
- return humanReadableArgName(arg);
1667
- });
1668
-
1669
- var usage = '[options]' +
1670
- (this.commands.length ? ' [command]' : '') +
1671
- (this._args.length ? ' ' + args.join(' ') : '');
1672
-
1673
- if (arguments.length === 0) return this._usage || usage;
1674
- this._usage = str;
1675
-
1676
- return this;
1677
- };
1678
-
1679
- /**
1680
- * Get or set the name of the command
1681
- *
1682
- * @param {String} str
1683
- * @return {String|Command}
1684
- * @api public
1685
- */
1686
-
1687
- Command.prototype.name = function(str) {
1688
- if (arguments.length === 0) return this._name;
1689
- this._name = str;
1690
- return this;
1691
- };
1692
-
1693
- /**
1694
- * Return prepared commands.
1695
- *
1696
- * @return {Array}
1697
- * @api private
1698
- */
1699
-
1700
- Command.prototype.prepareCommands = function() {
1701
- return this.commands.filter(function(cmd) {
1702
- return !cmd._noHelp;
1703
- }).map(function(cmd) {
1704
- var args = cmd._args.map(function(arg) {
1705
- return humanReadableArgName(arg);
1706
- }).join(' ');
1707
-
1708
- return [
1709
- cmd._name +
1710
- (cmd._alias ? '|' + cmd._alias : '') +
1711
- (cmd.options.length ? ' [options]' : '') +
1712
- (args ? ' ' + args : ''),
1713
- cmd._description
1714
- ];
1715
- });
1716
- };
1717
-
1718
- /**
1719
- * Return the largest command length.
1720
- *
1721
- * @return {Number}
1722
- * @api private
1723
- */
1724
-
1725
- Command.prototype.largestCommandLength = function() {
1726
- var commands = this.prepareCommands();
1727
- return commands.reduce(function(max, command) {
1728
- return Math.max(max, command[0].length);
1729
- }, 0);
1730
- };
1731
-
1732
- /**
1733
- * Return the largest option length.
1734
- *
1735
- * @return {Number}
1736
- * @api private
1737
- */
1738
-
1739
- Command.prototype.largestOptionLength = function() {
1740
- var options = [].slice.call(this.options);
1741
- options.push({
1742
- flags: '-h, --help'
1743
- });
1744
- return options.reduce(function(max, option) {
1745
- return Math.max(max, option.flags.length);
1746
- }, 0);
1747
- };
1748
-
1749
- /**
1750
- * Return the largest arg length.
1751
- *
1752
- * @return {Number}
1753
- * @api private
1754
- */
1755
-
1756
- Command.prototype.largestArgLength = function() {
1757
- return this._args.reduce(function(max, arg) {
1758
- return Math.max(max, arg.name.length);
1759
- }, 0);
1760
- };
1761
-
1762
- /**
1763
- * Return the pad width.
1764
- *
1765
- * @return {Number}
1766
- * @api private
1767
- */
1768
-
1769
- Command.prototype.padWidth = function() {
1770
- var width = this.largestOptionLength();
1771
- if (this._argsDescription && this._args.length) {
1772
- if (this.largestArgLength() > width) {
1773
- width = this.largestArgLength();
1774
- }
1775
- }
1776
-
1777
- if (this.commands && this.commands.length) {
1778
- if (this.largestCommandLength() > width) {
1779
- width = this.largestCommandLength();
1780
- }
1781
- }
1782
-
1783
- return width;
1784
- };
1785
-
1786
- /**
1787
- * Return help for options.
1788
- *
1789
- * @return {String}
1790
- * @api private
1791
- */
1792
-
1793
- Command.prototype.optionHelp = function() {
1794
- var width = this.padWidth();
1795
-
1796
- // Append the help information
1797
- return this.options.map(function(option) {
1798
- return pad(option.flags, width) + ' ' + option.description +
1799
- ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + option.defaultValue + ')' : '');
1800
- }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])
1801
- .join('\n');
1802
- };
1803
-
1804
- /**
1805
- * Return command help documentation.
1806
- *
1807
- * @return {String}
1808
- * @api private
1809
- */
1810
-
1811
- Command.prototype.commandHelp = function() {
1812
- if (!this.commands.length) return '';
1813
-
1814
- var commands = this.prepareCommands();
1815
- var width = this.padWidth();
1816
-
1817
- return [
1818
- ' Commands:',
1819
- '',
1820
- commands.map(function(cmd) {
1821
- var desc = cmd[1] ? ' ' + cmd[1] : '';
1822
- return (desc ? pad(cmd[0], width) : cmd[0]) + desc;
1823
- }).join('\n').replace(/^/gm, ' '),
1824
- ''
1825
- ].join('\n');
1826
- };
1827
-
1828
- /**
1829
- * Return program help documentation.
1830
- *
1831
- * @return {String}
1832
- * @api private
1833
- */
1834
-
1835
- Command.prototype.helpInformation = function() {
1836
- var desc = [];
1837
- if (this._description) {
1838
- desc = [
1839
- ' ' + this._description,
1840
- ''
1841
- ];
1842
-
1843
- var argsDescription = this._argsDescription;
1844
- if (argsDescription && this._args.length) {
1845
- var width = this.padWidth();
1846
- desc.push(' Arguments:');
1847
- desc.push('');
1848
- this._args.forEach(function(arg) {
1849
- desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);
1850
- });
1851
- desc.push('');
1852
- }
1853
- }
1854
-
1855
- var cmdName = this._name;
1856
- if (this._alias) {
1857
- cmdName = cmdName + '|' + this._alias;
1858
- }
1859
- var usage = [
1860
- '',
1861
- ' Usage: ' + cmdName + ' ' + this.usage(),
1862
- ''
1863
- ];
1864
-
1865
- var cmds = [];
1866
- var commandHelp = this.commandHelp();
1867
- if (commandHelp) cmds = [commandHelp];
1868
-
1869
- var options = [
1870
- ' Options:',
1871
- '',
1872
- '' + this.optionHelp().replace(/^/gm, ' '),
1873
- ''
1874
- ];
1875
-
1876
- return usage
1877
- .concat(desc)
1878
- .concat(options)
1879
- .concat(cmds)
1880
- .join('\n');
1881
- };
1882
-
1883
- /**
1884
- * Output help information for this command
1885
- *
1886
- * @api public
1887
- */
1888
-
1889
- Command.prototype.outputHelp = function(cb) {
1890
- if (!cb) {
1891
- cb = function(passthru) {
1892
- return passthru;
1893
- };
1894
- }
1895
- process.stdout.write(cb(this.helpInformation()));
1896
- this.emit('--help');
1897
- };
1898
-
1899
- /**
1900
- * Output help information and exit.
1901
- *
1902
- * @api public
1903
- */
1904
-
1905
- Command.prototype.help = function(cb) {
1906
- this.outputHelp(cb);
1907
- process.exit();
1908
- };
1909
-
1910
- /**
1911
- * Camel-case the given `flag`
1912
- *
1913
- * @param {String} flag
1914
- * @return {String}
1915
- * @api private
1916
- */
1917
-
1918
- function camelcase(flag) {
1919
- return flag.split('-').reduce(function(str, word) {
1920
- return str + word[0].toUpperCase() + word.slice(1);
1921
- });
1922
- }
1923
-
1924
- /**
1925
- * Pad `str` to `width`.
1926
- *
1927
- * @param {String} str
1928
- * @param {Number} width
1929
- * @return {String}
1930
- * @api private
1931
- */
1932
-
1933
- function pad(str, width) {
1934
- var len = Math.max(0, width - str.length);
1935
- return str + Array(len + 1).join(' ');
1936
- }
1937
-
1938
- /**
1939
- * Output help information if necessary
1940
- *
1941
- * @param {Command} command to output help for
1942
- * @param {Array} array of options to search for -h or --help
1943
- * @api private
1944
- */
1945
-
1946
- function outputHelpIfNecessary(cmd, options) {
1947
- options = options || [];
1948
- for (var i = 0; i < options.length; i++) {
1949
- if (options[i] === '--help' || options[i] === '-h') {
1950
- cmd.outputHelp();
1951
- process.exit(0);
1952
- }
1953
- }
1954
- }
1955
-
1956
- /**
1957
- * Takes an argument an returns its human readable equivalent for help usage.
1958
- *
1959
- * @param {Object} arg
1960
- * @return {String}
1961
- * @api private
1962
- */
1963
-
1964
- function humanReadableArgName(arg) {
1965
- var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
1966
-
1967
- return arg.required
1968
- ? '<' + nameOutput + '>'
1969
- : '[' + nameOutput + ']';
1970
- }
1971
-
1972
- // for versions before node v0.8 when there weren't `fs.existsSync`
1973
- function exists(file) {
1974
- try {
1975
- if (fs.statSync(file).isFile()) {
1976
- return true;
1977
- }
1978
- } catch (e) {
1979
- return false;
1980
- }
1981
- }
1982
- });
1983
-
1984
- var domain; // The domain module is executed on demand
1985
- var hasSetImmediate = typeof setImmediate === "function";
1986
-
1987
- // Use the fastest means possible to execute a task in its own turn, with
1988
- // priority over other events including network IO events in Node.js.
1989
- //
1990
- // An exception thrown by a task will permanently interrupt the processing of
1991
- // subsequent tasks. The higher level `asap` function ensures that if an
1992
- // exception is thrown by a task, that the task queue will continue flushing as
1993
- // soon as possible, but if you use `rawAsap` directly, you are responsible to
1994
- // either ensure that no exceptions are thrown from your task, or to manually
1995
- // call `rawAsap.requestFlush` if an exception is thrown.
1996
- var raw = rawAsap;
1997
- function rawAsap(task) {
1998
- if (!queue.length) {
1999
- requestFlush();
2000
- flushing = true;
2001
- }
2002
- // Avoids a function call
2003
- queue[queue.length] = task;
2004
- }
2005
-
2006
- var queue = [];
2007
- // Once a flush has been requested, no further calls to `requestFlush` are
2008
- // necessary until the next `flush` completes.
2009
- var flushing = false;
2010
- // The position of the next task to execute in the task queue. This is
2011
- // preserved between calls to `flush` so that it can be resumed if
2012
- // a task throws an exception.
2013
- var index = 0;
2014
- // If a task schedules additional tasks recursively, the task queue can grow
2015
- // unbounded. To prevent memory excaustion, the task queue will periodically
2016
- // truncate already-completed tasks.
2017
- var capacity = 1024;
2018
-
2019
- // The flush function processes all tasks that have been scheduled with
2020
- // `rawAsap` unless and until one of those tasks throws an exception.
2021
- // If a task throws an exception, `flush` ensures that its state will remain
2022
- // consistent and will resume where it left off when called again.
2023
- // However, `flush` does not make any arrangements to be called again if an
2024
- // exception is thrown.
2025
- function flush() {
2026
- while (index < queue.length) {
2027
- var currentIndex = index;
2028
- // Advance the index before calling the task. This ensures that we will
2029
- // begin flushing on the next task the task throws an error.
2030
- index = index + 1;
2031
- queue[currentIndex].call();
2032
- // Prevent leaking memory for long chains of recursive calls to `asap`.
2033
- // If we call `asap` within tasks scheduled by `asap`, the queue will
2034
- // grow, but to avoid an O(n) walk for every task we execute, we don't
2035
- // shift tasks off the queue after they have been executed.
2036
- // Instead, we periodically shift 1024 tasks off the queue.
2037
- if (index > capacity) {
2038
- // Manually shift all values starting at the index back to the
2039
- // beginning of the queue.
2040
- for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
2041
- queue[scan] = queue[scan + index];
2042
- }
2043
- queue.length -= index;
2044
- index = 0;
2045
- }
2046
- }
2047
- queue.length = 0;
2048
- index = 0;
2049
- flushing = false;
2050
- }
2051
-
2052
- rawAsap.requestFlush = requestFlush;
2053
- function requestFlush() {
2054
- // Ensure flushing is not bound to any domain.
2055
- // It is not sufficient to exit the domain, because domains exist on a stack.
2056
- // To execute code outside of any domain, the following dance is necessary.
2057
- var parentDomain = process.domain;
2058
- if (parentDomain) {
2059
- if (!domain) {
2060
- // Lazy execute the domain module.
2061
- // Only employed if the user elects to use domains.
2062
- domain = require$$0$1;
2063
- }
2064
- domain.active = process.domain = null;
2065
- }
2066
-
2067
- // `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
2068
- // cannot handle recursion.
2069
- // `requestFlush` will only be called recursively from `asap.js`, to resume
2070
- // flushing after an error is thrown into a domain.
2071
- // Conveniently, `setImmediate` was introduced in the same version
2072
- // `process.nextTick` started throwing recursion errors.
2073
- if (flushing && hasSetImmediate) {
2074
- setImmediate(flush);
2075
- } else {
2076
- process.nextTick(flush);
2077
- }
2078
-
2079
- if (parentDomain) {
2080
- domain.active = process.domain = parentDomain;
2081
- }
2082
- }
2083
-
2084
- function noop() {}
2085
-
2086
- // States:
2087
- //
2088
- // 0 - pending
2089
- // 1 - fulfilled with _value
2090
- // 2 - rejected with _value
2091
- // 3 - adopted the state of another promise, _value
2092
- //
2093
- // once the state is no longer pending (0) it is immutable
2094
-
2095
- // All `_` prefixed properties will be reduced to `_{random number}`
2096
- // at build time to obfuscate them and discourage their use.
2097
- // We don't use symbols or Object.defineProperty to fully hide them
2098
- // because the performance isn't good enough.
2099
-
2100
-
2101
- // to avoid using try/catch inside critical functions, we
2102
- // extract them to here.
2103
- var LAST_ERROR = null;
2104
- var IS_ERROR = {};
2105
- function getThen(obj) {
2106
- try {
2107
- return obj.then;
2108
- } catch (ex) {
2109
- LAST_ERROR = ex;
2110
- return IS_ERROR;
2111
- }
2112
- }
2113
-
2114
- function tryCallOne(fn, a) {
2115
- try {
2116
- return fn(a);
2117
- } catch (ex) {
2118
- LAST_ERROR = ex;
2119
- return IS_ERROR;
2120
- }
2121
- }
2122
- function tryCallTwo(fn, a, b) {
2123
- try {
2124
- fn(a, b);
2125
- } catch (ex) {
2126
- LAST_ERROR = ex;
2127
- return IS_ERROR;
2128
- }
2129
- }
2130
-
2131
- var core = Promise$1;
2132
-
2133
- function Promise$1(fn) {
2134
- if (typeof this !== 'object') {
2135
- throw new TypeError('Promises must be constructed via new');
2136
- }
2137
- if (typeof fn !== 'function') {
2138
- throw new TypeError('Promise constructor\'s argument is not a function');
2139
- }
2140
- this._75 = 0;
2141
- this._83 = 0;
2142
- this._18 = null;
2143
- this._38 = null;
2144
- if (fn === noop) return;
2145
- doResolve(fn, this);
2146
- }
2147
- Promise$1._47 = null;
2148
- Promise$1._71 = null;
2149
- Promise$1._44 = noop;
2150
-
2151
- Promise$1.prototype.then = function(onFulfilled, onRejected) {
2152
- if (this.constructor !== Promise$1) {
2153
- return safeThen(this, onFulfilled, onRejected);
2154
- }
2155
- var res = new Promise$1(noop);
2156
- handle(this, new Handler(onFulfilled, onRejected, res));
2157
- return res;
2158
- };
2159
-
2160
- function safeThen(self, onFulfilled, onRejected) {
2161
- return new self.constructor(function (resolve, reject) {
2162
- var res = new Promise$1(noop);
2163
- res.then(resolve, reject);
2164
- handle(self, new Handler(onFulfilled, onRejected, res));
2165
- });
2166
- }
2167
- function handle(self, deferred) {
2168
- while (self._83 === 3) {
2169
- self = self._18;
2170
- }
2171
- if (Promise$1._47) {
2172
- Promise$1._47(self);
2173
- }
2174
- if (self._83 === 0) {
2175
- if (self._75 === 0) {
2176
- self._75 = 1;
2177
- self._38 = deferred;
2178
- return;
2179
- }
2180
- if (self._75 === 1) {
2181
- self._75 = 2;
2182
- self._38 = [self._38, deferred];
2183
- return;
2184
- }
2185
- self._38.push(deferred);
2186
- return;
2187
- }
2188
- handleResolved(self, deferred);
2189
- }
2190
-
2191
- function handleResolved(self, deferred) {
2192
- raw(function() {
2193
- var cb = self._83 === 1 ? deferred.onFulfilled : deferred.onRejected;
2194
- if (cb === null) {
2195
- if (self._83 === 1) {
2196
- resolve(deferred.promise, self._18);
2197
- } else {
2198
- reject(deferred.promise, self._18);
2199
- }
2200
- return;
2201
- }
2202
- var ret = tryCallOne(cb, self._18);
2203
- if (ret === IS_ERROR) {
2204
- reject(deferred.promise, LAST_ERROR);
2205
- } else {
2206
- resolve(deferred.promise, ret);
2207
- }
2208
- });
2209
- }
2210
- function resolve(self, newValue) {
2211
- // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
2212
- if (newValue === self) {
2213
- return reject(
2214
- self,
2215
- new TypeError('A promise cannot be resolved with itself.')
2216
- );
2217
- }
2218
- if (
2219
- newValue &&
2220
- (typeof newValue === 'object' || typeof newValue === 'function')
2221
- ) {
2222
- var then = getThen(newValue);
2223
- if (then === IS_ERROR) {
2224
- return reject(self, LAST_ERROR);
2225
- }
2226
- if (
2227
- then === self.then &&
2228
- newValue instanceof Promise$1
2229
- ) {
2230
- self._83 = 3;
2231
- self._18 = newValue;
2232
- finale(self);
2233
- return;
2234
- } else if (typeof then === 'function') {
2235
- doResolve(then.bind(newValue), self);
2236
- return;
2237
- }
2238
- }
2239
- self._83 = 1;
2240
- self._18 = newValue;
2241
- finale(self);
2242
- }
2243
-
2244
- function reject(self, newValue) {
2245
- self._83 = 2;
2246
- self._18 = newValue;
2247
- if (Promise$1._71) {
2248
- Promise$1._71(self, newValue);
2249
- }
2250
- finale(self);
2251
- }
2252
- function finale(self) {
2253
- if (self._75 === 1) {
2254
- handle(self, self._38);
2255
- self._38 = null;
2256
- }
2257
- if (self._75 === 2) {
2258
- for (var i = 0; i < self._38.length; i++) {
2259
- handle(self, self._38[i]);
2260
- }
2261
- self._38 = null;
2262
- }
2263
- }
2264
-
2265
- function Handler(onFulfilled, onRejected, promise){
2266
- this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
2267
- this.onRejected = typeof onRejected === 'function' ? onRejected : null;
2268
- this.promise = promise;
2269
- }
2270
-
2271
- /**
2272
- * Take a potentially misbehaving resolver function and make sure
2273
- * onFulfilled and onRejected are only called once.
2274
- *
2275
- * Makes no guarantees about asynchrony.
2276
- */
2277
- function doResolve(fn, promise) {
2278
- var done = false;
2279
- var res = tryCallTwo(fn, function (value) {
2280
- if (done) return;
2281
- done = true;
2282
- resolve(promise, value);
2283
- }, function (reason) {
2284
- if (done) return;
2285
- done = true;
2286
- reject(promise, reason);
2287
- });
2288
- if (!done && res === IS_ERROR) {
2289
- done = true;
2290
- reject(promise, LAST_ERROR);
2291
- }
2292
- }
2293
-
2294
- core.prototype.done = function (onFulfilled, onRejected) {
2295
- var self = arguments.length ? this.then.apply(this, arguments) : this;
2296
- self.then(null, function (err) {
2297
- setTimeout(function () {
2298
- throw err;
2299
- }, 0);
2300
- });
2301
- };
2302
-
2303
- core.prototype['finally'] = function (f) {
2304
- return this.then(function (value) {
2305
- return core.resolve(f()).then(function () {
2306
- return value;
2307
- });
2308
- }, function (err) {
2309
- return core.resolve(f()).then(function () {
2310
- throw err;
2311
- });
2312
- });
2313
- };
2314
-
2315
- /* Static Functions */
2316
-
2317
- var TRUE = valuePromise(true);
2318
- var FALSE = valuePromise(false);
2319
- var NULL = valuePromise(null);
2320
- var UNDEFINED = valuePromise(undefined);
2321
- var ZERO = valuePromise(0);
2322
- var EMPTYSTRING = valuePromise('');
2323
-
2324
- function valuePromise(value) {
2325
- var p = new core(core._44);
2326
- p._83 = 1;
2327
- p._18 = value;
2328
- return p;
2329
- }
2330
- core.resolve = function (value) {
2331
- if (value instanceof core) return value;
2332
-
2333
- if (value === null) return NULL;
2334
- if (value === undefined) return UNDEFINED;
2335
- if (value === true) return TRUE;
2336
- if (value === false) return FALSE;
2337
- if (value === 0) return ZERO;
2338
- if (value === '') return EMPTYSTRING;
2339
-
2340
- if (typeof value === 'object' || typeof value === 'function') {
2341
- try {
2342
- var then = value.then;
2343
- if (typeof then === 'function') {
2344
- return new core(then.bind(value));
2345
- }
2346
- } catch (ex) {
2347
- return new core(function (resolve, reject) {
2348
- reject(ex);
2349
- });
2350
- }
2351
- }
2352
- return valuePromise(value);
2353
- };
2354
-
2355
- core.all = function (arr) {
2356
- var args = Array.prototype.slice.call(arr);
2357
-
2358
- return new core(function (resolve, reject) {
2359
- if (args.length === 0) return resolve([]);
2360
- var remaining = args.length;
2361
- function res(i, val) {
2362
- if (val && (typeof val === 'object' || typeof val === 'function')) {
2363
- if (val instanceof core && val.then === core.prototype.then) {
2364
- while (val._83 === 3) {
2365
- val = val._18;
2366
- }
2367
- if (val._83 === 1) return res(i, val._18);
2368
- if (val._83 === 2) reject(val._18);
2369
- val.then(function (val) {
2370
- res(i, val);
2371
- }, reject);
2372
- return;
2373
- } else {
2374
- var then = val.then;
2375
- if (typeof then === 'function') {
2376
- var p = new core(then.bind(val));
2377
- p.then(function (val) {
2378
- res(i, val);
2379
- }, reject);
2380
- return;
2381
- }
2382
- }
2383
- }
2384
- args[i] = val;
2385
- if (--remaining === 0) {
2386
- resolve(args);
2387
- }
2388
- }
2389
- for (var i = 0; i < args.length; i++) {
2390
- res(i, args[i]);
2391
- }
2392
- });
2393
- };
2394
-
2395
- core.reject = function (value) {
2396
- return new core(function (resolve, reject) {
2397
- reject(value);
2398
- });
2399
- };
2400
-
2401
- core.race = function (values) {
2402
- return new core(function (resolve, reject) {
2403
- values.forEach(function(value){
2404
- core.resolve(value).then(resolve, reject);
2405
- });
2406
- });
2407
- };
2408
-
2409
- /* Prototype Methods */
2410
-
2411
- core.prototype['catch'] = function (onRejected) {
2412
- return this.then(null, onRejected);
2413
- };
2414
-
2415
- var freeTasks = [];
2416
-
2417
- /**
2418
- * Calls a task as soon as possible after returning, in its own event, with
2419
- * priority over IO events. An exception thrown in a task can be handled by
2420
- * `process.on("uncaughtException") or `domain.on("error")`, but will otherwise
2421
- * crash the process. If the error is handled, all subsequent tasks will
2422
- * resume.
2423
- *
2424
- * @param {{call}} task A callable object, typically a function that takes no
2425
- * arguments.
2426
- */
2427
- var asap_1 = asap;
2428
- function asap(task) {
2429
- var rawTask;
2430
- if (freeTasks.length) {
2431
- rawTask = freeTasks.pop();
2432
- } else {
2433
- rawTask = new RawTask();
2434
- }
2435
- rawTask.task = task;
2436
- rawTask.domain = process.domain;
2437
- raw(rawTask);
2438
- }
2439
-
2440
- function RawTask() {
2441
- this.task = null;
2442
- this.domain = null;
2443
- }
2444
-
2445
- RawTask.prototype.call = function () {
2446
- if (this.domain) {
2447
- this.domain.enter();
2448
- }
2449
- var threw = true;
2450
- try {
2451
- this.task.call();
2452
- threw = false;
2453
- // If the task throws an exception (presumably) Node.js restores the
2454
- // domain stack for the next event.
2455
- if (this.domain) {
2456
- this.domain.exit();
2457
- }
2458
- } finally {
2459
- // We use try/finally and a threw flag to avoid messing up stack traces
2460
- // when we catch and release errors.
2461
- if (threw) {
2462
- // In Node.js, uncaught exceptions are considered fatal errors.
2463
- // Re-throw them to interrupt flushing!
2464
- // Ensure that flushing continues if an uncaught exception is
2465
- // suppressed listening process.on("uncaughtException") or
2466
- // domain.on("error").
2467
- raw.requestFlush();
2468
- }
2469
- // If the task threw an error, we do not want to exit the domain here.
2470
- // Exiting the domain would prevent the domain from catching the error.
2471
- this.task = null;
2472
- this.domain = null;
2473
- freeTasks.push(this);
2474
- }
2475
- };
2476
-
2477
- /* Static Functions */
2478
-
2479
- core.denodeify = function (fn, argumentCount) {
2480
- if (
2481
- typeof argumentCount === 'number' && argumentCount !== Infinity
2482
- ) {
2483
- return denodeifyWithCount(fn, argumentCount);
2484
- } else {
2485
- return denodeifyWithoutCount(fn);
2486
- }
2487
- };
2488
-
2489
- var callbackFn = (
2490
- 'function (err, res) {' +
2491
- 'if (err) { rj(err); } else { rs(res); }' +
2492
- '}'
2493
- );
2494
- function denodeifyWithCount(fn, argumentCount) {
2495
- var args = [];
2496
- for (var i = 0; i < argumentCount; i++) {
2497
- args.push('a' + i);
2498
- }
2499
- var body = [
2500
- 'return function (' + args.join(',') + ') {',
2501
- 'var self = this;',
2502
- 'return new Promise(function (rs, rj) {',
2503
- 'var res = fn.call(',
2504
- ['self'].concat(args).concat([callbackFn]).join(','),
2505
- ');',
2506
- 'if (res &&',
2507
- '(typeof res === "object" || typeof res === "function") &&',
2508
- 'typeof res.then === "function"',
2509
- ') {rs(res);}',
2510
- '});',
2511
- '};'
2512
- ].join('');
2513
- return Function(['Promise', 'fn'], body)(core, fn);
2514
- }
2515
- function denodeifyWithoutCount(fn) {
2516
- var fnLength = Math.max(fn.length - 1, 3);
2517
- var args = [];
2518
- for (var i = 0; i < fnLength; i++) {
2519
- args.push('a' + i);
2520
- }
2521
- var body = [
2522
- 'return function (' + args.join(',') + ') {',
2523
- 'var self = this;',
2524
- 'var args;',
2525
- 'var argLength = arguments.length;',
2526
- 'if (arguments.length > ' + fnLength + ') {',
2527
- 'args = new Array(arguments.length + 1);',
2528
- 'for (var i = 0; i < arguments.length; i++) {',
2529
- 'args[i] = arguments[i];',
2530
- '}',
2531
- '}',
2532
- 'return new Promise(function (rs, rj) {',
2533
- 'var cb = ' + callbackFn + ';',
2534
- 'var res;',
2535
- 'switch (argLength) {',
2536
- args.concat(['extra']).map(function (_, index) {
2537
- return (
2538
- 'case ' + (index) + ':' +
2539
- 'res = fn.call(' + ['self'].concat(args.slice(0, index)).concat('cb').join(',') + ');' +
2540
- 'break;'
2541
- );
2542
- }).join(''),
2543
- 'default:',
2544
- 'args[argLength] = cb;',
2545
- 'res = fn.apply(self, args);',
2546
- '}',
2547
-
2548
- 'if (res &&',
2549
- '(typeof res === "object" || typeof res === "function") &&',
2550
- 'typeof res.then === "function"',
2551
- ') {rs(res);}',
2552
- '});',
2553
- '};'
2554
- ].join('');
2555
-
2556
- return Function(
2557
- ['Promise', 'fn'],
2558
- body
2559
- )(core, fn);
2560
- }
2561
-
2562
- core.nodeify = function (fn) {
2563
- return function () {
2564
- var args = Array.prototype.slice.call(arguments);
2565
- var callback =
2566
- typeof args[args.length - 1] === 'function' ? args.pop() : null;
2567
- var ctx = this;
2568
- try {
2569
- return fn.apply(this, arguments).nodeify(callback, ctx);
2570
- } catch (ex) {
2571
- if (callback === null || typeof callback == 'undefined') {
2572
- return new core(function (resolve, reject) {
2573
- reject(ex);
2574
- });
2575
- } else {
2576
- asap_1(function () {
2577
- callback.call(ctx, ex);
2578
- });
2579
- }
2580
- }
2581
- }
2582
- };
2583
-
2584
- core.prototype.nodeify = function (callback, ctx) {
2585
- if (typeof callback != 'function') return this;
2586
-
2587
- this.then(function (value) {
2588
- asap_1(function () {
2589
- callback.call(ctx, null, value);
2590
- });
2591
- }, function (err) {
2592
- asap_1(function () {
2593
- callback.call(ctx, err);
2594
- });
2595
- });
2596
- };
2597
-
2598
- core.enableSynchronous = function () {
2599
- core.prototype.isPending = function() {
2600
- return this.getState() == 0;
2601
- };
2602
-
2603
- core.prototype.isFulfilled = function() {
2604
- return this.getState() == 1;
2605
- };
2606
-
2607
- core.prototype.isRejected = function() {
2608
- return this.getState() == 2;
2609
- };
2610
-
2611
- core.prototype.getValue = function () {
2612
- if (this._83 === 3) {
2613
- return this._18.getValue();
2614
- }
2615
-
2616
- if (!this.isFulfilled()) {
2617
- throw new Error('Cannot get a value of an unfulfilled promise.');
2618
- }
2619
-
2620
- return this._18;
2621
- };
2622
-
2623
- core.prototype.getReason = function () {
2624
- if (this._83 === 3) {
2625
- return this._18.getReason();
2626
- }
2627
-
2628
- if (!this.isRejected()) {
2629
- throw new Error('Cannot get a rejection reason of a non-rejected promise.');
2630
- }
2631
-
2632
- return this._18;
2633
- };
2634
-
2635
- core.prototype.getState = function () {
2636
- if (this._83 === 3) {
2637
- return this._18.getState();
2638
- }
2639
- if (this._83 === -1 || this._83 === -2) {
2640
- return 0;
2641
- }
2642
-
2643
- return this._83;
2644
- };
2645
- };
2646
-
2647
- core.disableSynchronous = function() {
2648
- core.prototype.isPending = undefined;
2649
- core.prototype.isFulfilled = undefined;
2650
- core.prototype.isRejected = undefined;
2651
- core.prototype.getValue = undefined;
2652
- core.prototype.getReason = undefined;
2653
- core.prototype.getState = undefined;
2654
- };
2655
-
2656
- var lib = core;
2657
-
2658
- var promise = lib;
2659
-
2660
- /**
2661
- * @license
2662
- * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
2663
- *
2664
- * Licensed under the Apache License, Version 2.0 (the "License");
2665
- * you may not use this file except in compliance with the License.
2666
- * You may obtain a copy of the License at
2667
- *
2668
- * http://www.apache.org/licenses/LICENSE-2.0
2669
- *
2670
- * Unless required by applicable law or agreed to in writing, software
2671
- * distributed under the License is distributed on an "AS-IS" BASIS,
2672
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2673
- * See the License for the specific language governing permissions and
2674
- * limitations under the license.
2675
- */
2676
-
2677
-
2678
-
2679
-
2680
-
2681
-
2682
-
2683
-
2684
-
2685
-
2686
-
2687
-
2688
-
2689
- const DEFAULT_USER_AGENT = 'amphtml-validator';
2690
-
2691
- /**
2692
- * Determines if str begins with prefix.
2693
- * @param {string} str
2694
- * @param {string} prefix
2695
- * @return {boolean}
2696
- */
2697
- function hasPrefix(str, prefix) {
2698
- return str.indexOf(prefix) == 0;
2699
- }
2700
-
2701
- /**
2702
- * Convenience function to detect whether an argument is a URL. If not,
2703
- * it may be a local file.
2704
- * @param {string} url
2705
- * @return {boolean}
2706
- */
2707
- function isHttpOrHttpsUrl(url) {
2708
- return hasPrefix(url, 'http://') || hasPrefix(url, 'https://');
2709
- }
2710
-
2711
- /**
2712
- * Creates a promise which reads from a file.
2713
- * @param {string} name
2714
- * @return {Promise<string>}
2715
- */
2716
- function readFromFile(name) {
2717
- return new promise(function(resolve, reject) {
2718
- fs.readFile(name, 'utf8', function(err, data) {
2719
- if (err) {
2720
- reject(err);
2721
- } else {
2722
- resolve(data.trim());
2723
- }
2724
- });
2725
- });
2726
- }
2727
-
2728
- /**
2729
- * Creates a promise which reads from a stream.
2730
- * @param {string} name
2731
- * @param {!stream.Readable} readable
2732
- * @return {Promise<string>}
2733
- */
2734
- function readFromReadable(name, readable) {
2735
- return new promise(function(resolve, reject) {
2736
- const chunks = [];
2737
- readable.setEncoding('utf8');
2738
- readable.on('data', function(chunk) {
2739
- chunks.push(chunk);
2740
- });
2741
- readable.on('end', function() {
2742
- resolve(chunks.join(''));
2743
- });
2744
- readable.on('error', function(error) {
2745
- reject(new Error('Could not read from ' + name + ' - ' + error.message));
2746
- });
2747
- });
2748
- }
2749
-
2750
- /**
2751
- * Creates a promise which reads from standard input. Even though it would
2752
- * be easy to make a function that just returns the data, we return a promise
2753
- * for consistency with readFromUrl and readFromFile.
2754
- * @return {Promise<string>}
2755
- */
2756
- function readFromStdin() {
2757
- return readFromReadable('stdin', process.stdin).then(function(data) {
2758
- process.stdin.resume();
2759
- return data;
2760
- });
2761
- }
2762
-
2763
- /**
2764
- * Creates a promise which reads from a URL or more precisely, fetches
2765
- * the contents located at the URL by using the 'http' or 'https' module.
2766
- * Any HTTP status other than 200 is interpreted as an error.
2767
- * @param {string} url
2768
- * @param {string} userAgent
2769
- * @return {Promise<string>}
2770
- */
2771
- function readFromUrl(url, userAgent) {
2772
- return new promise(function(resolve, reject) {
2773
- const clientModule = hasPrefix(url, 'http://') ? http : https;
2774
- const req = clientModule.request(url, function(response) {
2775
- if (response.statusCode !== 200) {
2776
- // https://nodejs.org/api/http.html says: "[...] However, if
2777
- // you add a 'response' event handler, then you must consume
2778
- // the data from the response object, either by calling
2779
- // response.read() whenever there is a 'readable' event, or by
2780
- // adding a 'data' handler, or by calling the .resume()
2781
- // method."
2782
- response.resume();
2783
- reject(new Error(
2784
- 'Unable to fetch ' + url + ' - HTTP Status ' +
2785
- response.statusCode));
2786
- } else {
2787
- resolve(response);
2788
- }
2789
- });
2790
- req.setHeader('User-Agent', userAgent);
2791
- req.on('error', function(error) { // E.g., DNS resolution errors.
2792
- reject(
2793
- new Error('Unable to fetch ' + url + ' - ' + error.message));
2794
- });
2795
- req.end();
2796
- })
2797
- .then(readFromReadable.bind(null, url));
2798
- }
2799
-
2800
- /**
2801
- * ValidationResult is the record computed by the validator for each
2802
- * document. It contains an overall status (PASS/FAIL) and the list of
2803
- * errors, if any. This class corresponds to the ValidationResult
2804
- * message in validator.proto in this directory.
2805
- * @export
2806
- * @constructor
2807
- */
2808
- function ValidationResult() {
2809
- /**
2810
- * Possible values are 'UNKNOWN', 'PASS', and 'FAIL'.
2811
- * @type {string}
2812
- */
2813
- this.status = 'UNKNOWN';
2814
- /** @type {!Array<!ValidationError>} */
2815
- this.errors = [];
2816
- }
2817
-
2818
- /**
2819
- * Each validation error describes a specific problem in a validated
2820
- * document. This class corresponds to the ValidationError message in
2821
- * validator.proto in this directory.
2822
- * @export
2823
- * @constructor
2824
- */
2825
- function ValidationError() {
2826
- /**
2827
- * The severity of the error - possible values are 'UNKNOWN_SEVERITY',
2828
- * 'ERROR', and 'WARNING'.
2829
- */
2830
- this.severity = 'UNKNOWN_SEVERITY';
2831
- /**
2832
- * The line number at which the error was seen (1 is the first line).
2833
- */
2834
- this.line = 1;
2835
- /**
2836
- * The column number at which the error was seen (0 is the first column).
2837
- */
2838
- this.col = 0;
2839
- /**
2840
- * A human-readable error message for the validation error.
2841
- * If you find yourself trying to write a parser against this string
2842
- * to scrape out some detail, consider looking at the code and params
2843
- * fields below.
2844
- * @type {string}
2845
- */
2846
- this.message = '';
2847
- /**
2848
- * The spec URL is often added by the validator to provide additional
2849
- * context for the error. In a user interface this would be shown
2850
- * as a "Learn more" link.
2851
- * @type {string}
2852
- */
2853
- this.specUrl = null;
2854
- /**
2855
- * This field is only useful when scripting against the validator,
2856
- * it should not be displayed in a user interface as it adds nothing
2857
- * for humans to read over the message field (see above).
2858
- * Possible values are the codes listed in ValidationError.Code - see
2859
- * validator.proto. Examples: 'UNKNOWN_CODE', 'MANDATORY_TAG_MISSING',
2860
- * 'TAG_REQUIRED_BY_MISSING'. For each of these codes there is a
2861
- * format string in validator-main.protoascii (look for error_formats),
2862
- * which is used to assemble the message from the strings in params.
2863
- * @type {string}
2864
- */
2865
- this.code = 'UNKNOWN_CODE';
2866
- /**
2867
- * This field is only useful when scripting against the validator,
2868
- * it should not be displayed in a user interface as it adds nothing
2869
- * for humans to read over the message field (see above).
2870
- * @type {!Array<string>}
2871
- */
2872
- this.params = [];
2873
- }
2874
-
2875
- /**
2876
- * The validator instance is a proxy object to a precompiled
2877
- * validator.js script - in practice the script was either downloaded
2878
- * from 'https://cdn.ampproject.org/v0/validator.js' or read from a
2879
- * local file.
2880
- * @param {string} scriptContents
2881
- * @throws {!Error}
2882
- * @constructor
2883
- */
2884
- function Validator(scriptContents) {
2885
- // The 'sandbox' is a Javascript object (dictionary) which holds
2886
- // the results of evaluating the validatorJs / scriptContents, so
2887
- // basically, it holds functions, prototypes, etc. As a
2888
- // side-effect of evaluating, the VM will compile this code and
2889
- // it's worth holding onto it. Hence, this validate function is
2890
- // reached via 2 codepaths - either the sandbox came from the
2891
- // cache, precompiledByValidatorJs - or we just varructed it
2892
- // after downloading and evaluating the script. The API is fancier
2893
- // here, vm.Script / vm.createContext / vm.runInContext and all
2894
- // that, but it's quite similar to a Javascript eval.
2895
- this.sandbox = vm.createContext();
2896
- try {
2897
- new vm.Script(scriptContents).runInContext(this.sandbox);
2898
- } catch (error) {
2899
- throw new Error('Could not instantiate validator.js - ' + error.message);
2900
- }
2901
- }
2902
-
2903
- /**
2904
- * Validates the provided inputString; the htmlFormat can be 'AMP' or
2905
- * 'AMP4ADS'; it defaults to 'AMP' if not specified.
2906
- * @param {string} inputString
2907
- * @param {string=} htmlFormat
2908
- * @return {!ValidationResult}
2909
- * @export
2910
- */
2911
- Validator.prototype.validateString = function(inputString, htmlFormat) {
2912
- const internalResult =
2913
- this.sandbox.amp.validator.validateString(inputString, htmlFormat);
2914
- const result = new ValidationResult();
2915
- result.status = internalResult.status;
2916
- for (let ii = 0; ii < internalResult.errors.length; ii++) {
2917
- const internalError = internalResult.errors[ii];
2918
- const error = new ValidationError();
2919
- error.severity = internalError.severity;
2920
- error.line = internalError.line;
2921
- error.col = internalError.col;
2922
- error.message =
2923
- this.sandbox.amp.validator.renderErrorMessage(internalError);
2924
- error.specUrl = internalError.specUrl;
2925
- error.code = internalError.code;
2926
- error.params = internalError.params;
2927
- result.errors.push(error);
2928
- }
2929
- return result;
2930
- };
2931
-
2932
- /**
2933
- * A global static map used by the getInstance function to avoid loading
2934
- * AMP Validators more than once.
2935
- * @type {!Object<string, Validator>}
2936
- */
2937
- const instanceByValidatorJs = {};
2938
-
2939
- /**
2940
- * Provided a URL or a filename from which to fetch the validator.js
2941
- * file, fetches, instantiates, and caches the validator instance
2942
- * asynchronously. If you prefer to implement your own fetching /
2943
- * caching logic, you may want to consider newInstance() instead,
2944
- * which is synchronous and much simpler.
2945
- *
2946
- * @param {string=} opt_validatorJs
2947
- * @param {string=} opt_userAgent
2948
- * @return {!Promise<Validator>}
2949
- * @export
2950
- */
2951
- function getInstance(opt_validatorJs, opt_userAgent) {
2952
- const validatorJs =
2953
- opt_validatorJs || 'https://cdn.ampproject.org/v0/validator.js';
2954
- const userAgent = opt_userAgent || DEFAULT_USER_AGENT;
2955
- if (instanceByValidatorJs.hasOwnProperty(validatorJs)) {
2956
- return promise.resolve(instanceByValidatorJs[validatorJs]);
2957
- }
2958
- const validatorJsPromise = isHttpOrHttpsUrl(validatorJs) ?
2959
- readFromUrl(validatorJs, userAgent) :
2960
- readFromFile(validatorJs);
2961
- return validatorJsPromise.then(function(scriptContents) {
2962
- let instance;
2963
- try {
2964
- instance = new Validator(scriptContents);
2965
- } catch (error) {
2966
- // It may be useful to cache errors and exceptions encountered
2967
- // here, but for now we don't do this for e.g. http errors when
2968
- // fetching the validator, so we shouldn't do it for syntax
2969
- // errors etc. either (which lead to the varructor throwing an error).
2970
- throw error;
2971
- }
2972
- instanceByValidatorJs[validatorJs] = instance;
2973
- return instance;
2974
- });
2975
- }
2976
- var getInstance_1 = getInstance;
2977
-
2978
- /**
2979
- * Provided the contents of the validator.js file, e.g. as downloaded from
2980
- * 'https://cdn.ampproject.org/v0/validator.js', returns a new validator
2981
- * instance. The tradeoff between this function and getInstance() is that this
2982
- * function is synchronous but requires the contents of the validator.js
2983
- * file as a parameter, while getInstance is asynchronous, fetches files
2984
- * from disk or the web, and caches them.
2985
- *
2986
- * @param {string} validatorJsContents
2987
- * @return {!Validator}
2988
- * @export
2989
- */
2990
- function newInstance(validatorJsContents) {
2991
- return new Validator(validatorJsContents);
2992
- }
2993
- var newInstance_1 = newInstance;
2994
-
2995
- // A note on emitting output to the console and process exit status:
2996
- // Node.js prior to 0.11.8 did not support process.exitCode
2997
- // (https://nodejs.org/api/process.html#process_process_exitcode), which
2998
- // makes it difficult to emit output and errors from multiple callbacks
2999
- // and set the appropriate exit code. We use the following workaround:
3000
- // process.<<stream>>(<<some output>>, function() { process.exit(<<code>>); });
3001
- // This will flush the appropriate stream (stdout or stderr) and then
3002
- // exit with the provided code. For now, this makes the CLI work with
3003
- // Node.js versions as old as v0.10.25.
3004
-
3005
- /**
3006
- * Logs a validation result to the console using process.stdout and
3007
- * process.stderr as is appropriate.
3008
- * @param {string} filename
3009
- * @param {!ValidationResult} validationResult
3010
- * @param {boolean} color
3011
- */
3012
- function logValidationResult(filename, validationResult, color) {
3013
- if (validationResult.status === 'PASS') {
3014
- process.stdout.write(
3015
- filename + ': ' + (color ? safe.green('PASS') : 'PASS') + '\n');
3016
- }
3017
- for (let ii = 0; ii < validationResult.errors.length; ii++) {
3018
- const error = validationResult.errors[ii];
3019
- let msg = filename + ':' + error.line + ':' + error.col + ' ';
3020
- if (color) {
3021
- msg += (error.severity === 'ERROR' ? safe.red : safe.magenta)(
3022
- error.message);
3023
- } else {
3024
- msg += error.message;
3025
- }
3026
- if (error.specUrl) {
3027
- msg += ' (see ' + error.specUrl + ')';
3028
- }
3029
- // TODO(powdercloud): Should we distinguish error.severity === 'WARNING' ?
3030
- process.stderr.write(msg + '\n');
3031
- }
3032
- }
3033
-
3034
- /**
3035
- * Main entry point into the command line tool.
3036
- */
3037
- function main() {
3038
- commander
3039
- .usage(
3040
- '[options] <fileOrUrlOrMinus...>\n\n' +
3041
- ' Validates the files or urls provided as arguments. If "-" is\n' +
3042
- ' specified, reads from stdin instead.')
3043
- .option(
3044
- '--validator_js <fileOrUrl>',
3045
- 'The Validator Javascript.\n' +
3046
- ' Latest published version by default, or\n' +
3047
- ' dist/validator_minified.js (built with build.py)\n' +
3048
- ' for development.',
3049
- 'https://cdn.ampproject.org/v0/validator.js')
3050
- .option(
3051
- '--user-agent <userAgent>', 'User agent string to use in requests.',
3052
- DEFAULT_USER_AGENT)
3053
- .option(
3054
- '--html_format <AMP|AMP4ADS|AMP4EMAIL>',
3055
- 'The input format to be validated.\n' +
3056
- ' AMP by default.',
3057
- 'AMP')
3058
- .option(
3059
- '--format <color|text|json>',
3060
- 'How to format the output.\n' +
3061
- ' "color" displays errors/warnings/success in\n' +
3062
- ' red/orange/green.\n' +
3063
- ' "text" avoids color (e.g., useful in terminals not\n' +
3064
- ' supporting color).\n' +
3065
- ' "json" emits json corresponding to the ValidationResult\n' +
3066
- ' message in validator.proto.',
3067
- 'color')
3068
- .parse(process.argv);
3069
- if (commander.args.length === 0) {
3070
- commander.outputHelp();
3071
- process.exit(1);
3072
- }
3073
- if (commander.html_format !== 'AMP' && commander.html_format !== 'AMP4ADS' &&
3074
- commander.html_format !== 'AMP4EMAIL') {
3075
- process.stderr.write(
3076
- '--html_format must be set to "AMP", "AMP4ADS", or "AMP4EMAIL".\n',
3077
- function() {
3078
- process.exit(1);
3079
- });
3080
- }
3081
- if (commander.format !== 'color' && commander.format !== 'text' &&
3082
- commander.format !== 'json') {
3083
- process.stderr.write(
3084
- '--format must be set to "color", "text", or "json".\n', function() {
3085
- process.exit(1);
3086
- });
3087
- }
3088
- const inputs = [];
3089
- for (let ii = 0; ii < commander.args.length; ii++) {
3090
- const item = commander.args[ii];
3091
- if (item === '-') {
3092
- inputs.push(readFromStdin());
3093
- } else if (isHttpOrHttpsUrl(item)) {
3094
- inputs.push(readFromUrl(item, commander.userAgent));
3095
- } else {
3096
- inputs.push(readFromFile(item));
3097
- }
3098
- }
3099
- getInstance(commander.validator_js, commander.userAgent)
3100
- .then(function(validator) {
3101
- promise.all(inputs)
3102
- .then(function(resolvedInputs) {
3103
- const jsonOut = {};
3104
- let hasError = false;
3105
- for (let ii = 0; ii < resolvedInputs.length; ii++) {
3106
- const validationResult = validator.validateString(
3107
- resolvedInputs[ii], commander.html_format);
3108
- if (commander.format === 'json') {
3109
- jsonOut[commander.args[ii]] = validationResult;
3110
- } else {
3111
- logValidationResult(
3112
- commander.args[ii], validationResult,
3113
- commander.format === 'color' ? true : false);
3114
- }
3115
- if (validationResult.status !== 'PASS') {
3116
- hasError = true;
3117
- }
3118
- }
3119
- if (commander.format === 'json') {
3120
- process.stdout.write(
3121
- JSON.stringify(jsonOut) + '\n', function() {
3122
- process.exit(hasError ? 1 : 0);
3123
- });
3124
- } else if (hasError) {
3125
- process.stderr.write('', function() {
3126
- process.exit(1);
3127
- });
3128
- } else {
3129
- process.stdout.write('', function() {
3130
- process.exit(0);
3131
- });
3132
- }
3133
- })
3134
- .catch(function(error) {
3135
- process.stderr.write(
3136
- (commander.format == 'color' ? safe.red(error.message) :
3137
- error.message) +
3138
- '\n',
3139
- function() {
3140
- process.exit(1);
3141
- });
3142
- });
3143
- })
3144
- .catch(function(error) {
3145
- process.stderr.write(
3146
- (commander.format == 'color' ? safe.red(error.message) :
3147
- error.message) +
3148
- '\n',
3149
- function() {
3150
- process.exit(1);
3151
- });
3152
- });
3153
- }
3154
-
3155
- var main_1 = main;
3156
-
3157
- var amphtmlValidator = {
3158
- getInstance: getInstance_1,
3159
- newInstance: newInstance_1,
3160
- main: main_1
3161
- };
3162
-
3163
- function dev(opts) {
3164
- return new Watcher(opts).init();
3165
- }
3166
-
3167
- const dev_dir = '.svelte/dev';
3168
-
3169
- class Watcher extends EventEmitter {
3170
- constructor({ port, config }) {
3171
- super();
3172
-
3173
- this.port = port;
3174
- this.config = config;
3175
-
3176
- process.env.NODE_ENV = 'development';
3177
-
3178
- process.on('exit', () => {
3179
- this.close();
3180
- });
3181
- }
3182
-
3183
- async init() {
3184
- rimraf(dev_dir);
3185
-
3186
- copy_assets(dev_dir);
3187
-
3188
- // TODO move this (and copy_assets?) into create_app
3189
- // prettier-ignore
3190
- writeFileSync(`${dev_dir}/runtime/app/env.js`, [
3191
- 'export const browser = !import.meta.env.SSR;',
3192
- 'export const dev = true;',
3193
- `export const amp = ${this.config.amp};`
3194
- ].join('\n'));
3195
-
3196
- await this.init_filewatcher();
3197
- await this.init_server();
3198
-
3199
- this.update();
3200
-
3201
- return this;
3202
- }
3203
-
3204
- async init_filewatcher() {
3205
- this.cheapwatch = new CheapWatch({
3206
- dir: this.config.files.routes,
3207
- filter: ({ path }) => path.split('/').every((part) => !part.startsWith('_'))
3208
- });
3209
-
3210
- await this.cheapwatch.init();
3211
-
3212
- // not sure why TS doesn't understand that CheapWatch extends EventEmitter
3213
- this.cheapwatch.on('+', ({ isNew }) => {
3214
- if (isNew) this.update();
3215
- });
3216
-
3217
- this.cheapwatch.on('-', () => {
3218
- this.update();
3219
- });
3220
- }
3221
-
3222
- async init_server() {
3223
- /**
3224
- * @type {vite.ViteDevServer}
3225
- */
3226
- this.viteDevServer = await vite.createServer({
3227
- resolve: {
3228
- alias: {
3229
- $app: resolve$1(`${dev_dir}/runtime/app`)
3230
- }
3231
- },
3232
- plugins: [
3233
- svelte({
3234
- emitCss: true,
3235
- compilerOptions: {
3236
- dev: true,
3237
- hydratable: true
3238
- },
3239
- hot: true
3240
- })
3241
- ],
3242
- publicDir: this.config.files.assets,
3243
- server: {
3244
- middlewareMode: true
3245
- }
3246
- });
3247
-
3248
- const { set_paths } = await this.viteDevServer.ssrLoadModule(
3249
- `/${dev_dir}/runtime/internal/singletons.js`
3250
- );
3251
-
3252
- set_paths(this.config.paths);
3253
-
3254
- const validator = this.config.amp && (await amphtmlValidator.getInstance());
3255
-
3256
- this.server = http.createServer((req, res) => {
3257
- this.viteDevServer.middlewares(req, res, async () => {
3258
- try {
3259
- const parsed = parse(req.originalUrl);
3260
-
3261
- if (req.originalUrl === '/favicon.ico') return;
3262
-
3263
- // handle dynamic requests - i.e. pages and endpoints
3264
- const template = readFileSync(this.config.files.template, 'utf-8');
3265
-
3266
- const setup = await this.viteDevServer
3267
- .ssrLoadModule(`/${this.config.files.setup}`)
3268
- .catch(() => ({}));
3269
-
3270
- let root;
3271
-
3272
- try {
3273
- root = (await this.viteDevServer.ssrLoadModule(`/${dev_dir}/generated/root.svelte`))
3274
- .default;
3275
- } catch (e) {
3276
- res.statusCode = 500;
3277
- res.end(e.stack);
3278
- return;
3279
- }
3280
-
3281
- const body = await get_body(req);
3282
-
3283
- const rendered = await render(
3284
- {
3285
- headers: req.headers,
3286
- method: req.method,
3287
- path: parsed.pathname,
3288
- query: new URLSearchParams(parsed.query),
3289
- body
3290
- },
3291
- {
3292
- paths: this.config.paths,
3293
- template: ({ head, body }) => {
3294
- let rendered = template
3295
- .replace('%svelte.head%', () => head)
3296
- .replace('%svelte.body%', () => body);
3297
-
3298
- if (this.config.amp) {
3299
- const result = validator.validateString(rendered);
3300
-
3301
- if (result.status !== 'PASS') {
3302
- const lines = rendered.split('\n');
3303
-
3304
- const escape = (str) =>
3305
- str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3306
-
3307
- rendered = `<!doctype html>
3308
- <head>
3309
- <meta charset="utf-8" />
3310
- <meta name="viewport" content="width=device-width, initial-scale=1" />
3311
- <style>
3312
- body {
3313
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
3314
- color: #333;
3315
- }
3316
-
3317
- pre {
3318
- background: #f4f4f4;
3319
- padding: 1em;
3320
- overflow-x: auto;
3321
- }
3322
- </style>
3323
- </head>
3324
- <h1>AMP validation failed</h1>
3325
-
3326
- ${result.errors
3327
- .map(
3328
- (error) => `
3329
- <h2>${error.severity}</h2>
3330
- <p>Line ${error.line}, column ${error.col}: ${error.message} (<a href="${error.specUrl}">${
3331
- error.code
3332
- }</a>)</p>
3333
- <pre>${escape(lines[error.line - 1])}</pre>
3334
- `
3335
- )
3336
- .join('\n\n')}
3337
- `;
3338
- }
3339
- }
3340
-
3341
- return rendered;
3342
- },
3343
- manifest: this.manifest,
3344
- target: this.config.target,
3345
- entry: `/${dev_dir}/runtime/internal/start.js`,
3346
- dev: true,
3347
- amp: this.config.amp,
3348
- root,
3349
- setup,
3350
- only_prerender: false,
3351
- start_global: this.config.startGlobal,
3352
- host: this.config.host,
3353
- host_header: this.config.hostHeader,
3354
- get_stack: (error) => {
3355
- this.viteDevServer.ssrFixStacktrace(error);
3356
- return error.stack;
3357
- },
3358
- get_static_file: (file) => readFileSync(join(this.config.files.assets, file)),
3359
- get_amp_css: (url) => '' // TODO: implement this
3360
- }
3361
- );
3362
-
3363
- if (rendered) {
3364
- res.writeHead(rendered.status, rendered.headers);
3365
- res.end(rendered.body);
3366
- } else {
3367
- res.statusCode = 404;
3368
- res.end('Not found');
3369
- }
3370
- } catch (e) {
3371
- this.viteDevServer.ssrFixStacktrace(e);
3372
- res.end(e.stack);
3373
- }
3374
- });
3375
- });
3376
-
3377
- this.server.listen(this.port);
3378
- }
3379
-
3380
- update() {
3381
- const manifest_data = create_manifest_data({
3382
- config: this.config,
3383
- output: dev_dir
3384
- });
3385
-
3386
- create_app({
3387
- manifest_data,
3388
- output: dev_dir
3389
- });
3390
-
3391
- const common_css_deps = new Set();
3392
-
3393
- const load = async (url) => {
3394
- const mod = await this.viteDevServer.ssrLoadModule(url);
3395
- const node = await this.viteDevServer.moduleGraph.getModuleByUrl(url);
3396
-
3397
- const deps = new Set();
3398
- find_deps(node, deps);
3399
-
3400
- const css = new Set();
3401
- for (const dep of deps) {
3402
- // TODO what about .scss files, etc?
3403
- if (dep.file.endsWith('.css')) {
3404
- const mod = await this.viteDevServer.ssrLoadModule(dep.url);
3405
- css.add(mod.default);
3406
- }
3407
- }
3408
-
3409
- return { mod, css };
3410
- };
3411
-
3412
- const find_deps = (node, deps) => {
3413
- for (const dep of node.importedModules) {
3414
- if (!deps.has(dep)) {
3415
- deps.add(dep);
3416
- find_deps(dep, deps);
3417
- }
3418
- }
3419
- };
3420
-
3421
- this.manifest = {
3422
- assets: manifest_data.assets,
3423
- layout: async () => {
3424
- const { mod, css } = await load(manifest_data.layout);
3425
- css.forEach((mod) => {
3426
- common_css_deps.add(mod);
3427
- });
3428
- return mod;
3429
- },
3430
- error: async () => {
3431
- const { mod, css } = await load(manifest_data.error);
3432
- css.forEach((mod) => {
3433
- common_css_deps.add(mod);
3434
- });
3435
- return mod;
3436
- },
3437
- pages: manifest_data.pages.map((data) => {
3438
- // This is a bit of a hack, but it means we can inject the correct <style>
3439
- // contents without needing to do any analysis before loading
3440
- const css_deps = new Set();
3441
-
3442
- return {
3443
- pattern: data.pattern,
3444
- params: get_params(data.params),
3445
- parts: data.parts.map((file) => async () => {
3446
- const { mod, css } = await load(file);
3447
-
3448
- css.forEach((mod) => {
3449
- css_deps.add(mod);
3450
- });
3451
-
3452
- return mod;
3453
- }),
3454
- get style() {
3455
- return [...common_css_deps, ...css_deps].join('\n');
3456
- },
3457
- css: [],
3458
- js: []
3459
- };
3460
- }),
3461
- endpoints: manifest_data.endpoints.map((data) => ({
3462
- pattern: data.pattern,
3463
- params: get_params(data.params),
3464
- load: async () => await this.viteDevServer.ssrLoadModule(data.file)
3465
- }))
3466
- };
3467
- }
3468
-
3469
- close() {
3470
- if (this.closed) return;
3471
- this.closed = true;
3472
-
3473
- this.viteDevServer.close();
3474
- this.server.close();
3475
- this.cheapwatch.close();
3476
- }
3477
- }
3478
-
3479
- // given an array of params like `['x', 'y', 'z']` for
3480
- // src/routes/[x]/[y]/[z]/svelte, create a function
3481
- // that turns a RexExpMatchArray into ({ x, y, z })
3482
- function get_params(array) {
3483
- return (match) => {
3484
- const params = {};
3485
- array.forEach((key, i) => {
3486
- if (key.startsWith('...')) {
3487
- params[key.slice(3)] = decodeURIComponent(match[i + 1]).split('/');
3488
- } else {
3489
- params[key] = decodeURIComponent(match[i + 1]);
3490
- }
3491
- });
3492
- return params;
3493
- };
3494
- }
3495
-
3496
- export { dev };
3497
- //# sourceMappingURL=index2.js.map