1 (function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (function(modules) { // webpackBootstrap
2 /******/ // The module cache
3 /******/ var installedModules = {};
5 /******/ // The require function
6 /******/ function __webpack_require__(moduleId) {
8 /******/ // Check if module is in cache
9 /******/ if(installedModules[moduleId]) {
10 /******/ return installedModules[moduleId].exports;
12 /******/ // Create a new module (and put it into the cache)
13 /******/ var module = installedModules[moduleId] = {
19 /******/ // Execute the module function
20 /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
22 /******/ // Flag the module as loaded
23 /******/ module.l = true;
25 /******/ // Return the exports of the module
26 /******/ return module.exports;
30 /******/ // expose the modules object (__webpack_modules__)
31 /******/ __webpack_require__.m = modules;
33 /******/ // expose the module cache
34 /******/ __webpack_require__.c = installedModules;
36 /******/ // define getter function for harmony exports
37 /******/ __webpack_require__.d = function(exports, name, getter) {
38 /******/ if(!__webpack_require__.o(exports, name)) {
39 /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
43 /******/ // define __esModule on exports
44 /******/ __webpack_require__.r = function(exports) {
45 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
46 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
48 /******/ Object.defineProperty(exports, '__esModule', { value: true });
51 /******/ // create a fake namespace object
52 /******/ // mode & 1: value is a module id, require it
53 /******/ // mode & 2: merge all properties of value into the ns
54 /******/ // mode & 4: return value when already ns object
55 /******/ // mode & 8|1: behave like require
56 /******/ __webpack_require__.t = function(value, mode) {
57 /******/ if(mode & 1) value = __webpack_require__(value);
58 /******/ if(mode & 8) return value;
59 /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
60 /******/ var ns = Object.create(null);
61 /******/ __webpack_require__.r(ns);
62 /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
63 /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
67 /******/ // getDefaultExport function for compatibility with non-harmony modules
68 /******/ __webpack_require__.n = function(module) {
69 /******/ var getter = module && module.__esModule ?
70 /******/ function getDefault() { return module['default']; } :
71 /******/ function getModuleExports() { return module; };
72 /******/ __webpack_require__.d(getter, 'a', getter);
73 /******/ return getter;
76 /******/ // Object.prototype.hasOwnProperty.call
77 /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
79 /******/ // __webpack_public_path__
80 /******/ __webpack_require__.p = "";
83 /******/ // Load entry module and return exports
84 /******/ return __webpack_require__(__webpack_require__.s = 0);
86 /************************************************************************/
89 /***/ (function(module, exports, __webpack_require__) {
93 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
94 if (k2 === undefined) k2 = k;
95 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
96 }) : (function(o, m, k, k2) {
97 if (k2 === undefined) k2 = k;
100 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
101 Object.defineProperty(o, "default", { enumerable: true, value: v });
102 }) : function(o, v) {
105 var __importStar = (this && this.__importStar) || function (mod) {
106 if (mod && mod.__esModule) return mod;
108 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
109 __setModuleDefault(result, mod);
112 Object.defineProperty(exports, "__esModule", { value: true });
113 exports.activate = void 0;
114 const coc_nvim_1 = __webpack_require__(1);
115 const path_1 = __webpack_require__(2);
116 const cmds = __importStar(__webpack_require__(3));
117 const ctx_1 = __webpack_require__(33);
118 const file_status_1 = __webpack_require__(36);
119 const install = __importStar(__webpack_require__(37));
120 async function activate(context) {
122 const ctx = new ctx_1.Ctx(context);
123 if (!ctx.config.enabled) {
126 for (const service of coc_nvim_1.services.getServiceStats()) {
127 if (service.id.includes('clangd')) {
128 coc_nvim_1.workspace.showMessage(`Looks like you've configured clangd in coc-settings.json, you should remove it to use coc-clangd`, 'warning');
132 const clangdPath = await install.activate(context);
137 await ctx.startServer(clangdPath);
142 const fileStatus = new file_status_1.FileStatus();
143 const fileWatcher = coc_nvim_1.workspace.createFileSystemWatcher('**/{compile_commands.json,compile_flags.txt,.clang-tidy}');
144 fileWatcher.onDidChange((e) => reload(e.fsPath, ctx, context));
145 fileWatcher.onDidCreate((e) => reload(e.fsPath, ctx, context));
146 context.subscriptions.push(fileWatcher, fileStatus, coc_nvim_1.commands.registerCommand('clangd.switchSourceHeader', cmds.switchSourceHeader(ctx)), coc_nvim_1.commands.registerCommand('clangd.symbolInfo', cmds.symbolInfo(ctx)), ctx.client.onDidChangeState((e) => {
148 if (e.newState === coc_nvim_1.State.Running) {
149 (_a = ctx.client) === null || _a === void 0 ? void 0 : _a.onNotification('textDocument/clangd.fileStatus', (status) => {
150 status.onFileUpdated(status);
153 else if (e.newState === coc_nvim_1.State.Stopped) {
156 }), coc_nvim_1.workspace.onDidOpenTextDocument(() => {
157 fileStatus.updateStatus();
159 (_a = ctx.client) === null || _a === void 0 ? void 0 : _a.onNotification('textDocument/clangd.fileStatus', (status) => {
160 fileStatus.onFileUpdated(status);
163 exports.activate = activate;
164 async function reload(url, ctx, context) {
165 const notification = ctx.config.showDBChangedNotification;
167 const msg = `${path_1.basename(url)} has changed, clangd is reloading...`;
168 coc_nvim_1.workspace.showMessage(msg);
170 for (const sub of ctx.subscriptions) {
178 await activate(context);
180 coc_nvim_1.workspace.showMessage(`clangd has reloaded`);
186 /***/ (function(module, exports) {
188 module.exports = require("coc.nvim");
192 /***/ (function(module, exports) {
194 module.exports = require("path");
198 /***/ (function(module, exports, __webpack_require__) {
202 Object.defineProperty(exports, "__esModule", { value: true });
203 exports.symbolInfo = exports.switchSourceHeader = void 0;
204 const coc_nvim_1 = __webpack_require__(1);
205 const vscode_languageserver_protocol_1 = __webpack_require__(4);
206 var SwitchSourceHeaderRequest;
207 (function (SwitchSourceHeaderRequest) {
208 SwitchSourceHeaderRequest.type = new vscode_languageserver_protocol_1.RequestType('textDocument/switchSourceHeader');
209 })(SwitchSourceHeaderRequest || (SwitchSourceHeaderRequest = {}));
210 var SymbolInfoRequest;
211 (function (SymbolInfoRequest) {
212 SymbolInfoRequest.type = new vscode_languageserver_protocol_1.RequestType('textDocument/symbolInfo');
213 })(SymbolInfoRequest || (SymbolInfoRequest = {}));
214 function switchSourceHeader(ctx) {
219 const doc = await coc_nvim_1.workspace.document;
226 const dest = await ctx.client.sendRequest(SwitchSourceHeaderRequest.type.method, params);
228 coc_nvim_1.workspace.showMessage(`Didn't find a corresponding file.`);
231 await coc_nvim_1.workspace.jumpTo(dest);
234 exports.switchSourceHeader = switchSourceHeader;
235 function symbolInfo(ctx) {
240 const doc = await coc_nvim_1.workspace.document;
244 const position = await coc_nvim_1.workspace.getCursorPosition();
246 textDocument: { uri: doc.uri },
249 const details = await ctx.client.sendRequest(SymbolInfoRequest.type.method, params);
250 if (!details.length) {
254 const detail = details[0];
255 coc_nvim_1.workspace.showMessage(`name: ${detail.name}, containerName: ${detail.containerName}, usr: ${detail.usr}`);
258 exports.symbolInfo = symbolInfo;
263 /***/ (function(module, exports, __webpack_require__) {
266 /* --------------------------------------------------------------------------------------------
\r
267 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
268 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
269 * ------------------------------------------------------------------------------------------ */
\r
271 function __export(m) {
\r
272 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
274 Object.defineProperty(exports, "__esModule", { value: true });
\r
275 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
276 exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
\r
277 exports.ResponseError = vscode_jsonrpc_1.ResponseError;
\r
278 exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
\r
279 exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
\r
280 exports.Disposable = vscode_jsonrpc_1.Disposable;
\r
281 exports.Event = vscode_jsonrpc_1.Event;
\r
282 exports.Emitter = vscode_jsonrpc_1.Emitter;
\r
283 exports.Trace = vscode_jsonrpc_1.Trace;
\r
284 exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
\r
285 exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
\r
286 exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
\r
287 exports.RequestType = vscode_jsonrpc_1.RequestType;
\r
288 exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
\r
289 exports.NotificationType = vscode_jsonrpc_1.NotificationType;
\r
290 exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
\r
291 exports.MessageReader = vscode_jsonrpc_1.MessageReader;
\r
292 exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
\r
293 exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
\r
294 exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
\r
295 exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
\r
296 exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
\r
297 exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
\r
298 exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
\r
299 exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
\r
300 exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
\r
301 exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
\r
302 exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
\r
303 exports.ProgressType = vscode_jsonrpc_1.ProgressType;
\r
304 __export(__webpack_require__(18));
\r
305 __export(__webpack_require__(19));
\r
306 const callHierarchy = __webpack_require__(31);
\r
307 const st = __webpack_require__(32);
\r
309 (function (Proposed) {
\r
310 let CallHierarchyPrepareRequest;
\r
311 (function (CallHierarchyPrepareRequest) {
\r
312 CallHierarchyPrepareRequest.method = callHierarchy.CallHierarchyPrepareRequest.method;
\r
313 CallHierarchyPrepareRequest.type = callHierarchy.CallHierarchyPrepareRequest.type;
\r
314 })(CallHierarchyPrepareRequest = Proposed.CallHierarchyPrepareRequest || (Proposed.CallHierarchyPrepareRequest = {}));
\r
315 let CallHierarchyIncomingCallsRequest;
\r
316 (function (CallHierarchyIncomingCallsRequest) {
\r
317 CallHierarchyIncomingCallsRequest.method = callHierarchy.CallHierarchyIncomingCallsRequest.method;
\r
318 CallHierarchyIncomingCallsRequest.type = callHierarchy.CallHierarchyIncomingCallsRequest.type;
\r
319 })(CallHierarchyIncomingCallsRequest = Proposed.CallHierarchyIncomingCallsRequest || (Proposed.CallHierarchyIncomingCallsRequest = {}));
\r
320 let CallHierarchyOutgoingCallsRequest;
\r
321 (function (CallHierarchyOutgoingCallsRequest) {
\r
322 CallHierarchyOutgoingCallsRequest.method = callHierarchy.CallHierarchyOutgoingCallsRequest.method;
\r
323 CallHierarchyOutgoingCallsRequest.type = callHierarchy.CallHierarchyOutgoingCallsRequest.type;
\r
324 })(CallHierarchyOutgoingCallsRequest = Proposed.CallHierarchyOutgoingCallsRequest || (Proposed.CallHierarchyOutgoingCallsRequest = {}));
\r
325 Proposed.SemanticTokenTypes = st.SemanticTokenTypes;
\r
326 Proposed.SemanticTokenModifiers = st.SemanticTokenModifiers;
\r
327 Proposed.SemanticTokens = st.SemanticTokens;
\r
328 let SemanticTokensRequest;
\r
329 (function (SemanticTokensRequest) {
\r
330 SemanticTokensRequest.method = st.SemanticTokensRequest.method;
\r
331 SemanticTokensRequest.type = st.SemanticTokensRequest.type;
\r
332 })(SemanticTokensRequest = Proposed.SemanticTokensRequest || (Proposed.SemanticTokensRequest = {}));
\r
333 let SemanticTokensEditsRequest;
\r
334 (function (SemanticTokensEditsRequest) {
\r
335 SemanticTokensEditsRequest.method = st.SemanticTokensEditsRequest.method;
\r
336 SemanticTokensEditsRequest.type = st.SemanticTokensEditsRequest.type;
\r
337 })(SemanticTokensEditsRequest = Proposed.SemanticTokensEditsRequest || (Proposed.SemanticTokensEditsRequest = {}));
\r
338 let SemanticTokensRangeRequest;
\r
339 (function (SemanticTokensRangeRequest) {
\r
340 SemanticTokensRangeRequest.method = st.SemanticTokensRangeRequest.method;
\r
341 SemanticTokensRangeRequest.type = st.SemanticTokensRangeRequest.type;
\r
342 })(SemanticTokensRangeRequest = Proposed.SemanticTokensRangeRequest || (Proposed.SemanticTokensRangeRequest = {}));
\r
343 })(Proposed = exports.Proposed || (exports.Proposed = {}));
\r
344 function createProtocolConnection(reader, writer, logger, strategy) {
\r
345 return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
\r
347 exports.createProtocolConnection = createProtocolConnection;
\r
352 /***/ (function(module, exports, __webpack_require__) {
355 /* --------------------------------------------------------------------------------------------
\r
356 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
357 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
358 * ------------------------------------------------------------------------------------------ */
\r
359 /// <reference path="../typings/thenable.d.ts" />
\r
361 function __export(m) {
\r
362 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
364 Object.defineProperty(exports, "__esModule", { value: true });
\r
365 const Is = __webpack_require__(6);
\r
366 const messages_1 = __webpack_require__(7);
\r
367 exports.RequestType = messages_1.RequestType;
\r
368 exports.RequestType0 = messages_1.RequestType0;
\r
369 exports.RequestType1 = messages_1.RequestType1;
\r
370 exports.RequestType2 = messages_1.RequestType2;
\r
371 exports.RequestType3 = messages_1.RequestType3;
\r
372 exports.RequestType4 = messages_1.RequestType4;
\r
373 exports.RequestType5 = messages_1.RequestType5;
\r
374 exports.RequestType6 = messages_1.RequestType6;
\r
375 exports.RequestType7 = messages_1.RequestType7;
\r
376 exports.RequestType8 = messages_1.RequestType8;
\r
377 exports.RequestType9 = messages_1.RequestType9;
\r
378 exports.ResponseError = messages_1.ResponseError;
\r
379 exports.ErrorCodes = messages_1.ErrorCodes;
\r
380 exports.NotificationType = messages_1.NotificationType;
\r
381 exports.NotificationType0 = messages_1.NotificationType0;
\r
382 exports.NotificationType1 = messages_1.NotificationType1;
\r
383 exports.NotificationType2 = messages_1.NotificationType2;
\r
384 exports.NotificationType3 = messages_1.NotificationType3;
\r
385 exports.NotificationType4 = messages_1.NotificationType4;
\r
386 exports.NotificationType5 = messages_1.NotificationType5;
\r
387 exports.NotificationType6 = messages_1.NotificationType6;
\r
388 exports.NotificationType7 = messages_1.NotificationType7;
\r
389 exports.NotificationType8 = messages_1.NotificationType8;
\r
390 exports.NotificationType9 = messages_1.NotificationType9;
\r
391 const messageReader_1 = __webpack_require__(8);
\r
392 exports.MessageReader = messageReader_1.MessageReader;
\r
393 exports.StreamMessageReader = messageReader_1.StreamMessageReader;
\r
394 exports.IPCMessageReader = messageReader_1.IPCMessageReader;
\r
395 exports.SocketMessageReader = messageReader_1.SocketMessageReader;
\r
396 const messageWriter_1 = __webpack_require__(10);
\r
397 exports.MessageWriter = messageWriter_1.MessageWriter;
\r
398 exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
\r
399 exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
\r
400 exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
\r
401 const events_1 = __webpack_require__(9);
\r
402 exports.Disposable = events_1.Disposable;
\r
403 exports.Event = events_1.Event;
\r
404 exports.Emitter = events_1.Emitter;
\r
405 const cancellation_1 = __webpack_require__(11);
\r
406 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
\r
407 exports.CancellationToken = cancellation_1.CancellationToken;
\r
408 const linkedMap_1 = __webpack_require__(12);
\r
409 __export(__webpack_require__(13));
\r
410 __export(__webpack_require__(17));
\r
411 var CancelNotification;
\r
412 (function (CancelNotification) {
\r
413 CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
\r
414 })(CancelNotification || (CancelNotification = {}));
\r
415 var ProgressNotification;
\r
416 (function (ProgressNotification) {
\r
417 ProgressNotification.type = new messages_1.NotificationType('$/progress');
\r
418 })(ProgressNotification || (ProgressNotification = {}));
\r
419 class ProgressType {
\r
423 exports.ProgressType = ProgressType;
\r
424 exports.NullLogger = Object.freeze({
\r
431 (function (Trace) {
\r
432 Trace[Trace["Off"] = 0] = "Off";
\r
433 Trace[Trace["Messages"] = 1] = "Messages";
\r
434 Trace[Trace["Verbose"] = 2] = "Verbose";
\r
435 })(Trace = exports.Trace || (exports.Trace = {}));
\r
436 (function (Trace) {
\r
437 function fromString(value) {
\r
438 if (!Is.string(value)) {
\r
441 value = value.toLowerCase();
\r
446 return Trace.Messages;
\r
448 return Trace.Verbose;
\r
453 Trace.fromString = fromString;
\r
454 function toString(value) {
\r
458 case Trace.Messages:
\r
460 case Trace.Verbose:
\r
466 Trace.toString = toString;
\r
467 })(Trace = exports.Trace || (exports.Trace = {}));
\r
469 (function (TraceFormat) {
\r
470 TraceFormat["Text"] = "text";
\r
471 TraceFormat["JSON"] = "json";
\r
472 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
473 (function (TraceFormat) {
\r
474 function fromString(value) {
\r
475 value = value.toLowerCase();
\r
476 if (value === 'json') {
\r
477 return TraceFormat.JSON;
\r
480 return TraceFormat.Text;
\r
483 TraceFormat.fromString = fromString;
\r
484 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
485 var SetTraceNotification;
\r
486 (function (SetTraceNotification) {
\r
487 SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
\r
488 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
\r
489 var LogTraceNotification;
\r
490 (function (LogTraceNotification) {
\r
491 LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
\r
492 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
\r
493 var ConnectionErrors;
\r
494 (function (ConnectionErrors) {
\r
496 * The connection is closed.
\r
498 ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
\r
500 * The connection got disposed.
\r
502 ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
\r
504 * The connection is already in listening mode.
\r
506 ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
\r
507 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
\r
508 class ConnectionError extends Error {
\r
509 constructor(code, message) {
\r
512 Object.setPrototypeOf(this, ConnectionError.prototype);
\r
515 exports.ConnectionError = ConnectionError;
\r
516 var ConnectionStrategy;
\r
517 (function (ConnectionStrategy) {
\r
518 function is(value) {
\r
519 let candidate = value;
\r
520 return candidate && Is.func(candidate.cancelUndispatched);
\r
522 ConnectionStrategy.is = is;
\r
523 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
\r
524 var ConnectionState;
\r
525 (function (ConnectionState) {
\r
526 ConnectionState[ConnectionState["New"] = 1] = "New";
\r
527 ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
\r
528 ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
\r
529 ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
\r
530 })(ConnectionState || (ConnectionState = {}));
\r
531 function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
\r
532 let sequenceNumber = 0;
\r
533 let notificationSquenceNumber = 0;
\r
534 let unknownResponseSquenceNumber = 0;
\r
535 const version = '2.0';
\r
536 let starRequestHandler = undefined;
\r
537 let requestHandlers = Object.create(null);
\r
538 let starNotificationHandler = undefined;
\r
539 let notificationHandlers = Object.create(null);
\r
540 let progressHandlers = new Map();
\r
542 let messageQueue = new linkedMap_1.LinkedMap();
\r
543 let responsePromises = Object.create(null);
\r
544 let requestTokens = Object.create(null);
\r
545 let trace = Trace.Off;
\r
546 let traceFormat = TraceFormat.Text;
\r
548 let state = ConnectionState.New;
\r
549 let errorEmitter = new events_1.Emitter();
\r
550 let closeEmitter = new events_1.Emitter();
\r
551 let unhandledNotificationEmitter = new events_1.Emitter();
\r
552 let unhandledProgressEmitter = new events_1.Emitter();
\r
553 let disposeEmitter = new events_1.Emitter();
\r
554 function createRequestQueueKey(id) {
\r
555 return 'req-' + id.toString();
\r
557 function createResponseQueueKey(id) {
\r
559 return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
\r
562 return 'res-' + id.toString();
\r
565 function createNotificationQueueKey() {
\r
566 return 'not-' + (++notificationSquenceNumber).toString();
\r
568 function addMessageToQueue(queue, message) {
\r
569 if (messages_1.isRequestMessage(message)) {
\r
570 queue.set(createRequestQueueKey(message.id), message);
\r
572 else if (messages_1.isResponseMessage(message)) {
\r
573 queue.set(createResponseQueueKey(message.id), message);
\r
576 queue.set(createNotificationQueueKey(), message);
\r
579 function cancelUndispatched(_message) {
\r
582 function isListening() {
\r
583 return state === ConnectionState.Listening;
\r
585 function isClosed() {
\r
586 return state === ConnectionState.Closed;
\r
588 function isDisposed() {
\r
589 return state === ConnectionState.Disposed;
\r
591 function closeHandler() {
\r
592 if (state === ConnectionState.New || state === ConnectionState.Listening) {
\r
593 state = ConnectionState.Closed;
\r
594 closeEmitter.fire(undefined);
\r
596 // If the connection is disposed don't sent close events.
\r
598 function readErrorHandler(error) {
\r
599 errorEmitter.fire([error, undefined, undefined]);
\r
601 function writeErrorHandler(data) {
\r
602 errorEmitter.fire(data);
\r
604 messageReader.onClose(closeHandler);
\r
605 messageReader.onError(readErrorHandler);
\r
606 messageWriter.onClose(closeHandler);
\r
607 messageWriter.onError(writeErrorHandler);
\r
608 function triggerMessageQueue() {
\r
609 if (timer || messageQueue.size === 0) {
\r
612 timer = setImmediate(() => {
\r
614 processMessageQueue();
\r
617 function processMessageQueue() {
\r
618 if (messageQueue.size === 0) {
\r
621 let message = messageQueue.shift();
\r
623 if (messages_1.isRequestMessage(message)) {
\r
624 handleRequest(message);
\r
626 else if (messages_1.isNotificationMessage(message)) {
\r
627 handleNotification(message);
\r
629 else if (messages_1.isResponseMessage(message)) {
\r
630 handleResponse(message);
\r
633 handleInvalidMessage(message);
\r
637 triggerMessageQueue();
\r
640 let callback = (message) => {
\r
642 // We have received a cancellation message. Check if the message is still in the queue
\r
643 // and cancel it if allowed to do so.
\r
644 if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
\r
645 let key = createRequestQueueKey(message.params.id);
\r
646 let toCancel = messageQueue.get(key);
\r
647 if (messages_1.isRequestMessage(toCancel)) {
\r
648 let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
\r
649 if (response && (response.error !== void 0 || response.result !== void 0)) {
\r
650 messageQueue.delete(key);
\r
651 response.id = toCancel.id;
\r
652 traceSendingResponse(response, message.method, Date.now());
\r
653 messageWriter.write(response);
\r
658 addMessageToQueue(messageQueue, message);
\r
661 triggerMessageQueue();
\r
664 function handleRequest(requestMessage) {
\r
665 if (isDisposed()) {
\r
666 // we return here silently since we fired an event when the
\r
667 // connection got disposed.
\r
670 function reply(resultOrError, method, startTime) {
\r
673 id: requestMessage.id
\r
675 if (resultOrError instanceof messages_1.ResponseError) {
\r
676 message.error = resultOrError.toJson();
\r
679 message.result = resultOrError === void 0 ? null : resultOrError;
\r
681 traceSendingResponse(message, method, startTime);
\r
682 messageWriter.write(message);
\r
684 function replyError(error, method, startTime) {
\r
687 id: requestMessage.id,
\r
688 error: error.toJson()
\r
690 traceSendingResponse(message, method, startTime);
\r
691 messageWriter.write(message);
\r
693 function replySuccess(result, method, startTime) {
\r
694 // The JSON RPC defines that a response must either have a result or an error
\r
695 // So we can't treat undefined as a valid response result.
\r
696 if (result === void 0) {
\r
701 id: requestMessage.id,
\r
704 traceSendingResponse(message, method, startTime);
\r
705 messageWriter.write(message);
\r
707 traceReceivedRequest(requestMessage);
\r
708 let element = requestHandlers[requestMessage.method];
\r
710 let requestHandler;
\r
712 type = element.type;
\r
713 requestHandler = element.handler;
\r
715 let startTime = Date.now();
\r
716 if (requestHandler || starRequestHandler) {
\r
717 let cancellationSource = new cancellation_1.CancellationTokenSource();
\r
718 let tokenKey = String(requestMessage.id);
\r
719 requestTokens[tokenKey] = cancellationSource;
\r
722 if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
723 handlerResult = requestHandler
\r
724 ? requestHandler(cancellationSource.token)
\r
725 : starRequestHandler(requestMessage.method, cancellationSource.token);
\r
727 else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
728 handlerResult = requestHandler
\r
729 ? requestHandler(...requestMessage.params, cancellationSource.token)
\r
730 : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
\r
733 handlerResult = requestHandler
\r
734 ? requestHandler(requestMessage.params, cancellationSource.token)
\r
735 : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
\r
737 let promise = handlerResult;
\r
738 if (!handlerResult) {
\r
739 delete requestTokens[tokenKey];
\r
740 replySuccess(handlerResult, requestMessage.method, startTime);
\r
742 else if (promise.then) {
\r
743 promise.then((resultOrError) => {
\r
744 delete requestTokens[tokenKey];
\r
745 reply(resultOrError, requestMessage.method, startTime);
\r
747 delete requestTokens[tokenKey];
\r
748 if (error instanceof messages_1.ResponseError) {
\r
749 replyError(error, requestMessage.method, startTime);
\r
751 else if (error && Is.string(error.message)) {
\r
752 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
755 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
760 delete requestTokens[tokenKey];
\r
761 reply(handlerResult, requestMessage.method, startTime);
\r
765 delete requestTokens[tokenKey];
\r
766 if (error instanceof messages_1.ResponseError) {
\r
767 reply(error, requestMessage.method, startTime);
\r
769 else if (error && Is.string(error.message)) {
\r
770 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
773 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
778 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
\r
781 function handleResponse(responseMessage) {
\r
782 if (isDisposed()) {
\r
783 // See handle request.
\r
786 if (responseMessage.id === null) {
\r
787 if (responseMessage.error) {
\r
788 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
\r
791 logger.error(`Received response message without id. No further error information provided.`);
\r
795 let key = String(responseMessage.id);
\r
796 let responsePromise = responsePromises[key];
\r
797 traceReceivedResponse(responseMessage, responsePromise);
\r
798 if (responsePromise) {
\r
799 delete responsePromises[key];
\r
801 if (responseMessage.error) {
\r
802 let error = responseMessage.error;
\r
803 responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
\r
805 else if (responseMessage.result !== void 0) {
\r
806 responsePromise.resolve(responseMessage.result);
\r
809 throw new Error('Should never happen.');
\r
813 if (error.message) {
\r
814 logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
\r
817 logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
\r
823 function handleNotification(message) {
\r
824 if (isDisposed()) {
\r
825 // See handle request.
\r
828 let type = undefined;
\r
829 let notificationHandler;
\r
830 if (message.method === CancelNotification.type.method) {
\r
831 notificationHandler = (params) => {
\r
832 let id = params.id;
\r
833 let source = requestTokens[String(id)];
\r
840 let element = notificationHandlers[message.method];
\r
842 notificationHandler = element.handler;
\r
843 type = element.type;
\r
846 if (notificationHandler || starNotificationHandler) {
\r
848 traceReceivedNotification(message);
\r
849 if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
850 notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
\r
852 else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
853 notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
\r
856 notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
\r
860 if (error.message) {
\r
861 logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
\r
864 logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
\r
869 unhandledNotificationEmitter.fire(message);
\r
872 function handleInvalidMessage(message) {
\r
874 logger.error('Received empty message.');
\r
877 logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
\r
878 // Test whether we find an id to reject the promise
\r
879 let responseMessage = message;
\r
880 if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
\r
881 let key = String(responseMessage.id);
\r
882 let responseHandler = responsePromises[key];
\r
883 if (responseHandler) {
\r
884 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
\r
888 function traceSendingRequest(message) {
\r
889 if (trace === Trace.Off || !tracer) {
\r
892 if (traceFormat === TraceFormat.Text) {
\r
893 let data = undefined;
\r
894 if (trace === Trace.Verbose && message.params) {
\r
895 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
897 tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
\r
900 logLSPMessage('send-request', message);
\r
903 function traceSendingNotification(message) {
\r
904 if (trace === Trace.Off || !tracer) {
\r
907 if (traceFormat === TraceFormat.Text) {
\r
908 let data = undefined;
\r
909 if (trace === Trace.Verbose) {
\r
910 if (message.params) {
\r
911 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
914 data = 'No parameters provided.\n\n';
\r
917 tracer.log(`Sending notification '${message.method}'.`, data);
\r
920 logLSPMessage('send-notification', message);
\r
923 function traceSendingResponse(message, method, startTime) {
\r
924 if (trace === Trace.Off || !tracer) {
\r
927 if (traceFormat === TraceFormat.Text) {
\r
928 let data = undefined;
\r
929 if (trace === Trace.Verbose) {
\r
930 if (message.error && message.error.data) {
\r
931 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
934 if (message.result) {
\r
935 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
937 else if (message.error === void 0) {
\r
938 data = 'No result returned.\n\n';
\r
942 tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
\r
945 logLSPMessage('send-response', message);
\r
948 function traceReceivedRequest(message) {
\r
949 if (trace === Trace.Off || !tracer) {
\r
952 if (traceFormat === TraceFormat.Text) {
\r
953 let data = undefined;
\r
954 if (trace === Trace.Verbose && message.params) {
\r
955 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
957 tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
\r
960 logLSPMessage('receive-request', message);
\r
963 function traceReceivedNotification(message) {
\r
964 if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
\r
967 if (traceFormat === TraceFormat.Text) {
\r
968 let data = undefined;
\r
969 if (trace === Trace.Verbose) {
\r
970 if (message.params) {
\r
971 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
974 data = 'No parameters provided.\n\n';
\r
977 tracer.log(`Received notification '${message.method}'.`, data);
\r
980 logLSPMessage('receive-notification', message);
\r
983 function traceReceivedResponse(message, responsePromise) {
\r
984 if (trace === Trace.Off || !tracer) {
\r
987 if (traceFormat === TraceFormat.Text) {
\r
988 let data = undefined;
\r
989 if (trace === Trace.Verbose) {
\r
990 if (message.error && message.error.data) {
\r
991 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
994 if (message.result) {
\r
995 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
997 else if (message.error === void 0) {
\r
998 data = 'No result returned.\n\n';
\r
1002 if (responsePromise) {
\r
1003 let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
\r
1004 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
\r
1007 tracer.log(`Received response ${message.id} without active response promise.`, data);
\r
1011 logLSPMessage('receive-response', message);
\r
1014 function logLSPMessage(type, message) {
\r
1015 if (!tracer || trace === Trace.Off) {
\r
1018 const lspMessage = {
\r
1019 isLSPMessage: true,
\r
1022 timestamp: Date.now()
\r
1024 tracer.log(lspMessage);
\r
1026 function throwIfClosedOrDisposed() {
\r
1028 throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
\r
1030 if (isDisposed()) {
\r
1031 throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
\r
1034 function throwIfListening() {
\r
1035 if (isListening()) {
\r
1036 throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
\r
1039 function throwIfNotListening() {
\r
1040 if (!isListening()) {
\r
1041 throw new Error('Call listen() first.');
\r
1044 function undefinedToNull(param) {
\r
1045 if (param === void 0) {
\r
1052 function computeMessageParams(type, params) {
\r
1054 let numberOfParams = type.numberOfParams;
\r
1055 switch (numberOfParams) {
\r
1060 result = undefinedToNull(params[0]);
\r
1064 for (let i = 0; i < params.length && i < numberOfParams; i++) {
\r
1065 result.push(undefinedToNull(params[i]));
\r
1067 if (params.length < numberOfParams) {
\r
1068 for (let i = params.length; i < numberOfParams; i++) {
\r
1069 result.push(null);
\r
1076 let connection = {
\r
1077 sendNotification: (type, ...params) => {
\r
1078 throwIfClosedOrDisposed();
\r
1080 let messageParams;
\r
1081 if (Is.string(type)) {
\r
1083 switch (params.length) {
\r
1085 messageParams = null;
\r
1088 messageParams = params[0];
\r
1091 messageParams = params;
\r
1096 method = type.method;
\r
1097 messageParams = computeMessageParams(type, params);
\r
1099 let notificationMessage = {
\r
1102 params: messageParams
\r
1104 traceSendingNotification(notificationMessage);
\r
1105 messageWriter.write(notificationMessage);
\r
1107 onNotification: (type, handler) => {
\r
1108 throwIfClosedOrDisposed();
\r
1109 if (Is.func(type)) {
\r
1110 starNotificationHandler = type;
\r
1112 else if (handler) {
\r
1113 if (Is.string(type)) {
\r
1114 notificationHandlers[type] = { type: undefined, handler };
\r
1117 notificationHandlers[type.method] = { type, handler };
\r
1121 onProgress: (_type, token, handler) => {
\r
1122 if (progressHandlers.has(token)) {
\r
1123 throw new Error(`Progress handler for token ${token} already registered`);
\r
1125 progressHandlers.set(token, handler);
\r
1128 progressHandlers.delete(token);
\r
1132 sendProgress: (_type, token, value) => {
\r
1133 connection.sendNotification(ProgressNotification.type, { token, value });
\r
1135 onUnhandledProgress: unhandledProgressEmitter.event,
\r
1136 sendRequest: (type, ...params) => {
\r
1137 throwIfClosedOrDisposed();
\r
1138 throwIfNotListening();
\r
1140 let messageParams;
\r
1141 let token = undefined;
\r
1142 if (Is.string(type)) {
\r
1144 switch (params.length) {
\r
1146 messageParams = null;
\r
1149 // The cancellation token is optional so it can also be undefined.
\r
1150 if (cancellation_1.CancellationToken.is(params[0])) {
\r
1151 messageParams = null;
\r
1152 token = params[0];
\r
1155 messageParams = undefinedToNull(params[0]);
\r
1159 const last = params.length - 1;
\r
1160 if (cancellation_1.CancellationToken.is(params[last])) {
\r
1161 token = params[last];
\r
1162 if (params.length === 2) {
\r
1163 messageParams = undefinedToNull(params[0]);
\r
1166 messageParams = params.slice(0, last).map(value => undefinedToNull(value));
\r
1170 messageParams = params.map(value => undefinedToNull(value));
\r
1176 method = type.method;
\r
1177 messageParams = computeMessageParams(type, params);
\r
1178 let numberOfParams = type.numberOfParams;
\r
1179 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
\r
1181 let id = sequenceNumber++;
\r
1182 let result = new Promise((resolve, reject) => {
\r
1183 let requestMessage = {
\r
1187 params: messageParams
\r
1189 let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
\r
1190 traceSendingRequest(requestMessage);
\r
1192 messageWriter.write(requestMessage);
\r
1195 // Writing the message failed. So we need to reject the promise.
\r
1196 responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
\r
1197 responsePromise = null;
\r
1199 if (responsePromise) {
\r
1200 responsePromises[String(id)] = responsePromise;
\r
1204 token.onCancellationRequested(() => {
\r
1205 connection.sendNotification(CancelNotification.type, { id });
\r
1210 onRequest: (type, handler) => {
\r
1211 throwIfClosedOrDisposed();
\r
1212 if (Is.func(type)) {
\r
1213 starRequestHandler = type;
\r
1215 else if (handler) {
\r
1216 if (Is.string(type)) {
\r
1217 requestHandlers[type] = { type: undefined, handler };
\r
1220 requestHandlers[type.method] = { type, handler };
\r
1224 trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
\r
1225 let _sendNotification = false;
\r
1226 let _traceFormat = TraceFormat.Text;
\r
1227 if (sendNotificationOrTraceOptions !== void 0) {
\r
1228 if (Is.boolean(sendNotificationOrTraceOptions)) {
\r
1229 _sendNotification = sendNotificationOrTraceOptions;
\r
1232 _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
\r
1233 _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
\r
1237 traceFormat = _traceFormat;
\r
1238 if (trace === Trace.Off) {
\r
1239 tracer = undefined;
\r
1244 if (_sendNotification && !isClosed() && !isDisposed()) {
\r
1245 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
\r
1248 onError: errorEmitter.event,
\r
1249 onClose: closeEmitter.event,
\r
1250 onUnhandledNotification: unhandledNotificationEmitter.event,
\r
1251 onDispose: disposeEmitter.event,
\r
1253 if (isDisposed()) {
\r
1256 state = ConnectionState.Disposed;
\r
1257 disposeEmitter.fire(undefined);
\r
1258 let error = new Error('Connection got disposed.');
\r
1259 Object.keys(responsePromises).forEach((key) => {
\r
1260 responsePromises[key].reject(error);
\r
1262 responsePromises = Object.create(null);
\r
1263 requestTokens = Object.create(null);
\r
1264 messageQueue = new linkedMap_1.LinkedMap();
\r
1265 // Test for backwards compatibility
\r
1266 if (Is.func(messageWriter.dispose)) {
\r
1267 messageWriter.dispose();
\r
1269 if (Is.func(messageReader.dispose)) {
\r
1270 messageReader.dispose();
\r
1274 throwIfClosedOrDisposed();
\r
1275 throwIfListening();
\r
1276 state = ConnectionState.Listening;
\r
1277 messageReader.listen(callback);
\r
1280 // eslint-disable-next-line no-console
\r
1281 console.log('inspect');
\r
1284 connection.onNotification(LogTraceNotification.type, (params) => {
\r
1285 if (trace === Trace.Off || !tracer) {
\r
1288 tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
\r
1290 connection.onNotification(ProgressNotification.type, (params) => {
\r
1291 const handler = progressHandlers.get(params.token);
\r
1293 handler(params.value);
\r
1296 unhandledProgressEmitter.fire(params);
\r
1299 return connection;
\r
1301 function isMessageReader(value) {
\r
1302 return value.listen !== void 0 && value.read === void 0;
\r
1304 function isMessageWriter(value) {
\r
1305 return value.write !== void 0 && value.end === void 0;
\r
1307 function createMessageConnection(input, output, logger, strategy) {
\r
1309 logger = exports.NullLogger;
\r
1311 let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
\r
1312 let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
\r
1313 return _createMessageConnection(reader, writer, logger, strategy);
\r
1315 exports.createMessageConnection = createMessageConnection;
\r
1320 /***/ (function(module, exports, __webpack_require__) {
1323 /* --------------------------------------------------------------------------------------------
\r
1324 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1325 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1326 * ------------------------------------------------------------------------------------------ */
\r
1328 Object.defineProperty(exports, "__esModule", { value: true });
\r
1329 function boolean(value) {
\r
1330 return value === true || value === false;
\r
1332 exports.boolean = boolean;
\r
1333 function string(value) {
\r
1334 return typeof value === 'string' || value instanceof String;
\r
1336 exports.string = string;
\r
1337 function number(value) {
\r
1338 return typeof value === 'number' || value instanceof Number;
\r
1340 exports.number = number;
\r
1341 function error(value) {
\r
1342 return value instanceof Error;
\r
1344 exports.error = error;
\r
1345 function func(value) {
\r
1346 return typeof value === 'function';
\r
1348 exports.func = func;
\r
1349 function array(value) {
\r
1350 return Array.isArray(value);
\r
1352 exports.array = array;
\r
1353 function stringArray(value) {
\r
1354 return array(value) && value.every(elem => string(elem));
\r
1356 exports.stringArray = stringArray;
\r
1361 /***/ (function(module, exports, __webpack_require__) {
1364 /* --------------------------------------------------------------------------------------------
\r
1365 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1366 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1367 * ------------------------------------------------------------------------------------------ */
\r
1369 Object.defineProperty(exports, "__esModule", { value: true });
\r
1370 const is = __webpack_require__(6);
\r
1372 * Predefined error codes.
\r
1375 (function (ErrorCodes) {
\r
1376 // Defined by JSON RPC
\r
1377 ErrorCodes.ParseError = -32700;
\r
1378 ErrorCodes.InvalidRequest = -32600;
\r
1379 ErrorCodes.MethodNotFound = -32601;
\r
1380 ErrorCodes.InvalidParams = -32602;
\r
1381 ErrorCodes.InternalError = -32603;
\r
1382 ErrorCodes.serverErrorStart = -32099;
\r
1383 ErrorCodes.serverErrorEnd = -32000;
\r
1384 ErrorCodes.ServerNotInitialized = -32002;
\r
1385 ErrorCodes.UnknownErrorCode = -32001;
\r
1386 // Defined by the protocol.
\r
1387 ErrorCodes.RequestCancelled = -32800;
\r
1388 ErrorCodes.ContentModified = -32801;
\r
1389 // Defined by VSCode library.
\r
1390 ErrorCodes.MessageWriteError = 1;
\r
1391 ErrorCodes.MessageReadError = 2;
\r
1392 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
\r
1394 * An error object return in a response in case a request
\r
1397 class ResponseError extends Error {
\r
1398 constructor(code, message, data) {
\r
1400 this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
\r
1402 Object.setPrototypeOf(this, ResponseError.prototype);
\r
1407 message: this.message,
\r
1412 exports.ResponseError = ResponseError;
\r
1414 * An abstract implementation of a MessageType.
\r
1416 class AbstractMessageType {
\r
1417 constructor(_method, _numberOfParams) {
\r
1418 this._method = _method;
\r
1419 this._numberOfParams = _numberOfParams;
\r
1422 return this._method;
\r
1424 get numberOfParams() {
\r
1425 return this._numberOfParams;
\r
1428 exports.AbstractMessageType = AbstractMessageType;
\r
1430 * Classes to type request response pairs
\r
1432 * The type parameter RO will be removed in the next major version
\r
1433 * of the JSON RPC library since it is a LSP concept and doesn't
\r
1434 * belong here. For now it is tagged as default never.
\r
1436 class RequestType0 extends AbstractMessageType {
\r
1437 constructor(method) {
\r
1441 exports.RequestType0 = RequestType0;
\r
1442 class RequestType extends AbstractMessageType {
\r
1443 constructor(method) {
\r
1447 exports.RequestType = RequestType;
\r
1448 class RequestType1 extends AbstractMessageType {
\r
1449 constructor(method) {
\r
1453 exports.RequestType1 = RequestType1;
\r
1454 class RequestType2 extends AbstractMessageType {
\r
1455 constructor(method) {
\r
1459 exports.RequestType2 = RequestType2;
\r
1460 class RequestType3 extends AbstractMessageType {
\r
1461 constructor(method) {
\r
1465 exports.RequestType3 = RequestType3;
\r
1466 class RequestType4 extends AbstractMessageType {
\r
1467 constructor(method) {
\r
1471 exports.RequestType4 = RequestType4;
\r
1472 class RequestType5 extends AbstractMessageType {
\r
1473 constructor(method) {
\r
1477 exports.RequestType5 = RequestType5;
\r
1478 class RequestType6 extends AbstractMessageType {
\r
1479 constructor(method) {
\r
1483 exports.RequestType6 = RequestType6;
\r
1484 class RequestType7 extends AbstractMessageType {
\r
1485 constructor(method) {
\r
1489 exports.RequestType7 = RequestType7;
\r
1490 class RequestType8 extends AbstractMessageType {
\r
1491 constructor(method) {
\r
1495 exports.RequestType8 = RequestType8;
\r
1496 class RequestType9 extends AbstractMessageType {
\r
1497 constructor(method) {
\r
1501 exports.RequestType9 = RequestType9;
\r
1503 * The type parameter RO will be removed in the next major version
\r
1504 * of the JSON RPC library since it is a LSP concept and doesn't
\r
1505 * belong here. For now it is tagged as default never.
\r
1507 class NotificationType extends AbstractMessageType {
\r
1508 constructor(method) {
\r
1510 this._ = undefined;
\r
1513 exports.NotificationType = NotificationType;
\r
1514 class NotificationType0 extends AbstractMessageType {
\r
1515 constructor(method) {
\r
1519 exports.NotificationType0 = NotificationType0;
\r
1520 class NotificationType1 extends AbstractMessageType {
\r
1521 constructor(method) {
\r
1525 exports.NotificationType1 = NotificationType1;
\r
1526 class NotificationType2 extends AbstractMessageType {
\r
1527 constructor(method) {
\r
1531 exports.NotificationType2 = NotificationType2;
\r
1532 class NotificationType3 extends AbstractMessageType {
\r
1533 constructor(method) {
\r
1537 exports.NotificationType3 = NotificationType3;
\r
1538 class NotificationType4 extends AbstractMessageType {
\r
1539 constructor(method) {
\r
1543 exports.NotificationType4 = NotificationType4;
\r
1544 class NotificationType5 extends AbstractMessageType {
\r
1545 constructor(method) {
\r
1549 exports.NotificationType5 = NotificationType5;
\r
1550 class NotificationType6 extends AbstractMessageType {
\r
1551 constructor(method) {
\r
1555 exports.NotificationType6 = NotificationType6;
\r
1556 class NotificationType7 extends AbstractMessageType {
\r
1557 constructor(method) {
\r
1561 exports.NotificationType7 = NotificationType7;
\r
1562 class NotificationType8 extends AbstractMessageType {
\r
1563 constructor(method) {
\r
1567 exports.NotificationType8 = NotificationType8;
\r
1568 class NotificationType9 extends AbstractMessageType {
\r
1569 constructor(method) {
\r
1573 exports.NotificationType9 = NotificationType9;
\r
1575 * Tests if the given message is a request message
\r
1577 function isRequestMessage(message) {
\r
1578 let candidate = message;
\r
1579 return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
\r
1581 exports.isRequestMessage = isRequestMessage;
\r
1583 * Tests if the given message is a notification message
\r
1585 function isNotificationMessage(message) {
\r
1586 let candidate = message;
\r
1587 return candidate && is.string(candidate.method) && message.id === void 0;
\r
1589 exports.isNotificationMessage = isNotificationMessage;
\r
1591 * Tests if the given message is a response message
\r
1593 function isResponseMessage(message) {
\r
1594 let candidate = message;
\r
1595 return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
\r
1597 exports.isResponseMessage = isResponseMessage;
\r
1602 /***/ (function(module, exports, __webpack_require__) {
1605 /* --------------------------------------------------------------------------------------------
\r
1606 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1607 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1608 * ------------------------------------------------------------------------------------------ */
\r
1610 Object.defineProperty(exports, "__esModule", { value: true });
\r
1611 const events_1 = __webpack_require__(9);
\r
1612 const Is = __webpack_require__(6);
\r
1613 let DefaultSize = 8192;
\r
1614 let CR = Buffer.from('\r', 'ascii')[0];
\r
1615 let LF = Buffer.from('\n', 'ascii')[0];
\r
1616 let CRLF = '\r\n';
\r
1617 class MessageBuffer {
\r
1618 constructor(encoding = 'utf8') {
\r
1619 this.encoding = encoding;
\r
1621 this.buffer = Buffer.allocUnsafe(DefaultSize);
\r
1624 var toAppend = chunk;
\r
1625 if (typeof (chunk) === 'string') {
\r
1627 var bufferLen = Buffer.byteLength(str, this.encoding);
\r
1628 toAppend = Buffer.allocUnsafe(bufferLen);
\r
1629 toAppend.write(str, 0, bufferLen, this.encoding);
\r
1631 if (this.buffer.length - this.index >= toAppend.length) {
\r
1632 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
\r
1635 var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
\r
1636 if (this.index === 0) {
\r
1637 this.buffer = Buffer.allocUnsafe(newSize);
\r
1638 toAppend.copy(this.buffer, 0, 0, toAppend.length);
\r
1641 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
\r
1644 this.index += toAppend.length;
\r
1646 tryReadHeaders() {
\r
1647 let result = undefined;
\r
1649 while (current + 3 < this.index && (this.buffer[current] !== CR || this.buffer[current + 1] !== LF || this.buffer[current + 2] !== CR || this.buffer[current + 3] !== LF)) {
\r
1652 // No header / body separator found (e.g CRLFCRLF)
\r
1653 if (current + 3 >= this.index) {
\r
1656 result = Object.create(null);
\r
1657 let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
\r
1658 headers.forEach((header) => {
\r
1659 let index = header.indexOf(':');
\r
1660 if (index === -1) {
\r
1661 throw new Error('Message header must separate key and value using :');
\r
1663 let key = header.substr(0, index);
\r
1664 let value = header.substr(index + 1).trim();
\r
1665 result[key] = value;
\r
1667 let nextStart = current + 4;
\r
1668 this.buffer = this.buffer.slice(nextStart);
\r
1669 this.index = this.index - nextStart;
\r
1672 tryReadContent(length) {
\r
1673 if (this.index < length) {
\r
1676 let result = this.buffer.toString(this.encoding, 0, length);
\r
1677 let nextStart = length;
\r
1678 this.buffer.copy(this.buffer, 0, nextStart);
\r
1679 this.index = this.index - nextStart;
\r
1682 get numberOfBytes() {
\r
1683 return this.index;
\r
1686 var MessageReader;
\r
1687 (function (MessageReader) {
\r
1688 function is(value) {
\r
1689 let candidate = value;
\r
1690 return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
\r
1691 Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
\r
1693 MessageReader.is = is;
\r
1694 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
\r
1695 class AbstractMessageReader {
\r
1697 this.errorEmitter = new events_1.Emitter();
\r
1698 this.closeEmitter = new events_1.Emitter();
\r
1699 this.partialMessageEmitter = new events_1.Emitter();
\r
1702 this.errorEmitter.dispose();
\r
1703 this.closeEmitter.dispose();
\r
1706 return this.errorEmitter.event;
\r
1708 fireError(error) {
\r
1709 this.errorEmitter.fire(this.asError(error));
\r
1712 return this.closeEmitter.event;
\r
1715 this.closeEmitter.fire(undefined);
\r
1717 get onPartialMessage() {
\r
1718 return this.partialMessageEmitter.event;
\r
1720 firePartialMessage(info) {
\r
1721 this.partialMessageEmitter.fire(info);
\r
1724 if (error instanceof Error) {
\r
1728 return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
1732 exports.AbstractMessageReader = AbstractMessageReader;
\r
1733 class StreamMessageReader extends AbstractMessageReader {
\r
1734 constructor(readable, encoding = 'utf8') {
\r
1736 this.readable = readable;
\r
1737 this.buffer = new MessageBuffer(encoding);
\r
1738 this._partialMessageTimeout = 10000;
\r
1740 set partialMessageTimeout(timeout) {
\r
1741 this._partialMessageTimeout = timeout;
\r
1743 get partialMessageTimeout() {
\r
1744 return this._partialMessageTimeout;
\r
1746 listen(callback) {
\r
1747 this.nextMessageLength = -1;
\r
1748 this.messageToken = 0;
\r
1749 this.partialMessageTimer = undefined;
\r
1750 this.callback = callback;
\r
1751 this.readable.on('data', (data) => {
\r
1752 this.onData(data);
\r
1754 this.readable.on('error', (error) => this.fireError(error));
\r
1755 this.readable.on('close', () => this.fireClose());
\r
1758 this.buffer.append(data);
\r
1760 if (this.nextMessageLength === -1) {
\r
1761 let headers = this.buffer.tryReadHeaders();
\r
1765 let contentLength = headers['Content-Length'];
\r
1766 if (!contentLength) {
\r
1767 throw new Error('Header must provide a Content-Length property.');
\r
1769 let length = parseInt(contentLength);
\r
1770 if (isNaN(length)) {
\r
1771 throw new Error('Content-Length value must be a number.');
\r
1773 this.nextMessageLength = length;
\r
1774 // Take the encoding form the header. For compatibility
\r
1775 // treat both utf-8 and utf8 as node utf8
\r
1777 var msg = this.buffer.tryReadContent(this.nextMessageLength);
\r
1778 if (msg === null) {
\r
1779 /** We haven't received the full message yet. */
\r
1780 this.setPartialMessageTimer();
\r
1783 this.clearPartialMessageTimer();
\r
1784 this.nextMessageLength = -1;
\r
1785 this.messageToken++;
\r
1786 var json = JSON.parse(msg);
\r
1787 this.callback(json);
\r
1790 clearPartialMessageTimer() {
\r
1791 if (this.partialMessageTimer) {
\r
1792 clearTimeout(this.partialMessageTimer);
\r
1793 this.partialMessageTimer = undefined;
\r
1796 setPartialMessageTimer() {
\r
1797 this.clearPartialMessageTimer();
\r
1798 if (this._partialMessageTimeout <= 0) {
\r
1801 this.partialMessageTimer = setTimeout((token, timeout) => {
\r
1802 this.partialMessageTimer = undefined;
\r
1803 if (token === this.messageToken) {
\r
1804 this.firePartialMessage({ messageToken: token, waitingTime: timeout });
\r
1805 this.setPartialMessageTimer();
\r
1807 }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
\r
1810 exports.StreamMessageReader = StreamMessageReader;
\r
1811 class IPCMessageReader extends AbstractMessageReader {
\r
1812 constructor(process) {
\r
1814 this.process = process;
\r
1815 let eventEmitter = this.process;
\r
1816 eventEmitter.on('error', (error) => this.fireError(error));
\r
1817 eventEmitter.on('close', () => this.fireClose());
\r
1819 listen(callback) {
\r
1820 this.process.on('message', callback);
\r
1823 exports.IPCMessageReader = IPCMessageReader;
\r
1824 class SocketMessageReader extends StreamMessageReader {
\r
1825 constructor(socket, encoding = 'utf-8') {
\r
1826 super(socket, encoding);
\r
1829 exports.SocketMessageReader = SocketMessageReader;
\r
1834 /***/ (function(module, exports, __webpack_require__) {
1837 /* --------------------------------------------------------------------------------------------
\r
1838 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1839 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1840 * ------------------------------------------------------------------------------------------ */
\r
1842 Object.defineProperty(exports, "__esModule", { value: true });
\r
1844 (function (Disposable) {
\r
1845 function create(func) {
\r
1850 Disposable.create = create;
\r
1851 })(Disposable = exports.Disposable || (exports.Disposable = {}));
\r
1853 (function (Event) {
\r
1854 const _disposable = { dispose() { } };
\r
1855 Event.None = function () { return _disposable; };
\r
1856 })(Event = exports.Event || (exports.Event = {}));
\r
1857 class CallbackList {
\r
1858 add(callback, context = null, bucket) {
\r
1859 if (!this._callbacks) {
\r
1860 this._callbacks = [];
\r
1861 this._contexts = [];
\r
1863 this._callbacks.push(callback);
\r
1864 this._contexts.push(context);
\r
1865 if (Array.isArray(bucket)) {
\r
1866 bucket.push({ dispose: () => this.remove(callback, context) });
\r
1869 remove(callback, context = null) {
\r
1870 if (!this._callbacks) {
\r
1873 var foundCallbackWithDifferentContext = false;
\r
1874 for (var i = 0, len = this._callbacks.length; i < len; i++) {
\r
1875 if (this._callbacks[i] === callback) {
\r
1876 if (this._contexts[i] === context) {
\r
1877 // callback & context match => remove it
\r
1878 this._callbacks.splice(i, 1);
\r
1879 this._contexts.splice(i, 1);
\r
1883 foundCallbackWithDifferentContext = true;
\r
1887 if (foundCallbackWithDifferentContext) {
\r
1888 throw new Error('When adding a listener with a context, you should remove it with the same context');
\r
1892 if (!this._callbacks) {
\r
1895 var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
\r
1896 for (var i = 0, len = callbacks.length; i < len; i++) {
\r
1898 ret.push(callbacks[i].apply(contexts[i], args));
\r
1901 // eslint-disable-next-line no-console
\r
1908 return !this._callbacks || this._callbacks.length === 0;
\r
1911 this._callbacks = undefined;
\r
1912 this._contexts = undefined;
\r
1916 constructor(_options) {
\r
1917 this._options = _options;
\r
1920 * For the public to allow to subscribe
\r
1921 * to events from this Emitter
\r
1924 if (!this._event) {
\r
1925 this._event = (listener, thisArgs, disposables) => {
\r
1926 if (!this._callbacks) {
\r
1927 this._callbacks = new CallbackList();
\r
1929 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
\r
1930 this._options.onFirstListenerAdd(this);
\r
1932 this._callbacks.add(listener, thisArgs);
\r
1936 this._callbacks.remove(listener, thisArgs);
\r
1937 result.dispose = Emitter._noop;
\r
1938 if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
\r
1939 this._options.onLastListenerRemove(this);
\r
1943 if (Array.isArray(disposables)) {
\r
1944 disposables.push(result);
\r
1949 return this._event;
\r
1952 * To be kept private to fire an event to
\r
1956 if (this._callbacks) {
\r
1957 this._callbacks.invoke.call(this._callbacks, event);
\r
1961 if (this._callbacks) {
\r
1962 this._callbacks.dispose();
\r
1963 this._callbacks = undefined;
\r
1967 exports.Emitter = Emitter;
\r
1968 Emitter._noop = function () { };
\r
1973 /***/ (function(module, exports, __webpack_require__) {
1976 /* --------------------------------------------------------------------------------------------
\r
1977 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1978 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1979 * ------------------------------------------------------------------------------------------ */
\r
1981 Object.defineProperty(exports, "__esModule", { value: true });
\r
1982 const events_1 = __webpack_require__(9);
\r
1983 const Is = __webpack_require__(6);
\r
1984 let ContentLength = 'Content-Length: ';
\r
1985 let CRLF = '\r\n';
\r
1986 var MessageWriter;
\r
1987 (function (MessageWriter) {
\r
1988 function is(value) {
\r
1989 let candidate = value;
\r
1990 return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
\r
1991 Is.func(candidate.onError) && Is.func(candidate.write);
\r
1993 MessageWriter.is = is;
\r
1994 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
\r
1995 class AbstractMessageWriter {
\r
1997 this.errorEmitter = new events_1.Emitter();
\r
1998 this.closeEmitter = new events_1.Emitter();
\r
2001 this.errorEmitter.dispose();
\r
2002 this.closeEmitter.dispose();
\r
2005 return this.errorEmitter.event;
\r
2007 fireError(error, message, count) {
\r
2008 this.errorEmitter.fire([this.asError(error), message, count]);
\r
2011 return this.closeEmitter.event;
\r
2014 this.closeEmitter.fire(undefined);
\r
2017 if (error instanceof Error) {
\r
2021 return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
2025 exports.AbstractMessageWriter = AbstractMessageWriter;
\r
2026 class StreamMessageWriter extends AbstractMessageWriter {
\r
2027 constructor(writable, encoding = 'utf8') {
\r
2029 this.writable = writable;
\r
2030 this.encoding = encoding;
\r
2031 this.errorCount = 0;
\r
2032 this.writable.on('error', (error) => this.fireError(error));
\r
2033 this.writable.on('close', () => this.fireClose());
\r
2036 let json = JSON.stringify(msg);
\r
2037 let contentLength = Buffer.byteLength(json, this.encoding);
\r
2039 ContentLength, contentLength.toString(), CRLF,
\r
2043 // Header must be written in ASCII encoding
\r
2044 this.writable.write(headers.join(''), 'ascii');
\r
2045 // Now write the content. This can be written in any encoding
\r
2046 this.writable.write(json, this.encoding);
\r
2047 this.errorCount = 0;
\r
2050 this.errorCount++;
\r
2051 this.fireError(error, msg, this.errorCount);
\r
2055 exports.StreamMessageWriter = StreamMessageWriter;
\r
2056 class IPCMessageWriter extends AbstractMessageWriter {
\r
2057 constructor(process) {
\r
2059 this.process = process;
\r
2060 this.errorCount = 0;
\r
2062 this.sending = false;
\r
2063 let eventEmitter = this.process;
\r
2064 eventEmitter.on('error', (error) => this.fireError(error));
\r
2065 eventEmitter.on('close', () => this.fireClose);
\r
2068 if (!this.sending && this.queue.length === 0) {
\r
2069 // See https://github.com/nodejs/node/issues/7657
\r
2070 this.doWriteMessage(msg);
\r
2073 this.queue.push(msg);
\r
2076 doWriteMessage(msg) {
\r
2078 if (this.process.send) {
\r
2079 this.sending = true;
\r
2080 this.process.send(msg, undefined, undefined, (error) => {
\r
2081 this.sending = false;
\r
2083 this.errorCount++;
\r
2084 this.fireError(error, msg, this.errorCount);
\r
2087 this.errorCount = 0;
\r
2089 if (this.queue.length > 0) {
\r
2090 this.doWriteMessage(this.queue.shift());
\r
2096 this.errorCount++;
\r
2097 this.fireError(error, msg, this.errorCount);
\r
2101 exports.IPCMessageWriter = IPCMessageWriter;
\r
2102 class SocketMessageWriter extends AbstractMessageWriter {
\r
2103 constructor(socket, encoding = 'utf8') {
\r
2105 this.socket = socket;
\r
2107 this.sending = false;
\r
2108 this.encoding = encoding;
\r
2109 this.errorCount = 0;
\r
2110 this.socket.on('error', (error) => this.fireError(error));
\r
2111 this.socket.on('close', () => this.fireClose());
\r
2115 this.socket.destroy();
\r
2118 if (!this.sending && this.queue.length === 0) {
\r
2119 // See https://github.com/nodejs/node/issues/7657
\r
2120 this.doWriteMessage(msg);
\r
2123 this.queue.push(msg);
\r
2126 doWriteMessage(msg) {
\r
2127 let json = JSON.stringify(msg);
\r
2128 let contentLength = Buffer.byteLength(json, this.encoding);
\r
2130 ContentLength, contentLength.toString(), CRLF,
\r
2134 // Header must be written in ASCII encoding
\r
2135 this.sending = true;
\r
2136 this.socket.write(headers.join(''), 'ascii', (error) => {
\r
2138 this.handleError(error, msg);
\r
2141 // Now write the content. This can be written in any encoding
\r
2142 this.socket.write(json, this.encoding, (error) => {
\r
2143 this.sending = false;
\r
2145 this.handleError(error, msg);
\r
2148 this.errorCount = 0;
\r
2150 if (this.queue.length > 0) {
\r
2151 this.doWriteMessage(this.queue.shift());
\r
2156 this.handleError(error, msg);
\r
2161 this.handleError(error, msg);
\r
2164 handleError(error, msg) {
\r
2165 this.errorCount++;
\r
2166 this.fireError(error, msg, this.errorCount);
\r
2169 exports.SocketMessageWriter = SocketMessageWriter;
\r
2174 /***/ (function(module, exports, __webpack_require__) {
2177 /*---------------------------------------------------------------------------------------------
\r
2178 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2179 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2180 *--------------------------------------------------------------------------------------------*/
\r
2182 Object.defineProperty(exports, "__esModule", { value: true });
\r
2183 const events_1 = __webpack_require__(9);
\r
2184 const Is = __webpack_require__(6);
\r
2185 var CancellationToken;
\r
2186 (function (CancellationToken) {
\r
2187 CancellationToken.None = Object.freeze({
\r
2188 isCancellationRequested: false,
\r
2189 onCancellationRequested: events_1.Event.None
\r
2191 CancellationToken.Cancelled = Object.freeze({
\r
2192 isCancellationRequested: true,
\r
2193 onCancellationRequested: events_1.Event.None
\r
2195 function is(value) {
\r
2196 let candidate = value;
\r
2197 return candidate && (candidate === CancellationToken.None
\r
2198 || candidate === CancellationToken.Cancelled
\r
2199 || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
\r
2201 CancellationToken.is = is;
\r
2202 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
\r
2203 const shortcutEvent = Object.freeze(function (callback, context) {
\r
2204 let handle = setTimeout(callback.bind(context), 0);
\r
2205 return { dispose() { clearTimeout(handle); } };
\r
2207 class MutableToken {
\r
2209 this._isCancelled = false;
\r
2212 if (!this._isCancelled) {
\r
2213 this._isCancelled = true;
\r
2214 if (this._emitter) {
\r
2215 this._emitter.fire(undefined);
\r
2220 get isCancellationRequested() {
\r
2221 return this._isCancelled;
\r
2223 get onCancellationRequested() {
\r
2224 if (this._isCancelled) {
\r
2225 return shortcutEvent;
\r
2227 if (!this._emitter) {
\r
2228 this._emitter = new events_1.Emitter();
\r
2230 return this._emitter.event;
\r
2233 if (this._emitter) {
\r
2234 this._emitter.dispose();
\r
2235 this._emitter = undefined;
\r
2239 class CancellationTokenSource {
\r
2241 if (!this._token) {
\r
2242 // be lazy and create the token only when
\r
2243 // actually needed
\r
2244 this._token = new MutableToken();
\r
2246 return this._token;
\r
2249 if (!this._token) {
\r
2250 // save an object by returning the default
\r
2251 // cancelled token when cancellation happens
\r
2252 // before someone asks for the token
\r
2253 this._token = CancellationToken.Cancelled;
\r
2256 this._token.cancel();
\r
2260 if (!this._token) {
\r
2261 // ensure to initialize with an empty token if we had none
\r
2262 this._token = CancellationToken.None;
\r
2264 else if (this._token instanceof MutableToken) {
\r
2265 // actually dispose
\r
2266 this._token.dispose();
\r
2270 exports.CancellationTokenSource = CancellationTokenSource;
\r
2275 /***/ (function(module, exports, __webpack_require__) {
2279 /*---------------------------------------------------------------------------------------------
\r
2280 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2281 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2282 *--------------------------------------------------------------------------------------------*/
\r
2283 Object.defineProperty(exports, "__esModule", { value: true });
\r
2285 (function (Touch) {
\r
2289 })(Touch = exports.Touch || (exports.Touch = {}));
\r
2292 this._map = new Map();
\r
2293 this._head = undefined;
\r
2294 this._tail = undefined;
\r
2298 this._map.clear();
\r
2299 this._head = undefined;
\r
2300 this._tail = undefined;
\r
2304 return !this._head && !this._tail;
\r
2307 return this._size;
\r
2310 return this._map.has(key);
\r
2313 const item = this._map.get(key);
\r
2317 return item.value;
\r
2319 set(key, value, touch = Touch.None) {
\r
2320 let item = this._map.get(key);
\r
2322 item.value = value;
\r
2323 if (touch !== Touch.None) {
\r
2324 this.touch(item, touch);
\r
2328 item = { key, value, next: undefined, previous: undefined };
\r
2331 this.addItemLast(item);
\r
2334 this.addItemFirst(item);
\r
2337 this.addItemLast(item);
\r
2340 this.addItemLast(item);
\r
2343 this._map.set(key, item);
\r
2348 const item = this._map.get(key);
\r
2352 this._map.delete(key);
\r
2353 this.removeItem(item);
\r
2358 if (!this._head && !this._tail) {
\r
2361 if (!this._head || !this._tail) {
\r
2362 throw new Error('Invalid list');
\r
2364 const item = this._head;
\r
2365 this._map.delete(item.key);
\r
2366 this.removeItem(item);
\r
2368 return item.value;
\r
2370 forEach(callbackfn, thisArg) {
\r
2371 let current = this._head;
\r
2374 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2377 callbackfn(current.value, current.key, this);
\r
2379 current = current.next;
\r
2382 forEachReverse(callbackfn, thisArg) {
\r
2383 let current = this._tail;
\r
2386 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2389 callbackfn(current.value, current.key, this);
\r
2391 current = current.previous;
\r
2396 let current = this._head;
\r
2398 result.push(current.value);
\r
2399 current = current.next;
\r
2405 let current = this._head;
\r
2407 result.push(current.key);
\r
2408 current = current.next;
\r
2412 /* JSON RPC run on es5 which has no Symbol.iterator
\r
2413 public keys(): IterableIterator<K> {
\r
2414 let current = this._head;
\r
2415 let iterator: IterableIterator<K> = {
\r
2416 [Symbol.iterator]() {
\r
2419 next():IteratorResult<K> {
\r
2421 let result = { value: current.key, done: false };
\r
2422 current = current.next;
\r
2425 return { value: undefined, done: true };
\r
2432 public values(): IterableIterator<V> {
\r
2433 let current = this._head;
\r
2434 let iterator: IterableIterator<V> = {
\r
2435 [Symbol.iterator]() {
\r
2438 next():IteratorResult<V> {
\r
2440 let result = { value: current.value, done: false };
\r
2441 current = current.next;
\r
2444 return { value: undefined, done: true };
\r
2451 addItemFirst(item) {
\r
2452 // First time Insert
\r
2453 if (!this._head && !this._tail) {
\r
2454 this._tail = item;
\r
2456 else if (!this._head) {
\r
2457 throw new Error('Invalid list');
\r
2460 item.next = this._head;
\r
2461 this._head.previous = item;
\r
2463 this._head = item;
\r
2465 addItemLast(item) {
\r
2466 // First time Insert
\r
2467 if (!this._head && !this._tail) {
\r
2468 this._head = item;
\r
2470 else if (!this._tail) {
\r
2471 throw new Error('Invalid list');
\r
2474 item.previous = this._tail;
\r
2475 this._tail.next = item;
\r
2477 this._tail = item;
\r
2479 removeItem(item) {
\r
2480 if (item === this._head && item === this._tail) {
\r
2481 this._head = undefined;
\r
2482 this._tail = undefined;
\r
2484 else if (item === this._head) {
\r
2485 this._head = item.next;
\r
2487 else if (item === this._tail) {
\r
2488 this._tail = item.previous;
\r
2491 const next = item.next;
\r
2492 const previous = item.previous;
\r
2493 if (!next || !previous) {
\r
2494 throw new Error('Invalid list');
\r
2496 next.previous = previous;
\r
2497 previous.next = next;
\r
2500 touch(item, touch) {
\r
2501 if (!this._head || !this._tail) {
\r
2502 throw new Error('Invalid list');
\r
2504 if ((touch !== Touch.First && touch !== Touch.Last)) {
\r
2507 if (touch === Touch.First) {
\r
2508 if (item === this._head) {
\r
2511 const next = item.next;
\r
2512 const previous = item.previous;
\r
2513 // Unlink the item
\r
2514 if (item === this._tail) {
\r
2515 // previous must be defined since item was not head but is tail
\r
2516 // So there are more than on item in the map
\r
2517 previous.next = undefined;
\r
2518 this._tail = previous;
\r
2521 // Both next and previous are not undefined since item was neither head nor tail.
\r
2522 next.previous = previous;
\r
2523 previous.next = next;
\r
2525 // Insert the node at head
\r
2526 item.previous = undefined;
\r
2527 item.next = this._head;
\r
2528 this._head.previous = item;
\r
2529 this._head = item;
\r
2531 else if (touch === Touch.Last) {
\r
2532 if (item === this._tail) {
\r
2535 const next = item.next;
\r
2536 const previous = item.previous;
\r
2537 // Unlink the item.
\r
2538 if (item === this._head) {
\r
2539 // next must be defined since item was not tail but is head
\r
2540 // So there are more than on item in the map
\r
2541 next.previous = undefined;
\r
2542 this._head = next;
\r
2545 // Both next and previous are not undefined since item was neither head nor tail.
\r
2546 next.previous = previous;
\r
2547 previous.next = next;
\r
2549 item.next = undefined;
\r
2550 item.previous = this._tail;
\r
2551 this._tail.next = item;
\r
2552 this._tail = item;
\r
2556 exports.LinkedMap = LinkedMap;
\r
2561 /***/ (function(module, exports, __webpack_require__) {
2564 /* --------------------------------------------------------------------------------------------
\r
2565 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2566 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2567 * ------------------------------------------------------------------------------------------ */
\r
2569 Object.defineProperty(exports, "__esModule", { value: true });
\r
2570 const path_1 = __webpack_require__(2);
\r
2571 const os_1 = __webpack_require__(14);
\r
2572 const crypto_1 = __webpack_require__(15);
\r
2573 const net_1 = __webpack_require__(16);
\r
2574 const messageReader_1 = __webpack_require__(8);
\r
2575 const messageWriter_1 = __webpack_require__(10);
\r
2576 function generateRandomPipeName() {
\r
2577 const randomSuffix = crypto_1.randomBytes(21).toString('hex');
\r
2578 if (process.platform === 'win32') {
\r
2579 return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
\r
2582 // Mac/Unix: use socket file
\r
2583 return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
\r
2586 exports.generateRandomPipeName = generateRandomPipeName;
\r
2587 function createClientPipeTransport(pipeName, encoding = 'utf-8') {
\r
2588 let connectResolve;
\r
2589 let connected = new Promise((resolve, _reject) => {
\r
2590 connectResolve = resolve;
\r
2592 return new Promise((resolve, reject) => {
\r
2593 let server = net_1.createServer((socket) => {
\r
2596 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2597 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2600 server.on('error', reject);
\r
2601 server.listen(pipeName, () => {
\r
2602 server.removeListener('error', reject);
\r
2604 onConnected: () => { return connected; }
\r
2609 exports.createClientPipeTransport = createClientPipeTransport;
\r
2610 function createServerPipeTransport(pipeName, encoding = 'utf-8') {
\r
2611 const socket = net_1.createConnection(pipeName);
\r
2613 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2614 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2617 exports.createServerPipeTransport = createServerPipeTransport;
\r
2622 /***/ (function(module, exports) {
2624 module.exports = require("os");
2628 /***/ (function(module, exports) {
2630 module.exports = require("crypto");
2634 /***/ (function(module, exports) {
2636 module.exports = require("net");
2640 /***/ (function(module, exports, __webpack_require__) {
2643 /* --------------------------------------------------------------------------------------------
\r
2644 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2645 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2646 * ------------------------------------------------------------------------------------------ */
\r
2648 Object.defineProperty(exports, "__esModule", { value: true });
\r
2649 const net_1 = __webpack_require__(16);
\r
2650 const messageReader_1 = __webpack_require__(8);
\r
2651 const messageWriter_1 = __webpack_require__(10);
\r
2652 function createClientSocketTransport(port, encoding = 'utf-8') {
\r
2653 let connectResolve;
\r
2654 let connected = new Promise((resolve, _reject) => {
\r
2655 connectResolve = resolve;
\r
2657 return new Promise((resolve, reject) => {
\r
2658 let server = net_1.createServer((socket) => {
\r
2661 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2662 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2665 server.on('error', reject);
\r
2666 server.listen(port, '127.0.0.1', () => {
\r
2667 server.removeListener('error', reject);
\r
2669 onConnected: () => { return connected; }
\r
2674 exports.createClientSocketTransport = createClientSocketTransport;
\r
2675 function createServerSocketTransport(port, encoding = 'utf-8') {
\r
2676 const socket = net_1.createConnection(port, '127.0.0.1');
\r
2678 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2679 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2682 exports.createServerSocketTransport = createServerSocketTransport;
\r
2687 /***/ (function(module, __webpack_exports__, __webpack_require__) {
2690 __webpack_require__.r(__webpack_exports__);
2691 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
2692 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
2693 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
2694 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
2695 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
2696 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
2697 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
2698 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
2699 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
2700 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
2701 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
2702 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
2703 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
2704 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
2705 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
2706 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
2707 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
2708 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
2709 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
2710 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
2711 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
2712 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
2713 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
2714 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
2715 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
2716 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
2717 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
2718 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
2719 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemTag", function() { return CompletionItemTag; });
2720 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
2721 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
2722 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
2723 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
2724 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
2725 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
2726 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
2727 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
2728 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
2729 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolTag", function() { return SymbolTag; });
2730 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
2731 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
2732 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
2733 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
2734 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
2735 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
2736 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
2737 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
2738 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
2739 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
2740 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
2741 /* --------------------------------------------------------------------------------------------
\r
2742 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2743 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2744 * ------------------------------------------------------------------------------------------ */
\r
2747 * The Position namespace provides helper functions to work with
\r
2748 * [Position](#Position) literals.
\r
2751 (function (Position) {
\r
2753 * Creates a new Position literal from the given line and character.
\r
2754 * @param line The position's line.
\r
2755 * @param character The position's character.
\r
2757 function create(line, character) {
\r
2758 return { line: line, character: character };
\r
2760 Position.create = create;
\r
2762 * Checks whether the given liternal conforms to the [Position](#Position) interface.
\r
2764 function is(value) {
\r
2765 var candidate = value;
\r
2766 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
\r
2769 })(Position || (Position = {}));
\r
2771 * The Range namespace provides helper functions to work with
\r
2772 * [Range](#Range) literals.
\r
2775 (function (Range) {
\r
2776 function create(one, two, three, four) {
\r
2777 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
\r
2778 return { start: Position.create(one, two), end: Position.create(three, four) };
\r
2780 else if (Position.is(one) && Position.is(two)) {
\r
2781 return { start: one, end: two };
\r
2784 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
\r
2787 Range.create = create;
\r
2789 * Checks whether the given literal conforms to the [Range](#Range) interface.
\r
2791 function is(value) {
\r
2792 var candidate = value;
\r
2793 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
\r
2796 })(Range || (Range = {}));
\r
2798 * The Location namespace provides helper functions to work with
\r
2799 * [Location](#Location) literals.
\r
2802 (function (Location) {
\r
2804 * Creates a Location literal.
\r
2805 * @param uri The location's uri.
\r
2806 * @param range The location's range.
\r
2808 function create(uri, range) {
\r
2809 return { uri: uri, range: range };
\r
2811 Location.create = create;
\r
2813 * Checks whether the given literal conforms to the [Location](#Location) interface.
\r
2815 function is(value) {
\r
2816 var candidate = value;
\r
2817 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
\r
2820 })(Location || (Location = {}));
\r
2822 * The LocationLink namespace provides helper functions to work with
\r
2823 * [LocationLink](#LocationLink) literals.
\r
2826 (function (LocationLink) {
\r
2828 * Creates a LocationLink literal.
\r
2829 * @param targetUri The definition's uri.
\r
2830 * @param targetRange The full range of the definition.
\r
2831 * @param targetSelectionRange The span of the symbol definition at the target.
\r
2832 * @param originSelectionRange The span of the symbol being defined in the originating source file.
\r
2834 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
\r
2835 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
\r
2837 LocationLink.create = create;
\r
2839 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
\r
2841 function is(value) {
\r
2842 var candidate = value;
\r
2843 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
\r
2844 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
\r
2845 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
\r
2847 LocationLink.is = is;
\r
2848 })(LocationLink || (LocationLink = {}));
\r
2850 * The Color namespace provides helper functions to work with
\r
2851 * [Color](#Color) literals.
\r
2854 (function (Color) {
\r
2856 * Creates a new Color literal.
\r
2858 function create(red, green, blue, alpha) {
\r
2866 Color.create = create;
\r
2868 * Checks whether the given literal conforms to the [Color](#Color) interface.
\r
2870 function is(value) {
\r
2871 var candidate = value;
\r
2872 return Is.number(candidate.red)
\r
2873 && Is.number(candidate.green)
\r
2874 && Is.number(candidate.blue)
\r
2875 && Is.number(candidate.alpha);
\r
2878 })(Color || (Color = {}));
\r
2880 * The ColorInformation namespace provides helper functions to work with
\r
2881 * [ColorInformation](#ColorInformation) literals.
\r
2883 var ColorInformation;
\r
2884 (function (ColorInformation) {
\r
2886 * Creates a new ColorInformation literal.
\r
2888 function create(range, color) {
\r
2894 ColorInformation.create = create;
\r
2896 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2898 function is(value) {
\r
2899 var candidate = value;
\r
2900 return Range.is(candidate.range) && Color.is(candidate.color);
\r
2902 ColorInformation.is = is;
\r
2903 })(ColorInformation || (ColorInformation = {}));
\r
2905 * The Color namespace provides helper functions to work with
\r
2906 * [ColorPresentation](#ColorPresentation) literals.
\r
2908 var ColorPresentation;
\r
2909 (function (ColorPresentation) {
\r
2911 * Creates a new ColorInformation literal.
\r
2913 function create(label, textEdit, additionalTextEdits) {
\r
2916 textEdit: textEdit,
\r
2917 additionalTextEdits: additionalTextEdits,
\r
2920 ColorPresentation.create = create;
\r
2922 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2924 function is(value) {
\r
2925 var candidate = value;
\r
2926 return Is.string(candidate.label)
\r
2927 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
\r
2928 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
\r
2930 ColorPresentation.is = is;
\r
2931 })(ColorPresentation || (ColorPresentation = {}));
\r
2933 * Enum of known range kinds
\r
2935 var FoldingRangeKind;
\r
2936 (function (FoldingRangeKind) {
\r
2938 * Folding range for a comment
\r
2940 FoldingRangeKind["Comment"] = "comment";
\r
2942 * Folding range for a imports or includes
\r
2944 FoldingRangeKind["Imports"] = "imports";
\r
2946 * Folding range for a region (e.g. `#region`)
\r
2948 FoldingRangeKind["Region"] = "region";
\r
2949 })(FoldingRangeKind || (FoldingRangeKind = {}));
\r
2951 * The folding range namespace provides helper functions to work with
\r
2952 * [FoldingRange](#FoldingRange) literals.
\r
2955 (function (FoldingRange) {
\r
2957 * Creates a new FoldingRange literal.
\r
2959 function create(startLine, endLine, startCharacter, endCharacter, kind) {
\r
2961 startLine: startLine,
\r
2964 if (Is.defined(startCharacter)) {
\r
2965 result.startCharacter = startCharacter;
\r
2967 if (Is.defined(endCharacter)) {
\r
2968 result.endCharacter = endCharacter;
\r
2970 if (Is.defined(kind)) {
\r
2971 result.kind = kind;
\r
2975 FoldingRange.create = create;
\r
2977 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
\r
2979 function is(value) {
\r
2980 var candidate = value;
\r
2981 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
\r
2982 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
\r
2983 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
\r
2984 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
\r
2986 FoldingRange.is = is;
\r
2987 })(FoldingRange || (FoldingRange = {}));
\r
2989 * The DiagnosticRelatedInformation namespace provides helper functions to work with
\r
2990 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
\r
2992 var DiagnosticRelatedInformation;
\r
2993 (function (DiagnosticRelatedInformation) {
\r
2995 * Creates a new DiagnosticRelatedInformation literal.
\r
2997 function create(location, message) {
\r
2999 location: location,
\r
3003 DiagnosticRelatedInformation.create = create;
\r
3005 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
\r
3007 function is(value) {
\r
3008 var candidate = value;
\r
3009 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
\r
3011 DiagnosticRelatedInformation.is = is;
\r
3012 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
\r
3014 * The diagnostic's severity.
\r
3016 var DiagnosticSeverity;
\r
3017 (function (DiagnosticSeverity) {
\r
3019 * Reports an error.
\r
3021 DiagnosticSeverity.Error = 1;
\r
3023 * Reports a warning.
\r
3025 DiagnosticSeverity.Warning = 2;
\r
3027 * Reports an information.
\r
3029 DiagnosticSeverity.Information = 3;
\r
3033 DiagnosticSeverity.Hint = 4;
\r
3034 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
\r
3036 * The diagnostic tags.
\r
3040 var DiagnosticTag;
\r
3041 (function (DiagnosticTag) {
\r
3043 * Unused or unnecessary code.
\r
3045 * Clients are allowed to render diagnostics with this tag faded out instead of having
\r
3046 * an error squiggle.
\r
3048 DiagnosticTag.Unnecessary = 1;
\r
3050 * Deprecated or obsolete code.
\r
3052 * Clients are allowed to rendered diagnostics with this tag strike through.
\r
3054 DiagnosticTag.Deprecated = 2;
\r
3055 })(DiagnosticTag || (DiagnosticTag = {}));
\r
3057 * The Diagnostic namespace provides helper functions to work with
\r
3058 * [Diagnostic](#Diagnostic) literals.
\r
3061 (function (Diagnostic) {
\r
3063 * Creates a new Diagnostic literal.
\r
3065 function create(range, message, severity, code, source, relatedInformation) {
\r
3066 var result = { range: range, message: message };
\r
3067 if (Is.defined(severity)) {
\r
3068 result.severity = severity;
\r
3070 if (Is.defined(code)) {
\r
3071 result.code = code;
\r
3073 if (Is.defined(source)) {
\r
3074 result.source = source;
\r
3076 if (Is.defined(relatedInformation)) {
\r
3077 result.relatedInformation = relatedInformation;
\r
3081 Diagnostic.create = create;
\r
3083 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
\r
3085 function is(value) {
\r
3086 var candidate = value;
\r
3087 return Is.defined(candidate)
\r
3088 && Range.is(candidate.range)
\r
3089 && Is.string(candidate.message)
\r
3090 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
\r
3091 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
\r
3092 && (Is.string(candidate.source) || Is.undefined(candidate.source))
\r
3093 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
\r
3095 Diagnostic.is = is;
\r
3096 })(Diagnostic || (Diagnostic = {}));
\r
3098 * The Command namespace provides helper functions to work with
\r
3099 * [Command](#Command) literals.
\r
3102 (function (Command) {
\r
3104 * Creates a new Command literal.
\r
3106 function create(title, command) {
\r
3108 for (var _i = 2; _i < arguments.length; _i++) {
\r
3109 args[_i - 2] = arguments[_i];
\r
3111 var result = { title: title, command: command };
\r
3112 if (Is.defined(args) && args.length > 0) {
\r
3113 result.arguments = args;
\r
3117 Command.create = create;
\r
3119 * Checks whether the given literal conforms to the [Command](#Command) interface.
\r
3121 function is(value) {
\r
3122 var candidate = value;
\r
3123 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
\r
3126 })(Command || (Command = {}));
\r
3128 * The TextEdit namespace provides helper function to create replace,
\r
3129 * insert and delete edits more easily.
\r
3132 (function (TextEdit) {
\r
3134 * Creates a replace text edit.
\r
3135 * @param range The range of text to be replaced.
\r
3136 * @param newText The new text.
\r
3138 function replace(range, newText) {
\r
3139 return { range: range, newText: newText };
\r
3141 TextEdit.replace = replace;
\r
3143 * Creates a insert text edit.
\r
3144 * @param position The position to insert the text at.
\r
3145 * @param newText The text to be inserted.
\r
3147 function insert(position, newText) {
\r
3148 return { range: { start: position, end: position }, newText: newText };
\r
3150 TextEdit.insert = insert;
\r
3152 * Creates a delete text edit.
\r
3153 * @param range The range of text to be deleted.
\r
3155 function del(range) {
\r
3156 return { range: range, newText: '' };
\r
3158 TextEdit.del = del;
\r
3159 function is(value) {
\r
3160 var candidate = value;
\r
3161 return Is.objectLiteral(candidate)
\r
3162 && Is.string(candidate.newText)
\r
3163 && Range.is(candidate.range);
\r
3166 })(TextEdit || (TextEdit = {}));
\r
3168 * The TextDocumentEdit namespace provides helper function to create
\r
3169 * an edit that manipulates a text document.
\r
3171 var TextDocumentEdit;
\r
3172 (function (TextDocumentEdit) {
\r
3174 * Creates a new `TextDocumentEdit`
\r
3176 function create(textDocument, edits) {
\r
3177 return { textDocument: textDocument, edits: edits };
\r
3179 TextDocumentEdit.create = create;
\r
3180 function is(value) {
\r
3181 var candidate = value;
\r
3182 return Is.defined(candidate)
\r
3183 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
\r
3184 && Array.isArray(candidate.edits);
\r
3186 TextDocumentEdit.is = is;
\r
3187 })(TextDocumentEdit || (TextDocumentEdit = {}));
\r
3189 (function (CreateFile) {
\r
3190 function create(uri, options) {
\r
3195 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
3196 result.options = options;
\r
3200 CreateFile.create = create;
\r
3201 function is(value) {
\r
3202 var candidate = value;
\r
3203 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
\r
3204 (candidate.options === void 0 ||
\r
3205 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3207 CreateFile.is = is;
\r
3208 })(CreateFile || (CreateFile = {}));
\r
3210 (function (RenameFile) {
\r
3211 function create(oldUri, newUri, options) {
\r
3217 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
3218 result.options = options;
\r
3222 RenameFile.create = create;
\r
3223 function is(value) {
\r
3224 var candidate = value;
\r
3225 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
\r
3226 (candidate.options === void 0 ||
\r
3227 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3229 RenameFile.is = is;
\r
3230 })(RenameFile || (RenameFile = {}));
\r
3232 (function (DeleteFile) {
\r
3233 function create(uri, options) {
\r
3238 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
\r
3239 result.options = options;
\r
3243 DeleteFile.create = create;
\r
3244 function is(value) {
\r
3245 var candidate = value;
\r
3246 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
\r
3247 (candidate.options === void 0 ||
\r
3248 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
\r
3250 DeleteFile.is = is;
\r
3251 })(DeleteFile || (DeleteFile = {}));
\r
3252 var WorkspaceEdit;
\r
3253 (function (WorkspaceEdit) {
\r
3254 function is(value) {
\r
3255 var candidate = value;
\r
3256 return candidate &&
\r
3257 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
\r
3258 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
\r
3259 if (Is.string(change.kind)) {
\r
3260 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
\r
3263 return TextDocumentEdit.is(change);
\r
3267 WorkspaceEdit.is = is;
\r
3268 })(WorkspaceEdit || (WorkspaceEdit = {}));
\r
3269 var TextEditChangeImpl = /** @class */ (function () {
\r
3270 function TextEditChangeImpl(edits) {
\r
3271 this.edits = edits;
\r
3273 TextEditChangeImpl.prototype.insert = function (position, newText) {
\r
3274 this.edits.push(TextEdit.insert(position, newText));
\r
3276 TextEditChangeImpl.prototype.replace = function (range, newText) {
\r
3277 this.edits.push(TextEdit.replace(range, newText));
\r
3279 TextEditChangeImpl.prototype.delete = function (range) {
\r
3280 this.edits.push(TextEdit.del(range));
\r
3282 TextEditChangeImpl.prototype.add = function (edit) {
\r
3283 this.edits.push(edit);
\r
3285 TextEditChangeImpl.prototype.all = function () {
\r
3286 return this.edits;
\r
3288 TextEditChangeImpl.prototype.clear = function () {
\r
3289 this.edits.splice(0, this.edits.length);
\r
3291 return TextEditChangeImpl;
\r
3294 * A workspace change helps constructing changes to a workspace.
\r
3296 var WorkspaceChange = /** @class */ (function () {
\r
3297 function WorkspaceChange(workspaceEdit) {
\r
3299 this._textEditChanges = Object.create(null);
\r
3300 if (workspaceEdit) {
\r
3301 this._workspaceEdit = workspaceEdit;
\r
3302 if (workspaceEdit.documentChanges) {
\r
3303 workspaceEdit.documentChanges.forEach(function (change) {
\r
3304 if (TextDocumentEdit.is(change)) {
\r
3305 var textEditChange = new TextEditChangeImpl(change.edits);
\r
3306 _this._textEditChanges[change.textDocument.uri] = textEditChange;
\r
3310 else if (workspaceEdit.changes) {
\r
3311 Object.keys(workspaceEdit.changes).forEach(function (key) {
\r
3312 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
\r
3313 _this._textEditChanges[key] = textEditChange;
\r
3318 Object.defineProperty(WorkspaceChange.prototype, "edit", {
\r
3320 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
\r
3321 * use to be returned from a workspace edit operation like rename.
\r
3323 get: function () {
\r
3324 return this._workspaceEdit;
\r
3327 configurable: true
\r
3329 WorkspaceChange.prototype.getTextEditChange = function (key) {
\r
3330 if (VersionedTextDocumentIdentifier.is(key)) {
\r
3331 if (!this._workspaceEdit) {
\r
3332 this._workspaceEdit = {
\r
3333 documentChanges: []
\r
3336 if (!this._workspaceEdit.documentChanges) {
\r
3337 throw new Error('Workspace edit is not configured for document changes.');
\r
3339 var textDocument = key;
\r
3340 var result = this._textEditChanges[textDocument.uri];
\r
3343 var textDocumentEdit = {
\r
3344 textDocument: textDocument,
\r
3347 this._workspaceEdit.documentChanges.push(textDocumentEdit);
\r
3348 result = new TextEditChangeImpl(edits);
\r
3349 this._textEditChanges[textDocument.uri] = result;
\r
3354 if (!this._workspaceEdit) {
\r
3355 this._workspaceEdit = {
\r
3356 changes: Object.create(null)
\r
3359 if (!this._workspaceEdit.changes) {
\r
3360 throw new Error('Workspace edit is not configured for normal text edit changes.');
\r
3362 var result = this._textEditChanges[key];
\r
3365 this._workspaceEdit.changes[key] = edits;
\r
3366 result = new TextEditChangeImpl(edits);
\r
3367 this._textEditChanges[key] = result;
\r
3372 WorkspaceChange.prototype.createFile = function (uri, options) {
\r
3373 this.checkDocumentChanges();
\r
3374 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
\r
3376 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
\r
3377 this.checkDocumentChanges();
\r
3378 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
\r
3380 WorkspaceChange.prototype.deleteFile = function (uri, options) {
\r
3381 this.checkDocumentChanges();
\r
3382 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
\r
3384 WorkspaceChange.prototype.checkDocumentChanges = function () {
\r
3385 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
\r
3386 throw new Error('Workspace edit is not configured for document changes.');
\r
3389 return WorkspaceChange;
\r
3393 * The TextDocumentIdentifier namespace provides helper functions to work with
\r
3394 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
\r
3396 var TextDocumentIdentifier;
\r
3397 (function (TextDocumentIdentifier) {
\r
3399 * Creates a new TextDocumentIdentifier literal.
\r
3400 * @param uri The document's uri.
\r
3402 function create(uri) {
\r
3403 return { uri: uri };
\r
3405 TextDocumentIdentifier.create = create;
\r
3407 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
\r
3409 function is(value) {
\r
3410 var candidate = value;
\r
3411 return Is.defined(candidate) && Is.string(candidate.uri);
\r
3413 TextDocumentIdentifier.is = is;
\r
3414 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
\r
3416 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
\r
3417 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
\r
3419 var VersionedTextDocumentIdentifier;
\r
3420 (function (VersionedTextDocumentIdentifier) {
\r
3422 * Creates a new VersionedTextDocumentIdentifier literal.
\r
3423 * @param uri The document's uri.
\r
3424 * @param uri The document's text.
\r
3426 function create(uri, version) {
\r
3427 return { uri: uri, version: version };
\r
3429 VersionedTextDocumentIdentifier.create = create;
\r
3431 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
\r
3433 function is(value) {
\r
3434 var candidate = value;
\r
3435 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
\r
3437 VersionedTextDocumentIdentifier.is = is;
\r
3438 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
\r
3440 * The TextDocumentItem namespace provides helper functions to work with
\r
3441 * [TextDocumentItem](#TextDocumentItem) literals.
\r
3443 var TextDocumentItem;
\r
3444 (function (TextDocumentItem) {
\r
3446 * Creates a new TextDocumentItem literal.
\r
3447 * @param uri The document's uri.
\r
3448 * @param languageId The document's language identifier.
\r
3449 * @param version The document's version number.
\r
3450 * @param text The document's text.
\r
3452 function create(uri, languageId, version, text) {
\r
3453 return { uri: uri, languageId: languageId, version: version, text: text };
\r
3455 TextDocumentItem.create = create;
\r
3457 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
\r
3459 function is(value) {
\r
3460 var candidate = value;
\r
3461 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
\r
3463 TextDocumentItem.is = is;
\r
3464 })(TextDocumentItem || (TextDocumentItem = {}));
\r
3466 * Describes the content type that a client supports in various
\r
3467 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
\r
3469 * Please note that `MarkupKinds` must not start with a `$`. This kinds
\r
3470 * are reserved for internal usage.
\r
3473 (function (MarkupKind) {
\r
3475 * Plain text is supported as a content format
\r
3477 MarkupKind.PlainText = 'plaintext';
\r
3479 * Markdown is supported as a content format
\r
3481 MarkupKind.Markdown = 'markdown';
\r
3482 })(MarkupKind || (MarkupKind = {}));
\r
3483 (function (MarkupKind) {
\r
3485 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
\r
3487 function is(value) {
\r
3488 var candidate = value;
\r
3489 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
\r
3491 MarkupKind.is = is;
\r
3492 })(MarkupKind || (MarkupKind = {}));
\r
3493 var MarkupContent;
\r
3494 (function (MarkupContent) {
\r
3496 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
\r
3498 function is(value) {
\r
3499 var candidate = value;
\r
3500 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
\r
3502 MarkupContent.is = is;
\r
3503 })(MarkupContent || (MarkupContent = {}));
\r
3505 * The kind of a completion entry.
\r
3507 var CompletionItemKind;
\r
3508 (function (CompletionItemKind) {
\r
3509 CompletionItemKind.Text = 1;
\r
3510 CompletionItemKind.Method = 2;
\r
3511 CompletionItemKind.Function = 3;
\r
3512 CompletionItemKind.Constructor = 4;
\r
3513 CompletionItemKind.Field = 5;
\r
3514 CompletionItemKind.Variable = 6;
\r
3515 CompletionItemKind.Class = 7;
\r
3516 CompletionItemKind.Interface = 8;
\r
3517 CompletionItemKind.Module = 9;
\r
3518 CompletionItemKind.Property = 10;
\r
3519 CompletionItemKind.Unit = 11;
\r
3520 CompletionItemKind.Value = 12;
\r
3521 CompletionItemKind.Enum = 13;
\r
3522 CompletionItemKind.Keyword = 14;
\r
3523 CompletionItemKind.Snippet = 15;
\r
3524 CompletionItemKind.Color = 16;
\r
3525 CompletionItemKind.File = 17;
\r
3526 CompletionItemKind.Reference = 18;
\r
3527 CompletionItemKind.Folder = 19;
\r
3528 CompletionItemKind.EnumMember = 20;
\r
3529 CompletionItemKind.Constant = 21;
\r
3530 CompletionItemKind.Struct = 22;
\r
3531 CompletionItemKind.Event = 23;
\r
3532 CompletionItemKind.Operator = 24;
\r
3533 CompletionItemKind.TypeParameter = 25;
\r
3534 })(CompletionItemKind || (CompletionItemKind = {}));
\r
3536 * Defines whether the insert text in a completion item should be interpreted as
\r
3537 * plain text or a snippet.
\r
3539 var InsertTextFormat;
\r
3540 (function (InsertTextFormat) {
\r
3542 * The primary text to be inserted is treated as a plain string.
\r
3544 InsertTextFormat.PlainText = 1;
\r
3546 * The primary text to be inserted is treated as a snippet.
\r
3548 * A snippet can define tab stops and placeholders with `$1`, `$2`
\r
3549 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
\r
3550 * the end of the snippet. Placeholders with equal identifiers are linked,
\r
3551 * that is typing in one will update others too.
\r
3553 * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
\r
3555 InsertTextFormat.Snippet = 2;
\r
3556 })(InsertTextFormat || (InsertTextFormat = {}));
\r
3558 * Completion item tags are extra annotations that tweak the rendering of a completion
\r
3563 var CompletionItemTag;
\r
3564 (function (CompletionItemTag) {
\r
3566 * Render a completion as obsolete, usually using a strike-out.
\r
3568 CompletionItemTag.Deprecated = 1;
\r
3569 })(CompletionItemTag || (CompletionItemTag = {}));
\r
3571 * The CompletionItem namespace provides functions to deal with
\r
3572 * completion items.
\r
3574 var CompletionItem;
\r
3575 (function (CompletionItem) {
\r
3577 * Create a completion item and seed it with a label.
\r
3578 * @param label The completion item's label
\r
3580 function create(label) {
\r
3581 return { label: label };
\r
3583 CompletionItem.create = create;
\r
3584 })(CompletionItem || (CompletionItem = {}));
\r
3586 * The CompletionList namespace provides functions to deal with
\r
3587 * completion lists.
\r
3589 var CompletionList;
\r
3590 (function (CompletionList) {
\r
3592 * Creates a new completion list.
\r
3594 * @param items The completion items.
\r
3595 * @param isIncomplete The list is not complete.
\r
3597 function create(items, isIncomplete) {
\r
3598 return { items: items ? items : [], isIncomplete: !!isIncomplete };
\r
3600 CompletionList.create = create;
\r
3601 })(CompletionList || (CompletionList = {}));
\r
3603 (function (MarkedString) {
\r
3605 * Creates a marked string from plain text.
\r
3607 * @param plainText The plain text.
\r
3609 function fromPlainText(plainText) {
\r
3610 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, '\\$&'); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
\r
3612 MarkedString.fromPlainText = fromPlainText;
\r
3614 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
\r
3616 function is(value) {
\r
3617 var candidate = value;
\r
3618 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
\r
3620 MarkedString.is = is;
\r
3621 })(MarkedString || (MarkedString = {}));
\r
3623 (function (Hover) {
\r
3625 * Checks whether the given value conforms to the [Hover](#Hover) interface.
\r
3627 function is(value) {
\r
3628 var candidate = value;
\r
3629 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
\r
3630 MarkedString.is(candidate.contents) ||
\r
3631 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
\r
3634 })(Hover || (Hover = {}));
\r
3636 * The ParameterInformation namespace provides helper functions to work with
\r
3637 * [ParameterInformation](#ParameterInformation) literals.
\r
3639 var ParameterInformation;
\r
3640 (function (ParameterInformation) {
\r
3642 * Creates a new parameter information literal.
\r
3644 * @param label A label string.
\r
3645 * @param documentation A doc string.
\r
3647 function create(label, documentation) {
\r
3648 return documentation ? { label: label, documentation: documentation } : { label: label };
\r
3650 ParameterInformation.create = create;
\r
3651 })(ParameterInformation || (ParameterInformation = {}));
\r
3653 * The SignatureInformation namespace provides helper functions to work with
\r
3654 * [SignatureInformation](#SignatureInformation) literals.
\r
3656 var SignatureInformation;
\r
3657 (function (SignatureInformation) {
\r
3658 function create(label, documentation) {
\r
3659 var parameters = [];
\r
3660 for (var _i = 2; _i < arguments.length; _i++) {
\r
3661 parameters[_i - 2] = arguments[_i];
\r
3663 var result = { label: label };
\r
3664 if (Is.defined(documentation)) {
\r
3665 result.documentation = documentation;
\r
3667 if (Is.defined(parameters)) {
\r
3668 result.parameters = parameters;
\r
3671 result.parameters = [];
\r
3675 SignatureInformation.create = create;
\r
3676 })(SignatureInformation || (SignatureInformation = {}));
\r
3678 * A document highlight kind.
\r
3680 var DocumentHighlightKind;
\r
3681 (function (DocumentHighlightKind) {
\r
3683 * A textual occurrence.
\r
3685 DocumentHighlightKind.Text = 1;
\r
3687 * Read-access of a symbol, like reading a variable.
\r
3689 DocumentHighlightKind.Read = 2;
\r
3691 * Write-access of a symbol, like writing to a variable.
\r
3693 DocumentHighlightKind.Write = 3;
\r
3694 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
\r
3696 * DocumentHighlight namespace to provide helper functions to work with
\r
3697 * [DocumentHighlight](#DocumentHighlight) literals.
\r
3699 var DocumentHighlight;
\r
3700 (function (DocumentHighlight) {
\r
3702 * Create a DocumentHighlight object.
\r
3703 * @param range The range the highlight applies to.
\r
3705 function create(range, kind) {
\r
3706 var result = { range: range };
\r
3707 if (Is.number(kind)) {
\r
3708 result.kind = kind;
\r
3712 DocumentHighlight.create = create;
\r
3713 })(DocumentHighlight || (DocumentHighlight = {}));
\r
3718 (function (SymbolKind) {
\r
3719 SymbolKind.File = 1;
\r
3720 SymbolKind.Module = 2;
\r
3721 SymbolKind.Namespace = 3;
\r
3722 SymbolKind.Package = 4;
\r
3723 SymbolKind.Class = 5;
\r
3724 SymbolKind.Method = 6;
\r
3725 SymbolKind.Property = 7;
\r
3726 SymbolKind.Field = 8;
\r
3727 SymbolKind.Constructor = 9;
\r
3728 SymbolKind.Enum = 10;
\r
3729 SymbolKind.Interface = 11;
\r
3730 SymbolKind.Function = 12;
\r
3731 SymbolKind.Variable = 13;
\r
3732 SymbolKind.Constant = 14;
\r
3733 SymbolKind.String = 15;
\r
3734 SymbolKind.Number = 16;
\r
3735 SymbolKind.Boolean = 17;
\r
3736 SymbolKind.Array = 18;
\r
3737 SymbolKind.Object = 19;
\r
3738 SymbolKind.Key = 20;
\r
3739 SymbolKind.Null = 21;
\r
3740 SymbolKind.EnumMember = 22;
\r
3741 SymbolKind.Struct = 23;
\r
3742 SymbolKind.Event = 24;
\r
3743 SymbolKind.Operator = 25;
\r
3744 SymbolKind.TypeParameter = 26;
\r
3745 })(SymbolKind || (SymbolKind = {}));
\r
3747 * Symbol tags are extra annotations that tweak the rendering of a symbol.
\r
3751 (function (SymbolTag) {
\r
3753 * Render a symbol as obsolete, usually using a strike-out.
\r
3755 SymbolTag.Deprecated = 1;
\r
3756 })(SymbolTag || (SymbolTag = {}));
\r
3757 var SymbolInformation;
\r
3758 (function (SymbolInformation) {
\r
3760 * Creates a new symbol information literal.
\r
3762 * @param name The name of the symbol.
\r
3763 * @param kind The kind of the symbol.
\r
3764 * @param range The range of the location of the symbol.
\r
3765 * @param uri The resource of the location of symbol, defaults to the current document.
\r
3766 * @param containerName The name of the symbol containing the symbol.
\r
3768 function create(name, kind, range, uri, containerName) {
\r
3772 location: { uri: uri, range: range }
\r
3774 if (containerName) {
\r
3775 result.containerName = containerName;
\r
3779 SymbolInformation.create = create;
\r
3780 })(SymbolInformation || (SymbolInformation = {}));
\r
3781 var DocumentSymbol;
\r
3782 (function (DocumentSymbol) {
\r
3784 * Creates a new symbol information literal.
\r
3786 * @param name The name of the symbol.
\r
3787 * @param detail The detail of the symbol.
\r
3788 * @param kind The kind of the symbol.
\r
3789 * @param range The range of the symbol.
\r
3790 * @param selectionRange The selectionRange of the symbol.
\r
3791 * @param children Children of the symbol.
\r
3793 function create(name, detail, kind, range, selectionRange, children) {
\r
3799 selectionRange: selectionRange
\r
3801 if (children !== void 0) {
\r
3802 result.children = children;
\r
3806 DocumentSymbol.create = create;
\r
3808 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
\r
3810 function is(value) {
\r
3811 var candidate = value;
\r
3812 return candidate &&
\r
3813 Is.string(candidate.name) && Is.number(candidate.kind) &&
\r
3814 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
\r
3815 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
\r
3816 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
\r
3817 (candidate.children === void 0 || Array.isArray(candidate.children));
\r
3819 DocumentSymbol.is = is;
\r
3820 })(DocumentSymbol || (DocumentSymbol = {}));
\r
3822 * A set of predefined code action kinds
\r
3824 var CodeActionKind;
\r
3825 (function (CodeActionKind) {
\r
3829 CodeActionKind.Empty = '';
\r
3831 * Base kind for quickfix actions: 'quickfix'
\r
3833 CodeActionKind.QuickFix = 'quickfix';
\r
3835 * Base kind for refactoring actions: 'refactor'
\r
3837 CodeActionKind.Refactor = 'refactor';
\r
3839 * Base kind for refactoring extraction actions: 'refactor.extract'
\r
3841 * Example extract actions:
\r
3843 * - Extract method
\r
3844 * - Extract function
\r
3845 * - Extract variable
\r
3846 * - Extract interface from class
\r
3849 CodeActionKind.RefactorExtract = 'refactor.extract';
\r
3851 * Base kind for refactoring inline actions: 'refactor.inline'
\r
3853 * Example inline actions:
\r
3855 * - Inline function
\r
3856 * - Inline variable
\r
3857 * - Inline constant
\r
3860 CodeActionKind.RefactorInline = 'refactor.inline';
\r
3862 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
\r
3864 * Example rewrite actions:
\r
3866 * - Convert JavaScript function to class
\r
3867 * - Add or remove parameter
\r
3868 * - Encapsulate field
\r
3869 * - Make method static
\r
3870 * - Move method to base class
\r
3873 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
\r
3875 * Base kind for source actions: `source`
\r
3877 * Source code actions apply to the entire file.
\r
3879 CodeActionKind.Source = 'source';
\r
3881 * Base kind for an organize imports source action: `source.organizeImports`
\r
3883 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
\r
3885 * Base kind for auto-fix source actions: `source.fixAll`.
\r
3887 * Fix all actions automatically fix errors that have a clear fix that do not require user input.
\r
3888 * They should not suppress errors or perform unsafe fixes such as generating new types or classes.
\r
3892 CodeActionKind.SourceFixAll = 'source.fixAll';
\r
3893 })(CodeActionKind || (CodeActionKind = {}));
\r
3895 * The CodeActionContext namespace provides helper functions to work with
\r
3896 * [CodeActionContext](#CodeActionContext) literals.
\r
3898 var CodeActionContext;
\r
3899 (function (CodeActionContext) {
\r
3901 * Creates a new CodeActionContext literal.
\r
3903 function create(diagnostics, only) {
\r
3904 var result = { diagnostics: diagnostics };
\r
3905 if (only !== void 0 && only !== null) {
\r
3906 result.only = only;
\r
3910 CodeActionContext.create = create;
\r
3912 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
\r
3914 function is(value) {
\r
3915 var candidate = value;
\r
3916 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
\r
3918 CodeActionContext.is = is;
\r
3919 })(CodeActionContext || (CodeActionContext = {}));
\r
3921 (function (CodeAction) {
\r
3922 function create(title, commandOrEdit, kind) {
\r
3923 var result = { title: title };
\r
3924 if (Command.is(commandOrEdit)) {
\r
3925 result.command = commandOrEdit;
\r
3928 result.edit = commandOrEdit;
\r
3930 if (kind !== void 0) {
\r
3931 result.kind = kind;
\r
3935 CodeAction.create = create;
\r
3936 function is(value) {
\r
3937 var candidate = value;
\r
3938 return candidate && Is.string(candidate.title) &&
\r
3939 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
\r
3940 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
\r
3941 (candidate.edit !== void 0 || candidate.command !== void 0) &&
\r
3942 (candidate.command === void 0 || Command.is(candidate.command)) &&
\r
3943 (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) &&
\r
3944 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
\r
3946 CodeAction.is = is;
\r
3947 })(CodeAction || (CodeAction = {}));
\r
3949 * The CodeLens namespace provides helper functions to work with
\r
3950 * [CodeLens](#CodeLens) literals.
\r
3953 (function (CodeLens) {
\r
3955 * Creates a new CodeLens literal.
\r
3957 function create(range, data) {
\r
3958 var result = { range: range };
\r
3959 if (Is.defined(data)) {
\r
3960 result.data = data;
\r
3964 CodeLens.create = create;
\r
3966 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
\r
3968 function is(value) {
\r
3969 var candidate = value;
\r
3970 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
\r
3973 })(CodeLens || (CodeLens = {}));
\r
3975 * The FormattingOptions namespace provides helper functions to work with
\r
3976 * [FormattingOptions](#FormattingOptions) literals.
\r
3978 var FormattingOptions;
\r
3979 (function (FormattingOptions) {
\r
3981 * Creates a new FormattingOptions literal.
\r
3983 function create(tabSize, insertSpaces) {
\r
3984 return { tabSize: tabSize, insertSpaces: insertSpaces };
\r
3986 FormattingOptions.create = create;
\r
3988 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
\r
3990 function is(value) {
\r
3991 var candidate = value;
\r
3992 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
\r
3994 FormattingOptions.is = is;
\r
3995 })(FormattingOptions || (FormattingOptions = {}));
\r
3997 * The DocumentLink namespace provides helper functions to work with
\r
3998 * [DocumentLink](#DocumentLink) literals.
\r
4001 (function (DocumentLink) {
\r
4003 * Creates a new DocumentLink literal.
\r
4005 function create(range, target, data) {
\r
4006 return { range: range, target: target, data: data };
\r
4008 DocumentLink.create = create;
\r
4010 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
\r
4012 function is(value) {
\r
4013 var candidate = value;
\r
4014 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
\r
4016 DocumentLink.is = is;
\r
4017 })(DocumentLink || (DocumentLink = {}));
\r
4019 * The SelectionRange namespace provides helper function to work with
\r
4020 * SelectionRange literals.
\r
4022 var SelectionRange;
\r
4023 (function (SelectionRange) {
\r
4025 * Creates a new SelectionRange
\r
4026 * @param range the range.
\r
4027 * @param parent an optional parent.
\r
4029 function create(range, parent) {
\r
4030 return { range: range, parent: parent };
\r
4032 SelectionRange.create = create;
\r
4033 function is(value) {
\r
4034 var candidate = value;
\r
4035 return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
\r
4037 SelectionRange.is = is;
\r
4038 })(SelectionRange || (SelectionRange = {}));
\r
4039 var EOL = ['\n', '\r\n', '\r'];
\r
4041 * @deprecated Use the text document from the new vscode-languageserver-textdocument package.
\r
4044 (function (TextDocument) {
\r
4046 * Creates a new ITextDocument literal from the given uri and content.
\r
4047 * @param uri The document's uri.
\r
4048 * @param languageId The document's language Id.
\r
4049 * @param content The document's content.
\r
4051 function create(uri, languageId, version, content) {
\r
4052 return new FullTextDocument(uri, languageId, version, content);
\r
4054 TextDocument.create = create;
\r
4056 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
\r
4058 function is(value) {
\r
4059 var candidate = value;
\r
4060 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
\r
4061 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
\r
4063 TextDocument.is = is;
\r
4064 function applyEdits(document, edits) {
\r
4065 var text = document.getText();
\r
4066 var sortedEdits = mergeSort(edits, function (a, b) {
\r
4067 var diff = a.range.start.line - b.range.start.line;
\r
4069 return a.range.start.character - b.range.start.character;
\r
4073 var lastModifiedOffset = text.length;
\r
4074 for (var i = sortedEdits.length - 1; i >= 0; i--) {
\r
4075 var e = sortedEdits[i];
\r
4076 var startOffset = document.offsetAt(e.range.start);
\r
4077 var endOffset = document.offsetAt(e.range.end);
\r
4078 if (endOffset <= lastModifiedOffset) {
\r
4079 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
\r
4082 throw new Error('Overlapping edit');
\r
4084 lastModifiedOffset = startOffset;
\r
4088 TextDocument.applyEdits = applyEdits;
\r
4089 function mergeSort(data, compare) {
\r
4090 if (data.length <= 1) {
\r
4094 var p = (data.length / 2) | 0;
\r
4095 var left = data.slice(0, p);
\r
4096 var right = data.slice(p);
\r
4097 mergeSort(left, compare);
\r
4098 mergeSort(right, compare);
\r
4102 while (leftIdx < left.length && rightIdx < right.length) {
\r
4103 var ret = compare(left[leftIdx], right[rightIdx]);
\r
4105 // smaller_equal -> take left to preserve order
\r
4106 data[i++] = left[leftIdx++];
\r
4109 // greater -> take right
\r
4110 data[i++] = right[rightIdx++];
\r
4113 while (leftIdx < left.length) {
\r
4114 data[i++] = left[leftIdx++];
\r
4116 while (rightIdx < right.length) {
\r
4117 data[i++] = right[rightIdx++];
\r
4121 })(TextDocument || (TextDocument = {}));
\r
4122 var FullTextDocument = /** @class */ (function () {
\r
4123 function FullTextDocument(uri, languageId, version, content) {
\r
4125 this._languageId = languageId;
\r
4126 this._version = version;
\r
4127 this._content = content;
\r
4128 this._lineOffsets = undefined;
\r
4130 Object.defineProperty(FullTextDocument.prototype, "uri", {
\r
4131 get: function () {
\r
4135 configurable: true
\r
4137 Object.defineProperty(FullTextDocument.prototype, "languageId", {
\r
4138 get: function () {
\r
4139 return this._languageId;
\r
4142 configurable: true
\r
4144 Object.defineProperty(FullTextDocument.prototype, "version", {
\r
4145 get: function () {
\r
4146 return this._version;
\r
4149 configurable: true
\r
4151 FullTextDocument.prototype.getText = function (range) {
\r
4153 var start = this.offsetAt(range.start);
\r
4154 var end = this.offsetAt(range.end);
\r
4155 return this._content.substring(start, end);
\r
4157 return this._content;
\r
4159 FullTextDocument.prototype.update = function (event, version) {
\r
4160 this._content = event.text;
\r
4161 this._version = version;
\r
4162 this._lineOffsets = undefined;
\r
4164 FullTextDocument.prototype.getLineOffsets = function () {
\r
4165 if (this._lineOffsets === undefined) {
\r
4166 var lineOffsets = [];
\r
4167 var text = this._content;
\r
4168 var isLineStart = true;
\r
4169 for (var i = 0; i < text.length; i++) {
\r
4170 if (isLineStart) {
\r
4171 lineOffsets.push(i);
\r
4172 isLineStart = false;
\r
4174 var ch = text.charAt(i);
\r
4175 isLineStart = (ch === '\r' || ch === '\n');
\r
4176 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
\r
4180 if (isLineStart && text.length > 0) {
\r
4181 lineOffsets.push(text.length);
\r
4183 this._lineOffsets = lineOffsets;
\r
4185 return this._lineOffsets;
\r
4187 FullTextDocument.prototype.positionAt = function (offset) {
\r
4188 offset = Math.max(Math.min(offset, this._content.length), 0);
\r
4189 var lineOffsets = this.getLineOffsets();
\r
4190 var low = 0, high = lineOffsets.length;
\r
4192 return Position.create(0, offset);
\r
4194 while (low < high) {
\r
4195 var mid = Math.floor((low + high) / 2);
\r
4196 if (lineOffsets[mid] > offset) {
\r
4203 // low is the least x for which the line offset is larger than the current offset
\r
4204 // or array.length if no line offset is larger than the current offset
\r
4205 var line = low - 1;
\r
4206 return Position.create(line, offset - lineOffsets[line]);
\r
4208 FullTextDocument.prototype.offsetAt = function (position) {
\r
4209 var lineOffsets = this.getLineOffsets();
\r
4210 if (position.line >= lineOffsets.length) {
\r
4211 return this._content.length;
\r
4213 else if (position.line < 0) {
\r
4216 var lineOffset = lineOffsets[position.line];
\r
4217 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
\r
4218 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
\r
4220 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
\r
4221 get: function () {
\r
4222 return this.getLineOffsets().length;
\r
4225 configurable: true
\r
4227 return FullTextDocument;
\r
4231 var toString = Object.prototype.toString;
\r
4232 function defined(value) {
\r
4233 return typeof value !== 'undefined';
\r
4235 Is.defined = defined;
\r
4236 function undefined(value) {
\r
4237 return typeof value === 'undefined';
\r
4239 Is.undefined = undefined;
\r
4240 function boolean(value) {
\r
4241 return value === true || value === false;
\r
4243 Is.boolean = boolean;
\r
4244 function string(value) {
\r
4245 return toString.call(value) === '[object String]';
\r
4247 Is.string = string;
\r
4248 function number(value) {
\r
4249 return toString.call(value) === '[object Number]';
\r
4251 Is.number = number;
\r
4252 function func(value) {
\r
4253 return toString.call(value) === '[object Function]';
\r
4256 function objectLiteral(value) {
\r
4257 // Strictly speaking class instances pass this check as well. Since the LSP
\r
4258 // doesn't use classes we ignore this for now. If we do we need to add something
\r
4259 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
4260 return value !== null && typeof value === 'object';
\r
4262 Is.objectLiteral = objectLiteral;
\r
4263 function typedArray(value, check) {
\r
4264 return Array.isArray(value) && value.every(check);
\r
4266 Is.typedArray = typedArray;
\r
4267 })(Is || (Is = {}));
\r
4272 /***/ (function(module, exports, __webpack_require__) {
4275 /* --------------------------------------------------------------------------------------------
\r
4276 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4277 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4278 * ------------------------------------------------------------------------------------------ */
\r
4280 Object.defineProperty(exports, "__esModule", { value: true });
\r
4281 const Is = __webpack_require__(20);
\r
4282 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
4283 const messages_1 = __webpack_require__(21);
\r
4284 const protocol_implementation_1 = __webpack_require__(22);
\r
4285 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
\r
4286 const protocol_typeDefinition_1 = __webpack_require__(23);
\r
4287 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
\r
4288 const protocol_workspaceFolders_1 = __webpack_require__(24);
\r
4289 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
\r
4290 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
\r
4291 const protocol_configuration_1 = __webpack_require__(25);
\r
4292 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
\r
4293 const protocol_colorProvider_1 = __webpack_require__(26);
\r
4294 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
\r
4295 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
\r
4296 const protocol_foldingRange_1 = __webpack_require__(27);
\r
4297 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
\r
4298 const protocol_declaration_1 = __webpack_require__(28);
\r
4299 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
\r
4300 const protocol_selectionRange_1 = __webpack_require__(29);
\r
4301 exports.SelectionRangeRequest = protocol_selectionRange_1.SelectionRangeRequest;
\r
4302 const protocol_progress_1 = __webpack_require__(30);
\r
4303 exports.WorkDoneProgress = protocol_progress_1.WorkDoneProgress;
\r
4304 exports.WorkDoneProgressCreateRequest = protocol_progress_1.WorkDoneProgressCreateRequest;
\r
4305 exports.WorkDoneProgressCancelNotification = protocol_progress_1.WorkDoneProgressCancelNotification;
\r
4306 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4307 let __noDynamicImport;
\r
4309 * The DocumentFilter namespace provides helper functions to work with
\r
4310 * [DocumentFilter](#DocumentFilter) literals.
\r
4312 var DocumentFilter;
\r
4313 (function (DocumentFilter) {
\r
4314 function is(value) {
\r
4315 const candidate = value;
\r
4316 return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
\r
4318 DocumentFilter.is = is;
\r
4319 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
\r
4321 * The DocumentSelector namespace provides helper functions to work with
\r
4322 * [DocumentSelector](#DocumentSelector)s.
\r
4324 var DocumentSelector;
\r
4325 (function (DocumentSelector) {
\r
4326 function is(value) {
\r
4327 if (!Array.isArray(value)) {
\r
4330 for (let elem of value) {
\r
4331 if (!Is.string(elem) && !DocumentFilter.is(elem)) {
\r
4337 DocumentSelector.is = is;
\r
4338 })(DocumentSelector = exports.DocumentSelector || (exports.DocumentSelector = {}));
\r
4340 * The `client/registerCapability` request is sent from the server to the client to register a new capability
\r
4341 * handler on the client side.
\r
4343 var RegistrationRequest;
\r
4344 (function (RegistrationRequest) {
\r
4345 RegistrationRequest.type = new messages_1.ProtocolRequestType('client/registerCapability');
\r
4346 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
\r
4348 * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
\r
4349 * handler on the client side.
\r
4351 var UnregistrationRequest;
\r
4352 (function (UnregistrationRequest) {
\r
4353 UnregistrationRequest.type = new messages_1.ProtocolRequestType('client/unregisterCapability');
\r
4354 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
\r
4355 var ResourceOperationKind;
\r
4356 (function (ResourceOperationKind) {
\r
4358 * Supports creating new files and folders.
\r
4360 ResourceOperationKind.Create = 'create';
\r
4362 * Supports renaming existing files and folders.
\r
4364 ResourceOperationKind.Rename = 'rename';
\r
4366 * Supports deleting existing files and folders.
\r
4368 ResourceOperationKind.Delete = 'delete';
\r
4369 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
\r
4370 var FailureHandlingKind;
\r
4371 (function (FailureHandlingKind) {
\r
4373 * Applying the workspace change is simply aborted if one of the changes provided
\r
4374 * fails. All operations executed before the failing operation stay executed.
\r
4376 FailureHandlingKind.Abort = 'abort';
\r
4378 * All operations are executed transactional. That means they either all
\r
4379 * succeed or no changes at all are applied to the workspace.
\r
4381 FailureHandlingKind.Transactional = 'transactional';
\r
4383 * If the workspace edit contains only textual file changes they are executed transactional.
\r
4384 * If resource changes (create, rename or delete file) are part of the change the failure
\r
4385 * handling startegy is abort.
\r
4387 FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
\r
4389 * The client tries to undo the operations already executed. But there is no
\r
4390 * guarantee that this is succeeding.
\r
4392 FailureHandlingKind.Undo = 'undo';
\r
4393 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
\r
4395 * The StaticRegistrationOptions namespace provides helper functions to work with
\r
4396 * [StaticRegistrationOptions](#StaticRegistrationOptions) literals.
\r
4398 var StaticRegistrationOptions;
\r
4399 (function (StaticRegistrationOptions) {
\r
4400 function hasId(value) {
\r
4401 const candidate = value;
\r
4402 return candidate && Is.string(candidate.id) && candidate.id.length > 0;
\r
4404 StaticRegistrationOptions.hasId = hasId;
\r
4405 })(StaticRegistrationOptions = exports.StaticRegistrationOptions || (exports.StaticRegistrationOptions = {}));
\r
4407 * The TextDocumentRegistrationOptions namespace provides helper functions to work with
\r
4408 * [TextDocumentRegistrationOptions](#TextDocumentRegistrationOptions) literals.
\r
4410 var TextDocumentRegistrationOptions;
\r
4411 (function (TextDocumentRegistrationOptions) {
\r
4412 function is(value) {
\r
4413 const candidate = value;
\r
4414 return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
\r
4416 TextDocumentRegistrationOptions.is = is;
\r
4417 })(TextDocumentRegistrationOptions = exports.TextDocumentRegistrationOptions || (exports.TextDocumentRegistrationOptions = {}));
\r
4419 * The WorkDoneProgressOptions namespace provides helper functions to work with
\r
4420 * [WorkDoneProgressOptions](#WorkDoneProgressOptions) literals.
\r
4422 var WorkDoneProgressOptions;
\r
4423 (function (WorkDoneProgressOptions) {
\r
4424 function is(value) {
\r
4425 const candidate = value;
\r
4426 return Is.objectLiteral(candidate) && (candidate.workDoneProgress === undefined || Is.boolean(candidate.workDoneProgress));
\r
4428 WorkDoneProgressOptions.is = is;
\r
4429 function hasWorkDoneProgress(value) {
\r
4430 const candidate = value;
\r
4431 return candidate && Is.boolean(candidate.workDoneProgress);
\r
4433 WorkDoneProgressOptions.hasWorkDoneProgress = hasWorkDoneProgress;
\r
4434 })(WorkDoneProgressOptions = exports.WorkDoneProgressOptions || (exports.WorkDoneProgressOptions = {}));
\r
4436 * The initialize request is sent from the client to the server.
\r
4437 * It is sent once as the request after starting up the server.
\r
4438 * The requests parameter is of type [InitializeParams](#InitializeParams)
\r
4439 * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
\r
4440 * resolves to such.
\r
4442 var InitializeRequest;
\r
4443 (function (InitializeRequest) {
\r
4444 InitializeRequest.type = new messages_1.ProtocolRequestType('initialize');
\r
4445 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
\r
4447 * Known error codes for an `InitializeError`;
\r
4449 var InitializeError;
\r
4450 (function (InitializeError) {
\r
4452 * If the protocol version provided by the client can't be handled by the server.
\r
4453 * @deprecated This initialize error got replaced by client capabilities. There is
\r
4454 * no version handshake in version 3.0x
\r
4456 InitializeError.unknownProtocolVersion = 1;
\r
4457 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
\r
4459 * The intialized notification is sent from the client to the
\r
4460 * server after the client is fully initialized and the server
\r
4461 * is allowed to send requests from the server to the client.
\r
4463 var InitializedNotification;
\r
4464 (function (InitializedNotification) {
\r
4465 InitializedNotification.type = new messages_1.ProtocolNotificationType('initialized');
\r
4466 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
\r
4467 //---- Shutdown Method ----
\r
4469 * A shutdown request is sent from the client to the server.
\r
4470 * It is sent once when the client decides to shutdown the
\r
4471 * server. The only notification that is sent after a shutdown request
\r
4472 * is the exit event.
\r
4474 var ShutdownRequest;
\r
4475 (function (ShutdownRequest) {
\r
4476 ShutdownRequest.type = new messages_1.ProtocolRequestType0('shutdown');
\r
4477 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
\r
4478 //---- Exit Notification ----
\r
4480 * The exit event is sent from the client to the server to
\r
4481 * ask the server to exit its process.
\r
4483 var ExitNotification;
\r
4484 (function (ExitNotification) {
\r
4485 ExitNotification.type = new messages_1.ProtocolNotificationType0('exit');
\r
4486 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
\r
4488 * The configuration change notification is sent from the client to the server
\r
4489 * when the client's configuration has changed. The notification contains
\r
4490 * the changed configuration as defined by the language client.
\r
4492 var DidChangeConfigurationNotification;
\r
4493 (function (DidChangeConfigurationNotification) {
\r
4494 DidChangeConfigurationNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeConfiguration');
\r
4495 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
\r
4496 //---- Message show and log notifications ----
\r
4498 * The message type
\r
4501 (function (MessageType) {
\r
4503 * An error message.
\r
4505 MessageType.Error = 1;
\r
4507 * A warning message.
\r
4509 MessageType.Warning = 2;
\r
4511 * An information message.
\r
4513 MessageType.Info = 3;
\r
4517 MessageType.Log = 4;
\r
4518 })(MessageType = exports.MessageType || (exports.MessageType = {}));
\r
4520 * The show message notification is sent from a server to a client to ask
\r
4521 * the client to display a particular message in the user interface.
\r
4523 var ShowMessageNotification;
\r
4524 (function (ShowMessageNotification) {
\r
4525 ShowMessageNotification.type = new messages_1.ProtocolNotificationType('window/showMessage');
\r
4526 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
\r
4528 * The show message request is sent from the server to the client to show a message
\r
4529 * and a set of options actions to the user.
\r
4531 var ShowMessageRequest;
\r
4532 (function (ShowMessageRequest) {
\r
4533 ShowMessageRequest.type = new messages_1.ProtocolRequestType('window/showMessageRequest');
\r
4534 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
\r
4536 * The log message notification is sent from the server to the client to ask
\r
4537 * the client to log a particular message.
\r
4539 var LogMessageNotification;
\r
4540 (function (LogMessageNotification) {
\r
4541 LogMessageNotification.type = new messages_1.ProtocolNotificationType('window/logMessage');
\r
4542 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
\r
4543 //---- Telemetry notification
\r
4545 * The telemetry event notification is sent from the server to the client to ask
\r
4546 * the client to log telemetry data.
\r
4548 var TelemetryEventNotification;
\r
4549 (function (TelemetryEventNotification) {
\r
4550 TelemetryEventNotification.type = new messages_1.ProtocolNotificationType('telemetry/event');
\r
4551 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
\r
4553 * Defines how the host (editor) should sync
\r
4554 * document changes to the language server.
\r
4556 var TextDocumentSyncKind;
\r
4557 (function (TextDocumentSyncKind) {
\r
4559 * Documents should not be synced at all.
\r
4561 TextDocumentSyncKind.None = 0;
\r
4563 * Documents are synced by always sending the full content
\r
4564 * of the document.
\r
4566 TextDocumentSyncKind.Full = 1;
\r
4568 * Documents are synced by sending the full content on open.
\r
4569 * After that only incremental updates to the document are
\r
4572 TextDocumentSyncKind.Incremental = 2;
\r
4573 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
\r
4575 * The document open notification is sent from the client to the server to signal
\r
4576 * newly opened text documents. The document's truth is now managed by the client
\r
4577 * and the server must not try to read the document's truth using the document's
\r
4578 * uri. Open in this sense means it is managed by the client. It doesn't necessarily
\r
4579 * mean that its content is presented in an editor. An open notification must not
\r
4580 * be sent more than once without a corresponding close notification send before.
\r
4581 * This means open and close notification must be balanced and the max open count
\r
4584 var DidOpenTextDocumentNotification;
\r
4585 (function (DidOpenTextDocumentNotification) {
\r
4586 DidOpenTextDocumentNotification.method = 'textDocument/didOpen';
\r
4587 DidOpenTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification.method);
\r
4588 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
\r
4590 * The document change notification is sent from the client to the server to signal
\r
4591 * changes to a text document.
\r
4593 var DidChangeTextDocumentNotification;
\r
4594 (function (DidChangeTextDocumentNotification) {
\r
4595 DidChangeTextDocumentNotification.method = 'textDocument/didChange';
\r
4596 DidChangeTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification.method);
\r
4597 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
\r
4599 * The document close notification is sent from the client to the server when
\r
4600 * the document got closed in the client. The document's truth now exists where
\r
4601 * the document's uri points to (e.g. if the document's uri is a file uri the
\r
4602 * truth now exists on disk). As with the open notification the close notification
\r
4603 * is about managing the document's content. Receiving a close notification
\r
4604 * doesn't mean that the document was open in an editor before. A close
\r
4605 * notification requires a previous open notification to be sent.
\r
4607 var DidCloseTextDocumentNotification;
\r
4608 (function (DidCloseTextDocumentNotification) {
\r
4609 DidCloseTextDocumentNotification.method = 'textDocument/didClose';
\r
4610 DidCloseTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification.method);
\r
4611 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
\r
4613 * The document save notification is sent from the client to the server when
\r
4614 * the document got saved in the client.
\r
4616 var DidSaveTextDocumentNotification;
\r
4617 (function (DidSaveTextDocumentNotification) {
\r
4618 DidSaveTextDocumentNotification.method = 'textDocument/didSave';
\r
4619 DidSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification.method);
\r
4620 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
\r
4622 * Represents reasons why a text document is saved.
\r
4624 var TextDocumentSaveReason;
\r
4625 (function (TextDocumentSaveReason) {
\r
4627 * Manually triggered, e.g. by the user pressing save, by starting debugging,
\r
4628 * or by an API call.
\r
4630 TextDocumentSaveReason.Manual = 1;
\r
4632 * Automatic after a delay.
\r
4634 TextDocumentSaveReason.AfterDelay = 2;
\r
4636 * When the editor lost focus.
\r
4638 TextDocumentSaveReason.FocusOut = 3;
\r
4639 })(TextDocumentSaveReason = exports.TextDocumentSaveReason || (exports.TextDocumentSaveReason = {}));
\r
4641 * A document will save notification is sent from the client to the server before
\r
4642 * the document is actually saved.
\r
4644 var WillSaveTextDocumentNotification;
\r
4645 (function (WillSaveTextDocumentNotification) {
\r
4646 WillSaveTextDocumentNotification.method = 'textDocument/willSave';
\r
4647 WillSaveTextDocumentNotification.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification.method);
\r
4648 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
\r
4650 * A document will save request is sent from the client to the server before
\r
4651 * the document is actually saved. The request can return an array of TextEdits
\r
4652 * which will be applied to the text document before it is saved. Please note that
\r
4653 * clients might drop results if computing the text edits took too long or if a
\r
4654 * server constantly fails on this request. This is done to keep the save fast and
\r
4657 var WillSaveTextDocumentWaitUntilRequest;
\r
4658 (function (WillSaveTextDocumentWaitUntilRequest) {
\r
4659 WillSaveTextDocumentWaitUntilRequest.method = 'textDocument/willSaveWaitUntil';
\r
4660 WillSaveTextDocumentWaitUntilRequest.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest.method);
\r
4661 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
\r
4663 * The watched files notification is sent from the client to the server when
\r
4664 * the client detects changes to file watched by the language client.
\r
4666 var DidChangeWatchedFilesNotification;
\r
4667 (function (DidChangeWatchedFilesNotification) {
\r
4668 DidChangeWatchedFilesNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWatchedFiles');
\r
4669 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
\r
4671 * The file event type
\r
4673 var FileChangeType;
\r
4674 (function (FileChangeType) {
\r
4676 * The file got created.
\r
4678 FileChangeType.Created = 1;
\r
4680 * The file got changed.
\r
4682 FileChangeType.Changed = 2;
\r
4684 * The file got deleted.
\r
4686 FileChangeType.Deleted = 3;
\r
4687 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
\r
4689 (function (WatchKind) {
\r
4691 * Interested in create events.
\r
4693 WatchKind.Create = 1;
\r
4695 * Interested in change events
\r
4697 WatchKind.Change = 2;
\r
4699 * Interested in delete events
\r
4701 WatchKind.Delete = 4;
\r
4702 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
\r
4704 * Diagnostics notification are sent from the server to the client to signal
\r
4705 * results of validation runs.
\r
4707 var PublishDiagnosticsNotification;
\r
4708 (function (PublishDiagnosticsNotification) {
\r
4709 PublishDiagnosticsNotification.type = new messages_1.ProtocolNotificationType('textDocument/publishDiagnostics');
\r
4710 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
\r
4712 * How a completion was triggered
\r
4714 var CompletionTriggerKind;
\r
4715 (function (CompletionTriggerKind) {
\r
4717 * Completion was triggered by typing an identifier (24x7 code
\r
4718 * complete), manual invocation (e.g Ctrl+Space) or via API.
\r
4720 CompletionTriggerKind.Invoked = 1;
\r
4722 * Completion was triggered by a trigger character specified by
\r
4723 * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
\r
4725 CompletionTriggerKind.TriggerCharacter = 2;
\r
4727 * Completion was re-triggered as current completion list is incomplete
\r
4729 CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
\r
4730 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
\r
4732 * Request to request completion at a given text document position. The request's
\r
4733 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
\r
4734 * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
\r
4735 * or a Thenable that resolves to such.
\r
4737 * The request can delay the computation of the [`detail`](#CompletionItem.detail)
\r
4738 * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
\r
4739 * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
\r
4740 * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
\r
4742 var CompletionRequest;
\r
4743 (function (CompletionRequest) {
\r
4744 CompletionRequest.method = 'textDocument/completion';
\r
4745 CompletionRequest.type = new messages_1.ProtocolRequestType(CompletionRequest.method);
\r
4746 /** @deprecated Use CompletionRequest.type */
\r
4747 CompletionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4748 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
\r
4750 * Request to resolve additional information for a given completion item.The request's
\r
4751 * parameter is of type [CompletionItem](#CompletionItem) the response
\r
4752 * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
\r
4754 var CompletionResolveRequest;
\r
4755 (function (CompletionResolveRequest) {
\r
4756 CompletionResolveRequest.method = 'completionItem/resolve';
\r
4757 CompletionResolveRequest.type = new messages_1.ProtocolRequestType(CompletionResolveRequest.method);
\r
4758 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
\r
4760 * Request to request hover information at a given text document position. The request's
\r
4761 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
\r
4762 * type [Hover](#Hover) or a Thenable that resolves to such.
\r
4765 (function (HoverRequest) {
\r
4766 HoverRequest.method = 'textDocument/hover';
\r
4767 HoverRequest.type = new messages_1.ProtocolRequestType(HoverRequest.method);
\r
4768 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
\r
4770 * How a signature help was triggered.
\r
4774 var SignatureHelpTriggerKind;
\r
4775 (function (SignatureHelpTriggerKind) {
\r
4777 * Signature help was invoked manually by the user or by a command.
\r
4779 SignatureHelpTriggerKind.Invoked = 1;
\r
4781 * Signature help was triggered by a trigger character.
\r
4783 SignatureHelpTriggerKind.TriggerCharacter = 2;
\r
4785 * Signature help was triggered by the cursor moving or by the document content changing.
\r
4787 SignatureHelpTriggerKind.ContentChange = 3;
\r
4788 })(SignatureHelpTriggerKind = exports.SignatureHelpTriggerKind || (exports.SignatureHelpTriggerKind = {}));
\r
4789 var SignatureHelpRequest;
\r
4790 (function (SignatureHelpRequest) {
\r
4791 SignatureHelpRequest.method = 'textDocument/signatureHelp';
\r
4792 SignatureHelpRequest.type = new messages_1.ProtocolRequestType(SignatureHelpRequest.method);
\r
4793 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
\r
4795 * A request to resolve the definition location of a symbol at a given text
\r
4796 * document position. The request's parameter is of type [TextDocumentPosition]
\r
4797 * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
\r
4798 * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
\r
4801 var DefinitionRequest;
\r
4802 (function (DefinitionRequest) {
\r
4803 DefinitionRequest.method = 'textDocument/definition';
\r
4804 DefinitionRequest.type = new messages_1.ProtocolRequestType(DefinitionRequest.method);
\r
4805 /** @deprecated Use DefinitionRequest.type */
\r
4806 DefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4807 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
\r
4809 * A request to resolve project-wide references for the symbol denoted
\r
4810 * by the given text document position. The request's parameter is of
\r
4811 * type [ReferenceParams](#ReferenceParams) the response is of type
\r
4812 * [Location[]](#Location) or a Thenable that resolves to such.
\r
4814 var ReferencesRequest;
\r
4815 (function (ReferencesRequest) {
\r
4816 ReferencesRequest.method = 'textDocument/references';
\r
4817 ReferencesRequest.type = new messages_1.ProtocolRequestType(ReferencesRequest.method);
\r
4818 /** @deprecated Use ReferencesRequest.type */
\r
4819 ReferencesRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4820 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
\r
4822 * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
\r
4823 * text document position. The request's parameter is of type [TextDocumentPosition]
\r
4824 * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
\r
4825 * (#DocumentHighlight) or a Thenable that resolves to such.
\r
4827 var DocumentHighlightRequest;
\r
4828 (function (DocumentHighlightRequest) {
\r
4829 DocumentHighlightRequest.method = 'textDocument/documentHighlight';
\r
4830 DocumentHighlightRequest.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest.method);
\r
4831 /** @deprecated Use DocumentHighlightRequest.type */
\r
4832 DocumentHighlightRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4833 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
\r
4835 * A request to list all symbols found in a given text document. The request's
\r
4836 * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
\r
4837 * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
\r
4838 * that resolves to such.
\r
4840 var DocumentSymbolRequest;
\r
4841 (function (DocumentSymbolRequest) {
\r
4842 DocumentSymbolRequest.method = 'textDocument/documentSymbol';
\r
4843 DocumentSymbolRequest.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest.method);
\r
4844 /** @deprecated Use DocumentSymbolRequest.type */
\r
4845 DocumentSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4846 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
\r
4848 * A request to provide commands for the given text document and range.
\r
4850 var CodeActionRequest;
\r
4851 (function (CodeActionRequest) {
\r
4852 CodeActionRequest.method = 'textDocument/codeAction';
\r
4853 CodeActionRequest.type = new messages_1.ProtocolRequestType(CodeActionRequest.method);
\r
4854 /** @deprecated Use CodeActionRequest.type */
\r
4855 CodeActionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4856 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
\r
4858 * A request to list project-wide symbols matching the query string given
\r
4859 * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
\r
4860 * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
\r
4861 * resolves to such.
\r
4863 var WorkspaceSymbolRequest;
\r
4864 (function (WorkspaceSymbolRequest) {
\r
4865 WorkspaceSymbolRequest.method = 'workspace/symbol';
\r
4866 WorkspaceSymbolRequest.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest.method);
\r
4867 /** @deprecated Use WorkspaceSymbolRequest.type */
\r
4868 WorkspaceSymbolRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4869 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
\r
4871 * A request to provide code lens for the given text document.
\r
4873 var CodeLensRequest;
\r
4874 (function (CodeLensRequest) {
\r
4875 CodeLensRequest.type = new messages_1.ProtocolRequestType('textDocument/codeLens');
\r
4876 /** @deprecated Use CodeLensRequest.type */
\r
4877 CodeLensRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4878 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
\r
4880 * A request to resolve a command for a given code lens.
\r
4882 var CodeLensResolveRequest;
\r
4883 (function (CodeLensResolveRequest) {
\r
4884 CodeLensResolveRequest.type = new messages_1.ProtocolRequestType('codeLens/resolve');
\r
4885 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
\r
4887 * A request to provide document links
\r
4889 var DocumentLinkRequest;
\r
4890 (function (DocumentLinkRequest) {
\r
4891 DocumentLinkRequest.method = 'textDocument/documentLink';
\r
4892 DocumentLinkRequest.type = new messages_1.ProtocolRequestType(DocumentLinkRequest.method);
\r
4893 /** @deprecated Use DocumentLinkRequest.type */
\r
4894 DocumentLinkRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
4895 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
\r
4897 * Request to resolve additional information for a given document link. The request's
\r
4898 * parameter is of type [DocumentLink](#DocumentLink) the response
\r
4899 * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
\r
4901 var DocumentLinkResolveRequest;
\r
4902 (function (DocumentLinkResolveRequest) {
\r
4903 DocumentLinkResolveRequest.type = new messages_1.ProtocolRequestType('documentLink/resolve');
\r
4904 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
\r
4906 * A request to to format a whole document.
\r
4908 var DocumentFormattingRequest;
\r
4909 (function (DocumentFormattingRequest) {
\r
4910 DocumentFormattingRequest.method = 'textDocument/formatting';
\r
4911 DocumentFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest.method);
\r
4912 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
\r
4914 * A request to to format a range in a document.
\r
4916 var DocumentRangeFormattingRequest;
\r
4917 (function (DocumentRangeFormattingRequest) {
\r
4918 DocumentRangeFormattingRequest.method = 'textDocument/rangeFormatting';
\r
4919 DocumentRangeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest.method);
\r
4920 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
\r
4922 * A request to format a document on type.
\r
4924 var DocumentOnTypeFormattingRequest;
\r
4925 (function (DocumentOnTypeFormattingRequest) {
\r
4926 DocumentOnTypeFormattingRequest.method = 'textDocument/onTypeFormatting';
\r
4927 DocumentOnTypeFormattingRequest.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest.method);
\r
4928 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
\r
4930 * A request to rename a symbol.
\r
4932 var RenameRequest;
\r
4933 (function (RenameRequest) {
\r
4934 RenameRequest.method = 'textDocument/rename';
\r
4935 RenameRequest.type = new messages_1.ProtocolRequestType(RenameRequest.method);
\r
4936 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
\r
4938 * A request to test and perform the setup necessary for a rename.
\r
4940 var PrepareRenameRequest;
\r
4941 (function (PrepareRenameRequest) {
\r
4942 PrepareRenameRequest.method = 'textDocument/prepareRename';
\r
4943 PrepareRenameRequest.type = new messages_1.ProtocolRequestType(PrepareRenameRequest.method);
\r
4944 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
\r
4946 * A request send from the client to the server to execute a command. The request might return
\r
4947 * a workspace edit which the client will apply to the workspace.
\r
4949 var ExecuteCommandRequest;
\r
4950 (function (ExecuteCommandRequest) {
\r
4951 ExecuteCommandRequest.type = new messages_1.ProtocolRequestType('workspace/executeCommand');
\r
4952 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
\r
4954 * A request sent from the server to the client to modified certain resources.
\r
4956 var ApplyWorkspaceEditRequest;
\r
4957 (function (ApplyWorkspaceEditRequest) {
\r
4958 ApplyWorkspaceEditRequest.type = new messages_1.ProtocolRequestType('workspace/applyEdit');
\r
4959 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
\r
4964 /***/ (function(module, exports, __webpack_require__) {
4967 /* --------------------------------------------------------------------------------------------
\r
4968 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4969 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4970 * ------------------------------------------------------------------------------------------ */
\r
4972 Object.defineProperty(exports, "__esModule", { value: true });
\r
4973 function boolean(value) {
\r
4974 return value === true || value === false;
\r
4976 exports.boolean = boolean;
\r
4977 function string(value) {
\r
4978 return typeof value === 'string' || value instanceof String;
\r
4980 exports.string = string;
\r
4981 function number(value) {
\r
4982 return typeof value === 'number' || value instanceof Number;
\r
4984 exports.number = number;
\r
4985 function error(value) {
\r
4986 return value instanceof Error;
\r
4988 exports.error = error;
\r
4989 function func(value) {
\r
4990 return typeof value === 'function';
\r
4992 exports.func = func;
\r
4993 function array(value) {
\r
4994 return Array.isArray(value);
\r
4996 exports.array = array;
\r
4997 function stringArray(value) {
\r
4998 return array(value) && value.every(elem => string(elem));
\r
5000 exports.stringArray = stringArray;
\r
5001 function typedArray(value, check) {
\r
5002 return Array.isArray(value) && value.every(check);
\r
5004 exports.typedArray = typedArray;
\r
5005 function objectLiteral(value) {
\r
5006 // Strictly speaking class instances pass this check as well. Since the LSP
\r
5007 // doesn't use classes we ignore this for now. If we do we need to add something
\r
5008 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
5009 return value !== null && typeof value === 'object';
\r
5011 exports.objectLiteral = objectLiteral;
\r
5016 /***/ (function(module, exports, __webpack_require__) {
5019 /* --------------------------------------------------------------------------------------------
\r
5020 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5021 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5022 * ------------------------------------------------------------------------------------------ */
\r
5024 Object.defineProperty(exports, "__esModule", { value: true });
\r
5025 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5026 class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
\r
5027 constructor(method) {
\r
5031 exports.ProtocolRequestType0 = ProtocolRequestType0;
\r
5032 class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
\r
5033 constructor(method) {
\r
5037 exports.ProtocolRequestType = ProtocolRequestType;
\r
5038 class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
\r
5039 constructor(method) {
\r
5043 exports.ProtocolNotificationType = ProtocolNotificationType;
\r
5044 class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
\r
5045 constructor(method) {
\r
5049 exports.ProtocolNotificationType0 = ProtocolNotificationType0;
\r
5054 /***/ (function(module, exports, __webpack_require__) {
5057 /* --------------------------------------------------------------------------------------------
\r
5058 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5059 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5060 * ------------------------------------------------------------------------------------------ */
\r
5062 Object.defineProperty(exports, "__esModule", { value: true });
\r
5063 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5064 const messages_1 = __webpack_require__(21);
\r
5065 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5066 let __noDynamicImport;
\r
5068 * A request to resolve the implementation locations of a symbol at a given text
\r
5069 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5070 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5071 * Thenable that resolves to such.
\r
5073 var ImplementationRequest;
\r
5074 (function (ImplementationRequest) {
\r
5075 ImplementationRequest.method = 'textDocument/implementation';
\r
5076 ImplementationRequest.type = new messages_1.ProtocolRequestType(ImplementationRequest.method);
\r
5077 /** @deprecated Use ImplementationRequest.type */
\r
5078 ImplementationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5079 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
\r
5084 /***/ (function(module, exports, __webpack_require__) {
5087 /* --------------------------------------------------------------------------------------------
\r
5088 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5089 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5090 * ------------------------------------------------------------------------------------------ */
\r
5092 Object.defineProperty(exports, "__esModule", { value: true });
\r
5093 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5094 const messages_1 = __webpack_require__(21);
\r
5095 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5096 let __noDynamicImport;
\r
5098 * A request to resolve the type definition locations of a symbol at a given text
\r
5099 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5100 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
5101 * Thenable that resolves to such.
\r
5103 var TypeDefinitionRequest;
\r
5104 (function (TypeDefinitionRequest) {
\r
5105 TypeDefinitionRequest.method = 'textDocument/typeDefinition';
\r
5106 TypeDefinitionRequest.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest.method);
\r
5107 /** @deprecated Use TypeDefinitionRequest.type */
\r
5108 TypeDefinitionRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5109 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
\r
5114 /***/ (function(module, exports, __webpack_require__) {
5117 /* --------------------------------------------------------------------------------------------
\r
5118 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5119 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5120 * ------------------------------------------------------------------------------------------ */
\r
5122 Object.defineProperty(exports, "__esModule", { value: true });
\r
5123 const messages_1 = __webpack_require__(21);
\r
5125 * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
\r
5127 var WorkspaceFoldersRequest;
\r
5128 (function (WorkspaceFoldersRequest) {
\r
5129 WorkspaceFoldersRequest.type = new messages_1.ProtocolRequestType0('workspace/workspaceFolders');
\r
5130 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
\r
5132 * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
\r
5133 * folder configuration changes.
\r
5135 var DidChangeWorkspaceFoldersNotification;
\r
5136 (function (DidChangeWorkspaceFoldersNotification) {
\r
5137 DidChangeWorkspaceFoldersNotification.type = new messages_1.ProtocolNotificationType('workspace/didChangeWorkspaceFolders');
\r
5138 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
\r
5143 /***/ (function(module, exports, __webpack_require__) {
5146 /* --------------------------------------------------------------------------------------------
\r
5147 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5148 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5149 * ------------------------------------------------------------------------------------------ */
\r
5151 Object.defineProperty(exports, "__esModule", { value: true });
\r
5152 const messages_1 = __webpack_require__(21);
\r
5154 * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
\r
5155 * configuration setting.
\r
5157 * This pull model replaces the old push model were the client signaled configuration change via an
\r
5158 * event. If the server still needs to react to configuration changes (since the server caches the
\r
5159 * result of `workspace/configuration` requests) the server should register for an empty configuration
\r
5160 * change event and empty the cache if such an event is received.
\r
5162 var ConfigurationRequest;
\r
5163 (function (ConfigurationRequest) {
\r
5164 ConfigurationRequest.type = new messages_1.ProtocolRequestType('workspace/configuration');
\r
5165 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
\r
5170 /***/ (function(module, exports, __webpack_require__) {
5173 /* --------------------------------------------------------------------------------------------
\r
5174 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5175 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5176 * ------------------------------------------------------------------------------------------ */
\r
5178 Object.defineProperty(exports, "__esModule", { value: true });
\r
5179 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5180 const messages_1 = __webpack_require__(21);
\r
5182 * A request to list all color symbols found in a given text document. The request's
\r
5183 * parameter is of type [DocumentColorParams](#DocumentColorParams) the
\r
5184 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5185 * that resolves to such.
\r
5187 var DocumentColorRequest;
\r
5188 (function (DocumentColorRequest) {
\r
5189 DocumentColorRequest.method = 'textDocument/documentColor';
\r
5190 DocumentColorRequest.type = new messages_1.ProtocolRequestType(DocumentColorRequest.method);
\r
5191 /** @deprecated Use DocumentColorRequest.type */
\r
5192 DocumentColorRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5193 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
\r
5195 * A request to list all presentation for a color. The request's
\r
5196 * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
\r
5197 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
5198 * that resolves to such.
\r
5200 var ColorPresentationRequest;
\r
5201 (function (ColorPresentationRequest) {
\r
5202 ColorPresentationRequest.type = new messages_1.ProtocolRequestType('textDocument/colorPresentation');
\r
5203 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
\r
5208 /***/ (function(module, exports, __webpack_require__) {
5212 /*---------------------------------------------------------------------------------------------
\r
5213 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5214 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5215 *--------------------------------------------------------------------------------------------*/
\r
5216 Object.defineProperty(exports, "__esModule", { value: true });
\r
5217 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5218 const messages_1 = __webpack_require__(21);
\r
5220 * Enum of known range kinds
\r
5222 var FoldingRangeKind;
\r
5223 (function (FoldingRangeKind) {
\r
5225 * Folding range for a comment
\r
5227 FoldingRangeKind["Comment"] = "comment";
\r
5229 * Folding range for a imports or includes
\r
5231 FoldingRangeKind["Imports"] = "imports";
\r
5233 * Folding range for a region (e.g. `#region`)
\r
5235 FoldingRangeKind["Region"] = "region";
\r
5236 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
\r
5238 * A request to provide folding ranges in a document. The request's
\r
5239 * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
\r
5240 * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
\r
5241 * that resolves to such.
\r
5243 var FoldingRangeRequest;
\r
5244 (function (FoldingRangeRequest) {
\r
5245 FoldingRangeRequest.method = 'textDocument/foldingRange';
\r
5246 FoldingRangeRequest.type = new messages_1.ProtocolRequestType(FoldingRangeRequest.method);
\r
5247 /** @deprecated Use FoldingRangeRequest.type */
\r
5248 FoldingRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5249 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
\r
5254 /***/ (function(module, exports, __webpack_require__) {
5257 /* --------------------------------------------------------------------------------------------
\r
5258 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5259 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5260 * ------------------------------------------------------------------------------------------ */
\r
5262 Object.defineProperty(exports, "__esModule", { value: true });
\r
5263 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5264 const messages_1 = __webpack_require__(21);
\r
5265 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
5266 let __noDynamicImport;
\r
5268 * A request to resolve the type definition locations of a symbol at a given text
\r
5269 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
5270 * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
\r
5271 * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
\r
5274 var DeclarationRequest;
\r
5275 (function (DeclarationRequest) {
\r
5276 DeclarationRequest.method = 'textDocument/declaration';
\r
5277 DeclarationRequest.type = new messages_1.ProtocolRequestType(DeclarationRequest.method);
\r
5278 /** @deprecated Use DeclarationRequest.type */
\r
5279 DeclarationRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5280 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
\r
5285 /***/ (function(module, exports, __webpack_require__) {
5289 /*---------------------------------------------------------------------------------------------
\r
5290 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5291 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5292 *--------------------------------------------------------------------------------------------*/
\r
5293 Object.defineProperty(exports, "__esModule", { value: true });
\r
5294 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5295 const messages_1 = __webpack_require__(21);
\r
5297 * A request to provide selection ranges in a document. The request's
\r
5298 * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
\r
5299 * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
\r
5300 * that resolves to such.
\r
5302 var SelectionRangeRequest;
\r
5303 (function (SelectionRangeRequest) {
\r
5304 SelectionRangeRequest.method = 'textDocument/selectionRange';
\r
5305 SelectionRangeRequest.type = new messages_1.ProtocolRequestType(SelectionRangeRequest.method);
\r
5306 /** @deprecated Use SelectionRangeRequest.type */
\r
5307 SelectionRangeRequest.resultType = new vscode_jsonrpc_1.ProgressType();
\r
5308 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
\r
5313 /***/ (function(module, exports, __webpack_require__) {
5316 /* --------------------------------------------------------------------------------------------
\r
5317 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5318 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5319 * ------------------------------------------------------------------------------------------ */
\r
5321 Object.defineProperty(exports, "__esModule", { value: true });
\r
5322 const vscode_jsonrpc_1 = __webpack_require__(5);
\r
5323 const messages_1 = __webpack_require__(21);
\r
5324 var WorkDoneProgress;
\r
5325 (function (WorkDoneProgress) {
\r
5326 WorkDoneProgress.type = new vscode_jsonrpc_1.ProgressType();
\r
5327 })(WorkDoneProgress = exports.WorkDoneProgress || (exports.WorkDoneProgress = {}));
\r
5329 * The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress
\r
5330 * reporting from the server.
\r
5332 var WorkDoneProgressCreateRequest;
\r
5333 (function (WorkDoneProgressCreateRequest) {
\r
5334 WorkDoneProgressCreateRequest.type = new messages_1.ProtocolRequestType('window/workDoneProgress/create');
\r
5335 })(WorkDoneProgressCreateRequest = exports.WorkDoneProgressCreateRequest || (exports.WorkDoneProgressCreateRequest = {}));
\r
5337 * The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress
\r
5338 * initiated on the server side.
\r
5340 var WorkDoneProgressCancelNotification;
\r
5341 (function (WorkDoneProgressCancelNotification) {
\r
5342 WorkDoneProgressCancelNotification.type = new messages_1.ProtocolNotificationType('window/workDoneProgress/cancel');
\r
5343 })(WorkDoneProgressCancelNotification = exports.WorkDoneProgressCancelNotification || (exports.WorkDoneProgressCancelNotification = {}));
\r
5348 /***/ (function(module, exports, __webpack_require__) {
5351 /* --------------------------------------------------------------------------------------------
\r
5352 * Copyright (c) TypeFox and others. All rights reserved.
\r
5353 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5354 * ------------------------------------------------------------------------------------------ */
\r
5356 Object.defineProperty(exports, "__esModule", { value: true });
\r
5357 const messages_1 = __webpack_require__(21);
\r
5359 * A request to result a `CallHierarchyItem` in a document at a given position.
\r
5360 * Can be used as an input to a incoming or outgoing call hierarchy.
\r
5362 * @since 3.16.0 - Proposed state
\r
5364 var CallHierarchyPrepareRequest;
\r
5365 (function (CallHierarchyPrepareRequest) {
\r
5366 CallHierarchyPrepareRequest.method = 'textDocument/prepareCallHierarchy';
\r
5367 CallHierarchyPrepareRequest.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest.method);
\r
5368 })(CallHierarchyPrepareRequest = exports.CallHierarchyPrepareRequest || (exports.CallHierarchyPrepareRequest = {}));
\r
5370 * A request to resolve the incoming calls for a given `CallHierarchyItem`.
\r
5372 * @since 3.16.0 - Proposed state
\r
5374 var CallHierarchyIncomingCallsRequest;
\r
5375 (function (CallHierarchyIncomingCallsRequest) {
\r
5376 CallHierarchyIncomingCallsRequest.method = 'callHierarchy/incomingCalls';
\r
5377 CallHierarchyIncomingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest.method);
\r
5378 })(CallHierarchyIncomingCallsRequest = exports.CallHierarchyIncomingCallsRequest || (exports.CallHierarchyIncomingCallsRequest = {}));
\r
5380 * A request to resolve the outgoing calls for a given `CallHierarchyItem`.
\r
5382 * @since 3.16.0 - Proposed state
\r
5384 var CallHierarchyOutgoingCallsRequest;
\r
5385 (function (CallHierarchyOutgoingCallsRequest) {
\r
5386 CallHierarchyOutgoingCallsRequest.method = 'callHierarchy/outgoingCalls';
\r
5387 CallHierarchyOutgoingCallsRequest.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest.method);
\r
5388 })(CallHierarchyOutgoingCallsRequest = exports.CallHierarchyOutgoingCallsRequest || (exports.CallHierarchyOutgoingCallsRequest = {}));
\r
5393 /***/ (function(module, exports, __webpack_require__) {
5396 /* --------------------------------------------------------------------------------------------
\r
5397 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5398 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5399 * ------------------------------------------------------------------------------------------ */
\r
5401 Object.defineProperty(exports, "__esModule", { value: true });
\r
5402 const messages_1 = __webpack_require__(21);
\r
5404 * A set of predefined token types. This set is not fixed
\r
5405 * an clients can specify additional token types via the
\r
5406 * corresponding client capabilities.
\r
5408 * @since 3.16.0 - Proposed state
\r
5410 var SemanticTokenTypes;
\r
5411 (function (SemanticTokenTypes) {
\r
5412 SemanticTokenTypes["comment"] = "comment";
\r
5413 SemanticTokenTypes["keyword"] = "keyword";
\r
5414 SemanticTokenTypes["string"] = "string";
\r
5415 SemanticTokenTypes["number"] = "number";
\r
5416 SemanticTokenTypes["regexp"] = "regexp";
\r
5417 SemanticTokenTypes["operator"] = "operator";
\r
5418 SemanticTokenTypes["namespace"] = "namespace";
\r
5419 SemanticTokenTypes["type"] = "type";
\r
5420 SemanticTokenTypes["struct"] = "struct";
\r
5421 SemanticTokenTypes["class"] = "class";
\r
5422 SemanticTokenTypes["interface"] = "interface";
\r
5423 SemanticTokenTypes["enum"] = "enum";
\r
5424 SemanticTokenTypes["typeParameter"] = "typeParameter";
\r
5425 SemanticTokenTypes["function"] = "function";
\r
5426 SemanticTokenTypes["member"] = "member";
\r
5427 SemanticTokenTypes["property"] = "property";
\r
5428 SemanticTokenTypes["macro"] = "macro";
\r
5429 SemanticTokenTypes["variable"] = "variable";
\r
5430 SemanticTokenTypes["parameter"] = "parameter";
\r
5431 SemanticTokenTypes["label"] = "label";
\r
5432 })(SemanticTokenTypes = exports.SemanticTokenTypes || (exports.SemanticTokenTypes = {}));
\r
5434 * A set of predefined token modifiers. This set is not fixed
\r
5435 * an clients can specify additional token types via the
\r
5436 * corresponding client capabilities.
\r
5438 * @since 3.16.0 - Proposed state
\r
5440 var SemanticTokenModifiers;
\r
5441 (function (SemanticTokenModifiers) {
\r
5442 SemanticTokenModifiers["documentation"] = "documentation";
\r
5443 SemanticTokenModifiers["declaration"] = "declaration";
\r
5444 SemanticTokenModifiers["definition"] = "definition";
\r
5445 SemanticTokenModifiers["reference"] = "reference";
\r
5446 SemanticTokenModifiers["static"] = "static";
\r
5447 SemanticTokenModifiers["abstract"] = "abstract";
\r
5448 SemanticTokenModifiers["deprecated"] = "deprecated";
\r
5449 SemanticTokenModifiers["async"] = "async";
\r
5450 SemanticTokenModifiers["volatile"] = "volatile";
\r
5451 SemanticTokenModifiers["readonly"] = "readonly";
\r
5452 })(SemanticTokenModifiers = exports.SemanticTokenModifiers || (exports.SemanticTokenModifiers = {}));
\r
5454 * @since 3.16.0 - Proposed state
\r
5456 var SemanticTokens;
\r
5457 (function (SemanticTokens) {
\r
5458 function is(value) {
\r
5459 const candidate = value;
\r
5460 return candidate !== undefined && (candidate.resultId === undefined || typeof candidate.resultId === 'string') &&
\r
5461 Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === 'number');
\r
5463 SemanticTokens.is = is;
\r
5464 })(SemanticTokens = exports.SemanticTokens || (exports.SemanticTokens = {}));
\r
5466 * @since 3.16.0 - Proposed state
\r
5468 var SemanticTokensRequest;
\r
5469 (function (SemanticTokensRequest) {
\r
5470 SemanticTokensRequest.method = 'textDocument/semanticTokens';
\r
5471 SemanticTokensRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRequest.method);
\r
5472 })(SemanticTokensRequest = exports.SemanticTokensRequest || (exports.SemanticTokensRequest = {}));
\r
5474 * @since 3.16.0 - Proposed state
\r
5476 var SemanticTokensEditsRequest;
\r
5477 (function (SemanticTokensEditsRequest) {
\r
5478 SemanticTokensEditsRequest.method = 'textDocument/semanticTokens/edits';
\r
5479 SemanticTokensEditsRequest.type = new messages_1.ProtocolRequestType(SemanticTokensEditsRequest.method);
\r
5480 })(SemanticTokensEditsRequest = exports.SemanticTokensEditsRequest || (exports.SemanticTokensEditsRequest = {}));
\r
5482 * @since 3.16.0 - Proposed state
\r
5484 var SemanticTokensRangeRequest;
\r
5485 (function (SemanticTokensRangeRequest) {
\r
5486 SemanticTokensRangeRequest.method = 'textDocument/semanticTokens/range';
\r
5487 SemanticTokensRangeRequest.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest.method);
\r
5488 })(SemanticTokensRangeRequest = exports.SemanticTokensRangeRequest || (exports.SemanticTokensRangeRequest = {}));
\r
5493 /***/ (function(module, exports, __webpack_require__) {
5497 Object.defineProperty(exports, "__esModule", { value: true });
5498 exports.Ctx = void 0;
5499 const coc_nvim_1 = __webpack_require__(1);
5500 const config_1 = __webpack_require__(34);
5501 const semantic_highlighting_1 = __webpack_require__(35);
5502 class ClangdExtensionFeature {
5505 fillClientCapabilities(capabilities) {
5507 const textDocument = capabilities.textDocument;
5508 // @ts-ignore: clangd extension
5509 (_a = textDocument.completion) === null || _a === void 0 ? void 0 : _a.editsNearCursor = true;
5513 constructor(context) {
5514 this.context = context;
5516 this.config = new config_1.Config();
5518 async startServer(bin) {
5519 const old = this.client;
5525 args: this.config.arguments,
5527 const serverOptions = exec;
5528 const outputChannel = coc_nvim_1.workspace.createOutputChannel('clangd log');
5529 const clientOptions = {
5531 { scheme: 'file', language: 'c' },
5532 { scheme: 'file', language: 'cpp' },
5533 { scheme: 'file', language: 'objc' },
5534 { scheme: 'file', language: 'objcpp' },
5535 { scheme: 'file', language: 'objective-c' },
5536 { scheme: 'file', language: 'objective-cpp' },
5537 { scheme: 'file', language: 'cuda' },
5538 { scheme: 'file', language: 'arduino' },
5540 initializationOptions: { clangdFileStatus: true, fallbackFlags: this.config.fallbackFlags },
5541 disableDiagnostics: this.config.disableDiagnostics,
5543 disableSnippetCompletion: this.config.disableSnippetCompletion,
5546 provideOnTypeFormattingEdits: (document, position, ch, options, token, next) => {
5547 // coc sends "\n" when exiting insert mode, when there is no newline added to the doc.
5550 return next(document, position, ch, options, token);
5552 provideWorkspaceSymbols: async (query, token, next) => {
5553 const symbols = await next(query, token);
5556 return symbols.map((symbol) => {
5557 if (symbol.containerName) {
5558 symbol.name = `${symbol.containerName}::${symbol.name}`;
5560 symbol.containerName = '';
5566 const client = new coc_nvim_1.LanguageClient('clangd', serverOptions, clientOptions);
5567 client.registerFeature(new ClangdExtensionFeature());
5568 if (this.config.semanticHighlighting) {
5569 const lspCxx = await coc_nvim_1.workspace.nvim.call('exists', 'g:lsp_cxx_hl_loaded');
5571 client.registerFeature(new semantic_highlighting_1.SemanticHighlightingFeature(client, this.context));
5574 this.context.subscriptions.push(coc_nvim_1.services.registLanguageClient(client));
5575 await client.onReady();
5576 this.client = client;
5578 get subscriptions() {
5579 return this.context.subscriptions;
5587 /***/ (function(module, exports, __webpack_require__) {
5591 Object.defineProperty(exports, "__esModule", { value: true });
5592 exports.Config = void 0;
5593 const coc_nvim_1 = __webpack_require__(1);
5596 this.cfg = coc_nvim_1.workspace.getConfiguration('clangd');
5599 return this.cfg.get('enabled');
5601 get disableDiagnostics() {
5602 return this.cfg.get('disableDiagnostics');
5604 get disableSnippetCompletion() {
5605 return this.cfg.get('disableSnippetCompletion');
5608 return this.cfg.get('arguments', []);
5610 get fallbackFlags() {
5611 return this.cfg.get('fallbackFlags', []);
5613 get semanticHighlighting() {
5614 return this.cfg.get('semanticHighlighting');
5616 get showDBChangedNotification() {
5617 return this.cfg.get('showDBChangedNotification');
5620 exports.Config = Config;
5625 /***/ (function(module, exports, __webpack_require__) {
5629 Object.defineProperty(exports, "__esModule", { value: true });
5630 exports.SemanticHighlightingFeature = void 0;
5631 const coc_nvim_1 = __webpack_require__(1);
5632 const vscode_languageserver_protocol_1 = __webpack_require__(4);
5633 class SemanticHighlightingFeature {
5634 constructor(client, context) {
5635 this.scopeTable = [];
5636 // Last tokens seen: bufTokens[bufnr][linenr] = [tokens...]
5637 this.bufTokens = {};
5638 context.subscriptions.push(client.onDidChangeState(({ newState }) => {
5639 if (newState === coc_nvim_1.State.Running) {
5640 const notification = new vscode_languageserver_protocol_1.NotificationType('textDocument/semanticHighlighting');
5641 client.onNotification(notification, this.handleNotification.bind(this));
5645 initialize(capabilities) {
5646 const serverCapabilities = capabilities;
5647 if (!serverCapabilities.semanticHighlighting)
5649 this.scopeTable = serverCapabilities.semanticHighlighting.scopes;
5651 fillClientCapabilities(capabilities) {
5652 const textDocumentCapabilities = capabilities.textDocument;
5653 textDocumentCapabilities.semanticHighlightingCapabilities = {
5654 semanticHighlighting: true,
5657 async handleNotification(params) {
5658 // use https://github.com/jackguo380/vim-lsp-cxx-highlight to do highlighting
5659 // first, assemble the full list of tokens.
5660 const doc = coc_nvim_1.workspace.getDocument(params.textDocument.uri);
5661 // Create implicit previous state if it doesn't exist.
5662 if (!(doc.bufnr in this.bufTokens))
5663 this.bufTokens[doc.bufnr] = [];
5664 const lines = this.bufTokens[doc.bufnr];
5665 // Update changed lines in place.
5666 for (const line of params.lines) {
5667 while (line.line >= lines.length)
5669 lines[line.line] = this.decodeTokens(line.tokens);
5673 for (const [line, tokens] of lines.entries()) {
5674 for (const token of tokens) {
5675 if (token.kind === 'InactiveCode') {
5676 skipped.push(vscode_languageserver_protocol_1.Range.create(line, token.character, line, token.character + token.length));
5682 ranges: [vscode_languageserver_protocol_1.Range.create(line, token.character, line, token.character + token.length)],
5683 parentKind: 'Unknown',
5689 await coc_nvim_1.workspace.nvim.call('lsp_cxx_hl#hl#notify_symbols', [doc.bufnr, symbols]);
5690 if (skipped.length) {
5691 await coc_nvim_1.workspace.nvim.call('lsp_cxx_hl#hl#notify_skipped', [doc.bufnr, skipped]);
5694 // Converts a string of base64 encoded tokens into the corresponding array of SemanticHighlightingToken.
5695 decodeTokens(tokens) {
5696 const scopeMask = 0xffff;
5697 const lenShift = 0x10;
5698 const uint32Size = 4;
5699 const buf = Buffer.from(tokens, 'base64');
5700 const retTokens = [];
5701 for (let i = 0, end = buf.length / uint32Size; i < end; i += 2) {
5702 const start = buf.readUInt32BE(i * uint32Size);
5703 const lenKind = buf.readUInt32BE((i + 1) * uint32Size);
5704 const scopeIndex = lenKind & scopeMask;
5705 const len = lenKind >>> lenShift;
5706 const kind = this.scopeTable[scopeIndex][0];
5707 retTokens.push({ character: start, scopeIndex: scopeIndex, length: len, kind: this.decodeKind(kind) });
5712 // https://github.com/llvm/llvm-project/blob/9adc7fc3cdf571bd70d5f8bda4e2e9c233c5fd63/clang-tools-extra/clangd/SemanticHighlighting.cpp#L477
5714 case 'entity.name.function.cpp':
5716 case 'entity.name.function.method.cpp':
5718 case 'entity.name.function.method.static.cpp':
5719 return 'StaticMethod';
5720 case 'variable.other.cpp':
5722 case 'variable.other.local.cpp':
5723 return 'LocalVariable';
5724 case 'variable.parameter.cpp':
5726 case 'variable.other.field.cpp':
5728 case 'variable.other.field.static.cpp':
5729 return 'StaticField';
5730 case 'entity.name.type.class.cpp':
5732 case 'entity.name.type.enum.cpp':
5734 case 'variable.other.enummember.cpp':
5735 return 'EnumConstant';
5736 case 'entity.name.type.typedef.cpp':
5738 case 'entity.name.type.dependent.cpp':
5739 return 'DependentType';
5740 case 'entity.name.other.dependent.cpp':
5741 return 'DependentName';
5742 case 'entity.name.namespace.cpp':
5744 case 'entity.name.type.template.cpp':
5745 return 'TemplateParameter';
5746 case 'entity.name.type.concept.cpp':
5748 case 'storage.type.primitive.cpp':
5750 case 'entity.name.function.preprocessor.cpp':
5752 case 'meta.disabled':
5753 return 'InactiveCode';
5759 exports.SemanticHighlightingFeature = SemanticHighlightingFeature;
5764 /***/ (function(module, exports, __webpack_require__) {
5768 Object.defineProperty(exports, "__esModule", { value: true });
5769 exports.FileStatus = void 0;
5770 const coc_nvim_1 = __webpack_require__(1);
5773 this.statuses = new Map();
5774 this.statusBarItem = coc_nvim_1.workspace.createStatusBarItem(0);
5776 onFileUpdated(status) {
5777 this.statuses.set(status.uri, status);
5778 this.updateStatus();
5780 async updateStatus() {
5781 const doc = await coc_nvim_1.workspace.document;
5785 const status = this.statuses.get(doc.uri);
5787 this.statusBarItem.hide();
5790 this.statusBarItem.text = `clangd: ` + status.state;
5791 this.statusBarItem.show();
5794 this.statuses.clear();
5795 this.statusBarItem.hide();
5798 this.statusBarItem.dispose();
5801 exports.FileStatus = FileStatus;
5806 /***/ (function(module, exports, __webpack_require__) {
5810 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5811 if (k2 === undefined) k2 = k;
5812 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5813 }) : (function(o, m, k, k2) {
5814 if (k2 === undefined) k2 = k;
5817 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
5818 Object.defineProperty(o, "default", { enumerable: true, value: v });
5819 }) : function(o, v) {
5822 var __importStar = (this && this.__importStar) || function (mod) {
5823 if (mod && mod.__esModule) return mod;
5825 if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
5826 __setModuleDefault(result, mod);
5829 Object.defineProperty(exports, "__esModule", { value: true });
5830 exports.activate = void 0;
5831 const coc = __importStar(__webpack_require__(1));
5832 const common = __importStar(__webpack_require__(38));
5834 constructor(context, config) {
5835 this.context = context;
5836 this.config = config;
5839 return this.context.storagePath;
5841 slow(title, result) {
5842 coc.workspace.showMessage(title + '...');
5846 coc.workspace.showMessage(s, 'error');
5849 coc.workspace.showMessage(s);
5851 progress(title, _cancel, body) {
5852 return this.slow(title, body(() => { }));
5854 async shouldReuse(release) {
5855 coc.workspace.showMessage(`Reusing existing ${release} installation in ${this.storagePath}`);
5858 async promptReload() {
5859 await coc.commands.executeCommand('editor.action.restart');
5861 showHelp(message, url) {
5862 message += ` See ${url}.`;
5863 coc.workspace.showMessage(message);
5865 async promptUpdate(oldVersion, newVersion) {
5866 const message = `clangd ${newVersion} is available (you have ${oldVersion}). :CocCommand clangd.install, or :CocSettings to disable clangd.checkUpdates.`;
5867 coc.workspace.showMessage(message);
5869 async promptInstall(version) {
5870 const message = `clangd was not found on your PATH. :CocCommand clangd.install will install ${version}.`;
5871 coc.workspace.showMessage(message);
5874 return this.config.get('path');
5877 this.config.update('path', p, /*isUser=*/ true);
5880 // Returns the clangd path to use, or null if clangd is not installed.
5881 async function activate(context) {
5882 const cfg = coc.workspace.getConfiguration('clangd');
5883 const ui = new UI(context, cfg);
5884 context.subscriptions.push(coc.commands.registerCommand('clangd.install', async () => common.installLatest(ui)));
5885 context.subscriptions.push(coc.commands.registerCommand('clangd.update', async () => common.checkUpdates(true, ui)));
5886 const status = await common.prepare(ui, cfg.get('checkUpdates', false));
5887 return status.clangdPath;
5889 exports.activate = activate;
5894 /***/ (function(module, exports, __webpack_require__) {
5898 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
5899 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5900 return new (P || (P = Promise))(function (resolve, reject) {
5901 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5902 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5903 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
5904 step((generator = generator.apply(thisArg, _arguments || [])).next());
5907 var __asyncValues = (this && this.__asyncValues) || function (o) {
5908 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
5909 var m = o[Symbol.asyncIterator], i;
5910 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
5911 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
5912 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
5914 Object.defineProperty(exports, "__esModule", { value: true });
5915 // Automatically install clangd binary releases from GitHub.
5917 // We don't bundle them with the package because they're big; we'd have to
5918 // include all OS versions, and download them again with every extension update.
5920 // There are several entry points:
5921 // - installation explicitly requested
5922 // - checking for updates (manual or automatic)
5923 // - no usable clangd found, try to recover
5924 // These have different flows, but the same underlying mechanisms.
5925 const abort_controller_1 = __webpack_require__(39);
5926 const child_process = __webpack_require__(41);
5927 const fs = __webpack_require__(42);
5928 const node_fetch_1 = __webpack_require__(43);
5929 const os = __webpack_require__(14);
5930 const path = __webpack_require__(2);
5931 const readdirp = __webpack_require__(49);
5932 const rimraf = __webpack_require__(57);
5933 const semver = __webpack_require__(75);
5934 const stream = __webpack_require__(44);
5935 const unzipper = __webpack_require__(118);
5936 const util_1 = __webpack_require__(50);
5937 const which = __webpack_require__(221);
5938 // Main startup workflow: check whether the configured clangd binary us usable.
5939 // If not, offer to install one. If so, check for updates.
5940 function prepare(ui, checkUpdate) {
5941 return __awaiter(this, void 0, void 0, function* () {
5943 var absPath = yield util_1.promisify(which)(ui.clangdPath);
5946 // Couldn't find clangd - start recovery flow and stop extension
5948 return { clangdPath: null, background: recover(ui) };
5950 // Allow extension to load, asynchronously check for updates.
5952 clangdPath: absPath,
5953 background: checkUpdate ? checkUpdates(/*requested=*/ false, ui)
5958 exports.prepare = prepare;
5959 // The user has explicitly asked to install the latest clangd.
5960 // Do so without further prompting, or report an error.
5961 function installLatest(ui) {
5962 return __awaiter(this, void 0, void 0, function* () {
5963 const abort = new abort_controller_1.AbortController();
5965 const release = yield Github.latestRelease();
5966 const asset = yield Github.chooseAsset(release);
5967 ui.clangdPath = yield Install.install(release, asset, abort, ui);
5968 ui.promptReload(`clangd ${release.name} is now installed.`);
5971 if (!abort.signal.aborted) {
5972 console.error('Failed to install clangd: ', e);
5973 const message = `Failed to install clangd language server: ${e}\n` +
5974 'You may want to install it manually.';
5975 ui.showHelp(message, installURL);
5980 exports.installLatest = installLatest;
5981 // We have an apparently-valid clangd (`clangdPath`), check for updates.
5982 function checkUpdates(requested, ui) {
5983 return __awaiter(this, void 0, void 0, function* () {
5984 // Gather all the version information to see if there's an upgrade.
5986 var release = yield Github.latestRelease();
5987 yield Github.chooseAsset(release); // Ensure a binary for this platform.
5988 var upgrade = yield Version.upgrade(release, ui.clangdPath);
5991 console.log('Failed to check for clangd update: ', e);
5992 // We're not sure whether there's an upgrade: stay quiet unless asked.
5994 ui.error(`Failed to check for clangd update: ${e}`);
5997 console.log('Checking for clangd update: available=', upgrade.new, ' installed=', upgrade.old);
5998 // Bail out if the new version is better or comparable.
5999 if (!upgrade.upgrade) {
6001 ui.info(`clangd is up-to-date (you have ${upgrade.old}, latest is ${upgrade.new})`);
6004 ui.promptUpdate(upgrade.old, upgrade.new);
6007 exports.checkUpdates = checkUpdates;
6008 // The extension has detected clangd isn't available.
6009 // Inform the user, and if possible offer to install or adjust the path.
6010 // Unlike installLatest(), we've had no explicit user request or consent yet.
6011 function recover(ui) {
6012 return __awaiter(this, void 0, void 0, function* () {
6014 const release = yield Github.latestRelease();
6015 yield Github.chooseAsset(release); // Ensure a binary for this platform.
6016 ui.promptInstall(release.name);
6019 console.error('Auto-install failed: ', e);
6020 ui.showHelp('The clangd language server is not installed.', installURL);
6024 const installURL = 'https://clangd.llvm.org/installation.html';
6025 // The GitHub API endpoint for the latest binary clangd release.
6026 let githubReleaseURL = 'https://api.github.com/repos/clangd/clangd/releases/latest';
6027 // Set a fake URL for testing.
6028 function fakeGitHubReleaseURL(u) { githubReleaseURL = u; }
6029 exports.fakeGitHubReleaseURL = fakeGitHubReleaseURL;
6030 let lddCommand = 'ldd';
6031 function fakeLddCommand(l) { lddCommand = l; }
6032 exports.fakeLddCommand = fakeLddCommand;
6033 // Bits for talking to github's release API
6035 (function (Github) {
6036 // Fetch the metadata for the latest stable clangd release.
6037 function latestRelease() {
6038 return __awaiter(this, void 0, void 0, function* () {
6039 const response = yield node_fetch_1.default(githubReleaseURL);
6041 console.log(response.url, response.status, response.statusText);
6042 throw new Error(`Can't fetch release: ${response.statusText}`);
6044 return yield response.json();
6047 Github.latestRelease = latestRelease;
6048 // Determine which release asset should be installed for this machine.
6049 function chooseAsset(release) {
6050 return __awaiter(this, void 0, void 0, function* () {
6056 const variant = variants[os.platform()];
6057 if (variant == 'linux') {
6058 // Hardcoding this here is sad, but we'd like to offer a nice error message
6059 // without making the user download the package first.
6060 const minGlibc = new semver.Range('2.18');
6061 const oldGlibc = yield Version.oldGlibc(minGlibc);
6063 throw new Error('The clangd release is not compatible with your system ' +
6064 `(glibc ${oldGlibc.raw} < ${minGlibc.raw}). ` +
6065 'Try to install it using your package manager instead.');
6068 // 32-bit vscode is still common on 64-bit windows, so don't reject that.
6069 if (variant && (os.arch() == 'x64' || variant == 'windows')) {
6070 const asset = release.assets.find(a => a.name.indexOf(variant) >= 0);
6074 throw new Error(`No clangd ${release.name} binary available for ${os.platform()}/${os.arch()}`);
6077 Github.chooseAsset = chooseAsset;
6078 })(Github || (Github = {}));
6079 // Functions to download and install the releases, and manage the files on disk.
6082 // <ui.storagePath>/
6085 // clangd_<version>/ (outer director from zip file)
6089 // clangd-platform-<version>.zip (deleted after extraction)
6091 (function (Install) {
6092 // Download the binary archive `asset` from a github `release` and extract it
6093 // to the extension's global storage location.
6094 // The `abort` controller is signaled if the user cancels the installation.
6095 // Returns the absolute path to the installed clangd executable.
6096 function install(release, asset, abort, ui) {
6097 return __awaiter(this, void 0, void 0, function* () {
6098 const dirs = yield createDirs(ui);
6099 const extractRoot = path.join(dirs.install, release.tag_name);
6100 if (yield util_1.promisify(fs.exists)(extractRoot)) {
6101 const reuse = yield ui.shouldReuse(release.name);
6102 if (reuse === undefined) {
6103 // User dismissed prompt, bail out.
6105 throw new Error(`clangd ${release.name} already installed!`);
6108 // Find clangd within the existing directory.
6109 let files = (yield readdirp.promise(extractRoot)).map(e => e.fullPath);
6110 return findExecutable(files);
6113 // Delete the old version.
6114 yield util_1.promisify(rimraf)(extractRoot);
6115 // continue with installation.
6118 const zipFile = path.join(dirs.download, asset.name);
6119 yield download(asset.browser_download_url, zipFile, abort, ui);
6120 const archive = yield unzipper.Open.file(zipFile);
6121 const executable = findExecutable(archive.files.map(f => f.path));
6122 yield ui.slow(`Extracting ${asset.name}`, archive.extract({ path: extractRoot }));
6123 const clangdPath = path.join(extractRoot, executable);
6124 yield fs.promises.chmod(clangdPath, 0o755);
6125 yield fs.promises.unlink(zipFile);
6129 Install.install = install;
6130 // Create the 'install' and 'download' directories, and return absolute paths.
6131 function createDirs(ui) {
6132 return __awaiter(this, void 0, void 0, function* () {
6133 const install = path.join(ui.storagePath, 'install');
6134 const download = path.join(ui.storagePath, 'download');
6135 for (const dir of [install, download])
6136 yield fs.promises.mkdir(dir, { 'recursive': true });
6137 return { install: install, download: download };
6140 // Find the clangd executable within a set of files.
6141 function findExecutable(paths) {
6142 const filename = os.platform() == 'win32' ? 'clangd.exe' : 'clangd';
6143 const entry = paths.find(f => path.posix.basename(f) == filename ||
6144 path.win32.basename(f) == filename);
6146 throw new Error('Didn\'t find a clangd executable!');
6149 // Downloads `url` to a local file `dest` (whose parent should exist).
6150 // A progress dialog is shown, if it is cancelled then `abort` is signaled.
6151 function download(url, dest, abort, ui) {
6152 return __awaiter(this, void 0, void 0, function* () {
6153 console.log('Downloading ', url, ' to ', dest);
6154 return ui.progress(`Downloading ${path.basename(dest)}`, abort, (progress) => __awaiter(this, void 0, void 0, function* () {
6155 const response = yield node_fetch_1.default(url, { signal: abort.signal });
6157 throw new Error(`Failed to download $url`);
6158 const size = Number(response.headers.get('content-length'));
6160 response.body.on('data', (chunk) => {
6161 read += chunk.length;
6162 progress(read / size);
6164 const out = fs.createWriteStream(dest);
6165 yield util_1.promisify(stream.pipeline)(response.body, out).catch(e => {
6166 // Clean up the partial file if the download failed.
6167 fs.unlink(dest, (_) => null); // Don't wait, and ignore error.
6173 })(Install || (Install = {}));
6174 // Functions dealing with clangd versions.
6176 // We parse both github release numbers and installed `clangd --version` output
6177 // by treating them as SemVer ranges, and offer an upgrade if the version
6178 // is unambiguously newer.
6180 // These functions throw if versions can't be parsed (e.g. installed clangd
6181 // is a vendor-modified version).
6183 (function (Version) {
6184 function upgrade(release, clangdPath) {
6185 return __awaiter(this, void 0, void 0, function* () {
6186 const releasedVer = released(release);
6187 const installedVer = yield installed(clangdPath);
6189 old: installedVer.raw,
6190 new: releasedVer.raw,
6191 upgrade: rangeGreater(releasedVer, installedVer)
6195 Version.upgrade = upgrade;
6199 // Get the version of an installed clangd binary using `clangd --version`.
6200 function installed(clangdPath) {
6201 return __awaiter(this, void 0, void 0, function* () {
6202 const output = yield run(clangdPath, ['--version']);
6203 console.log(clangdPath, ' --version output: ', output);
6204 const prefix = 'clangd version ';
6205 if (!output.startsWith(prefix))
6206 throw new Error(`Couldn't parse clangd --version output: ${output}`);
6207 const rawVersion = output.substr(prefix.length).split(' ', 1)[0];
6208 return new semver.Range(rawVersion, loose);
6211 // Get the version of a github release, by parsing the tag or name.
6212 function released(release) {
6213 // Prefer the tag name, but fall back to the release name.
6214 return (!semver.validRange(release.tag_name, loose) &&
6215 semver.validRange(release.name, loose))
6216 ? new semver.Range(release.name, loose)
6217 : new semver.Range(release.tag_name, loose);
6219 // Detect the (linux) system's glibc version. If older than `min`, return it.
6220 function oldGlibc(min) {
6221 return __awaiter(this, void 0, void 0, function* () {
6222 // ldd is distributed with glibc, so ldd --version should be a good proxy.
6223 const output = yield run(lddCommand, ['--version']);
6224 // The first line is e.g. "ldd (Debian GLIBC 2.29-9) 2.29".
6225 const line = output.split('\n', 1)[0];
6226 // Require some confirmation this is [e]glibc, and a plausible
6228 const match = line.match(/^ldd .*glibc.* (\d+(?:\.\d+)+)[^ ]*$/i);
6229 if (!match || !semver.validRange(match[1], loose)) {
6230 console.error(`Can't glibc version from ldd --version output: ${line}`);
6233 const version = new semver.Range(match[1], loose);
6234 console.log('glibc is', version.raw, 'min is', min.raw);
6235 return rangeGreater(min, version) ? version : null;
6238 Version.oldGlibc = oldGlibc;
6239 // Run a system command and capture any stdout produced.
6240 function run(command, flags) {
6242 return __awaiter(this, void 0, void 0, function* () {
6243 const child = child_process.spawn(command, flags, { stdio: ['ignore', 'pipe', 'ignore'] });
6246 for (var _b = __asyncValues(child.stdout), _c; _c = yield _b.next(), !_c.done;) {
6247 const chunk = _c.value;
6251 catch (e_1_1) { e_1 = { error: e_1_1 }; }
6254 if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
6256 finally { if (e_1) throw e_1.error; }
6261 function rangeGreater(newVer, oldVer) {
6262 return semver.gtr(semver.minVersion(newVer), oldVer);
6264 })(Version || (Version = {}));
6265 //# sourceMappingURL=index.js.map
6269 /***/ (function(module, exports, __webpack_require__) {
6273 * @author Toru Nagashima <https://github.com/mysticatea>
6274 * See LICENSE file in root directory for full license.
6278 Object.defineProperty(exports, '__esModule', { value: true });
6280 var eventTargetShim = __webpack_require__(40);
6284 * @see https://dom.spec.whatwg.org/#abortsignal
6286 class AbortSignal extends eventTargetShim.EventTarget {
6288 * AbortSignal cannot be constructed directly.
6292 throw new TypeError("AbortSignal cannot be constructed directly");
6295 * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
6298 const aborted = abortedFlags.get(this);
6299 if (typeof aborted !== "boolean") {
6300 throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
6305 eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort");
6307 * Create an AbortSignal object.
6309 function createAbortSignal() {
6310 const signal = Object.create(AbortSignal.prototype);
6311 eventTargetShim.EventTarget.call(signal);
6312 abortedFlags.set(signal, false);
6316 * Abort a given signal.
6318 function abortSignal(signal) {
6319 if (abortedFlags.get(signal) !== false) {
6322 abortedFlags.set(signal, true);
6323 signal.dispatchEvent({ type: "abort" });
6326 * Aborted flag for each instances.
6328 const abortedFlags = new WeakMap();
6329 // Properties should be enumerable.
6330 Object.defineProperties(AbortSignal.prototype, {
6331 aborted: { enumerable: true },
6333 // `toString()` should return `"[object AbortSignal]"`
6334 if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
6335 Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
6337 value: "AbortSignal",
6342 * The AbortController.
6343 * @see https://dom.spec.whatwg.org/#abortcontroller
6345 class AbortController {
6347 * Initialize this controller.
6350 signals.set(this, createAbortSignal());
6353 * Returns the `AbortSignal` object associated with this object.
6356 return getSignal(this);
6359 * Abort and signal to any observers that the associated activity is to be aborted.
6362 abortSignal(getSignal(this));
6366 * Associated signals.
6368 const signals = new WeakMap();
6370 * Get the associated signal of a given controller.
6372 function getSignal(controller) {
6373 const signal = signals.get(controller);
6374 if (signal == null) {
6375 throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
6379 // Properties should be enumerable.
6380 Object.defineProperties(AbortController.prototype, {
6381 signal: { enumerable: true },
6382 abort: { enumerable: true },
6384 if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
6385 Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
6387 value: "AbortController",
6391 exports.AbortController = AbortController;
6392 exports.AbortSignal = AbortSignal;
6393 exports.default = AbortController;
6395 module.exports = AbortController
6396 module.exports.AbortController = module.exports["default"] = AbortController
6397 module.exports.AbortSignal = AbortSignal
6398 //# sourceMappingURL=abort-controller.js.map
6403 /***/ (function(module, exports, __webpack_require__) {
6407 * @author Toru Nagashima <https://github.com/mysticatea>
6408 * @copyright 2015 Toru Nagashima. All rights reserved.
6409 * See LICENSE file in root directory for full license.
6413 Object.defineProperty(exports, '__esModule', { value: true });
6416 * @typedef {object} PrivateData
6417 * @property {EventTarget} eventTarget The event target.
6418 * @property {{type:string}} event The original event object.
6419 * @property {number} eventPhase The current event phase.
6420 * @property {EventTarget|null} currentTarget The current event target.
6421 * @property {boolean} canceled The flag to prevent default.
6422 * @property {boolean} stopped The flag to stop propagation.
6423 * @property {boolean} immediateStopped The flag to stop propagation immediately.
6424 * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
6425 * @property {number} timeStamp The unix time.
6430 * Private data for event wrappers.
6431 * @type {WeakMap<Event, PrivateData>}
6434 const privateData = new WeakMap();
6437 * Cache for wrapper classes.
6438 * @type {WeakMap<Object, Function>}
6441 const wrappers = new WeakMap();
6445 * @param {Event} event The event object to get private data.
6446 * @returns {PrivateData} The private data of the event.
6449 function pd(event) {
6450 const retv = privateData.get(event);
6453 "'this' is expected an Event object, but got",
6460 * https://dom.spec.whatwg.org/#set-the-canceled-flag
6461 * @param data {PrivateData} private data.
6463 function setCancelFlag(data) {
6464 if (data.passiveListener != null) {
6466 typeof console !== "undefined" &&
6467 typeof console.error === "function"
6470 "Unable to preventDefault inside passive event listener invocation.",
6471 data.passiveListener
6476 if (!data.event.cancelable) {
6480 data.canceled = true;
6481 if (typeof data.event.preventDefault === "function") {
6482 data.event.preventDefault();
6487 * @see https://dom.spec.whatwg.org/#interface-event
6491 * The event wrapper.
6493 * @param {EventTarget} eventTarget The event target of this dispatching.
6494 * @param {Event|{type:string}} event The original event to wrap.
6496 function Event(eventTarget, event) {
6497 privateData.set(this, {
6501 currentTarget: eventTarget,
6504 immediateStopped: false,
6505 passiveListener: null,
6506 timeStamp: event.timeStamp || Date.now(),
6509 // https://heycam.github.io/webidl/#Unforgeable
6510 Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
6513 const keys = Object.keys(event);
6514 for (let i = 0; i < keys.length; ++i) {
6515 const key = keys[i];
6516 if (!(key in this)) {
6517 Object.defineProperty(this, key, defineRedirectDescriptor(key));
6522 // Should be enumerable, but class methods are not enumerable.
6525 * The type of this event.
6529 return pd(this).event.type
6533 * The target of this event.
6534 * @type {EventTarget}
6537 return pd(this).eventTarget
6541 * The target of this event.
6542 * @type {EventTarget}
6544 get currentTarget() {
6545 return pd(this).currentTarget
6549 * @returns {EventTarget[]} The composed path of this event.
6552 const currentTarget = pd(this).currentTarget;
6553 if (currentTarget == null) {
6556 return [currentTarget]
6568 * Constant of CAPTURING_PHASE.
6571 get CAPTURING_PHASE() {
6576 * Constant of AT_TARGET.
6584 * Constant of BUBBLING_PHASE.
6587 get BUBBLING_PHASE() {
6592 * The target of this event.
6596 return pd(this).eventPhase
6600 * Stop event bubbling.
6604 const data = pd(this);
6606 data.stopped = true;
6607 if (typeof data.event.stopPropagation === "function") {
6608 data.event.stopPropagation();
6613 * Stop event bubbling.
6616 stopImmediatePropagation() {
6617 const data = pd(this);
6619 data.stopped = true;
6620 data.immediateStopped = true;
6621 if (typeof data.event.stopImmediatePropagation === "function") {
6622 data.event.stopImmediatePropagation();
6627 * The flag to be bubbling.
6631 return Boolean(pd(this).event.bubbles)
6635 * The flag to be cancelable.
6639 return Boolean(pd(this).event.cancelable)
6643 * Cancel this event.
6647 setCancelFlag(pd(this));
6651 * The flag to indicate cancellation state.
6654 get defaultPrevented() {
6655 return pd(this).canceled
6659 * The flag to be composed.
6663 return Boolean(pd(this).event.composed)
6667 * The unix time of this event.
6671 return pd(this).timeStamp
6675 * The target of this event.
6676 * @type {EventTarget}
6680 return pd(this).eventTarget
6684 * The flag to stop event bubbling.
6688 get cancelBubble() {
6689 return pd(this).stopped
6691 set cancelBubble(value) {
6695 const data = pd(this);
6697 data.stopped = true;
6698 if (typeof data.event.cancelBubble === "boolean") {
6699 data.event.cancelBubble = true;
6704 * The flag to indicate cancellation state.
6709 return !pd(this).canceled
6711 set returnValue(value) {
6713 setCancelFlag(pd(this));
6718 * Initialize this event object. But do nothing under event dispatching.
6719 * @param {string} type The event type.
6720 * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
6721 * @param {boolean} [cancelable=false] The flag to be possible to cancel.
6729 // `constructor` is not enumerable.
6730 Object.defineProperty(Event.prototype, "constructor", {
6736 // Ensure `event instanceof window.Event` is `true`.
6737 if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
6738 Object.setPrototypeOf(Event.prototype, window.Event.prototype);
6740 // Make association for wrappers.
6741 wrappers.set(window.Event.prototype, Event);
6745 * Get the property descriptor to redirect a given property.
6746 * @param {string} key Property name to define property descriptor.
6747 * @returns {PropertyDescriptor} The property descriptor to redirect the property.
6750 function defineRedirectDescriptor(key) {
6753 return pd(this).event[key]
6756 pd(this).event[key] = value;
6764 * Get the property descriptor to call a given method property.
6765 * @param {string} key Property name to define property descriptor.
6766 * @returns {PropertyDescriptor} The property descriptor to call the method property.
6769 function defineCallDescriptor(key) {
6772 const event = pd(this).event;
6773 return event[key].apply(event, arguments)
6781 * Define new wrapper class.
6782 * @param {Function} BaseEvent The base wrapper class.
6783 * @param {Object} proto The prototype of the original event.
6784 * @returns {Function} The defined wrapper class.
6787 function defineWrapper(BaseEvent, proto) {
6788 const keys = Object.keys(proto);
6789 if (keys.length === 0) {
6794 function CustomEvent(eventTarget, event) {
6795 BaseEvent.call(this, eventTarget, event);
6798 CustomEvent.prototype = Object.create(BaseEvent.prototype, {
6799 constructor: { value: CustomEvent, configurable: true, writable: true },
6802 // Define accessors.
6803 for (let i = 0; i < keys.length; ++i) {
6804 const key = keys[i];
6805 if (!(key in BaseEvent.prototype)) {
6806 const descriptor = Object.getOwnPropertyDescriptor(proto, key);
6807 const isFunc = typeof descriptor.value === "function";
6808 Object.defineProperty(
6809 CustomEvent.prototype,
6812 ? defineCallDescriptor(key)
6813 : defineRedirectDescriptor(key)
6822 * Get the wrapper class of a given prototype.
6823 * @param {Object} proto The prototype of the original event to get its wrapper.
6824 * @returns {Function} The wrapper class.
6827 function getWrapper(proto) {
6828 if (proto == null || proto === Object.prototype) {
6832 let wrapper = wrappers.get(proto);
6833 if (wrapper == null) {
6834 wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
6835 wrappers.set(proto, wrapper);
6841 * Wrap a given event to management a dispatching.
6842 * @param {EventTarget} eventTarget The event target of this dispatching.
6843 * @param {Object} event The event to wrap.
6844 * @returns {Event} The wrapper instance.
6847 function wrapEvent(eventTarget, event) {
6848 const Wrapper = getWrapper(Object.getPrototypeOf(event));
6849 return new Wrapper(eventTarget, event)
6853 * Get the immediateStopped flag of a given event.
6854 * @param {Event} event The event to get.
6855 * @returns {boolean} The flag to stop propagation immediately.
6858 function isStopped(event) {
6859 return pd(event).immediateStopped
6863 * Set the current event phase of a given event.
6864 * @param {Event} event The event to set current target.
6865 * @param {number} eventPhase New event phase.
6869 function setEventPhase(event, eventPhase) {
6870 pd(event).eventPhase = eventPhase;
6874 * Set the current target of a given event.
6875 * @param {Event} event The event to set current target.
6876 * @param {EventTarget|null} currentTarget New current target.
6880 function setCurrentTarget(event, currentTarget) {
6881 pd(event).currentTarget = currentTarget;
6885 * Set a passive listener of a given event.
6886 * @param {Event} event The event to set current target.
6887 * @param {Function|null} passiveListener New passive listener.
6891 function setPassiveListener(event, passiveListener) {
6892 pd(event).passiveListener = passiveListener;
6896 * @typedef {object} ListenerNode
6897 * @property {Function} listener
6898 * @property {1|2|3} listenerType
6899 * @property {boolean} passive
6900 * @property {boolean} once
6901 * @property {ListenerNode|null} next
6906 * @type {WeakMap<object, Map<string, ListenerNode>>}
6909 const listenersMap = new WeakMap();
6914 const ATTRIBUTE = 3;
6917 * Check whether a given value is an object or not.
6918 * @param {any} x The value to check.
6919 * @returns {boolean} `true` if the value is an object.
6921 function isObject(x) {
6922 return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
6927 * @param {EventTarget} eventTarget The event target to get.
6928 * @returns {Map<string, ListenerNode>} The listeners.
6931 function getListeners(eventTarget) {
6932 const listeners = listenersMap.get(eventTarget);
6933 if (listeners == null) {
6934 throw new TypeError(
6935 "'this' is expected an EventTarget object, but got another value."
6942 * Get the property descriptor for the event attribute of a given event.
6943 * @param {string} eventName The event name to get property descriptor.
6944 * @returns {PropertyDescriptor} The property descriptor.
6947 function defineEventAttributeDescriptor(eventName) {
6950 const listeners = getListeners(this);
6951 let node = listeners.get(eventName);
6952 while (node != null) {
6953 if (node.listenerType === ATTRIBUTE) {
6954 return node.listener
6962 if (typeof listener !== "function" && !isObject(listener)) {
6963 listener = null; // eslint-disable-line no-param-reassign
6965 const listeners = getListeners(this);
6967 // Traverse to the tail while removing old value.
6969 let node = listeners.get(eventName);
6970 while (node != null) {
6971 if (node.listenerType === ATTRIBUTE) {
6972 // Remove old value.
6973 if (prev !== null) {
6974 prev.next = node.next;
6975 } else if (node.next !== null) {
6976 listeners.set(eventName, node.next);
6978 listeners.delete(eventName);
6988 if (listener !== null) {
6991 listenerType: ATTRIBUTE,
6996 if (prev === null) {
6997 listeners.set(eventName, newNode);
6999 prev.next = newNode;
7009 * Define an event attribute (e.g. `eventTarget.onclick`).
7010 * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
7011 * @param {string} eventName The event name to define.
7014 function defineEventAttribute(eventTargetPrototype, eventName) {
7015 Object.defineProperty(
7016 eventTargetPrototype,
7018 defineEventAttributeDescriptor(eventName)
7023 * Define a custom EventTarget with event attributes.
7024 * @param {string[]} eventNames Event names for event attributes.
7025 * @returns {EventTarget} The custom EventTarget.
7028 function defineCustomEventTarget(eventNames) {
7029 /** CustomEventTarget */
7030 function CustomEventTarget() {
7031 EventTarget.call(this);
7034 CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
7036 value: CustomEventTarget,
7042 for (let i = 0; i < eventNames.length; ++i) {
7043 defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
7046 return CustomEventTarget
7052 * - This is constructor if no arguments.
7053 * - This is a function which returns a CustomEventTarget constructor if there are arguments.
7057 * class A extends EventTarget {}
7058 * class B extends EventTarget("message") {}
7059 * class C extends EventTarget("message", "error") {}
7060 * class D extends EventTarget(["message", "error"]) {}
7062 function EventTarget() {
7063 /*eslint-disable consistent-return */
7064 if (this instanceof EventTarget) {
7065 listenersMap.set(this, new Map());
7068 if (arguments.length === 1 && Array.isArray(arguments[0])) {
7069 return defineCustomEventTarget(arguments[0])
7071 if (arguments.length > 0) {
7072 const types = new Array(arguments.length);
7073 for (let i = 0; i < arguments.length; ++i) {
7074 types[i] = arguments[i];
7076 return defineCustomEventTarget(types)
7078 throw new TypeError("Cannot call a class as a function")
7079 /*eslint-enable consistent-return */
7082 // Should be enumerable, but class methods are not enumerable.
7083 EventTarget.prototype = {
7085 * Add a given listener to this event target.
7086 * @param {string} eventName The event name to add.
7087 * @param {Function} listener The listener to add.
7088 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
7091 addEventListener(eventName, listener, options) {
7092 if (listener == null) {
7095 if (typeof listener !== "function" && !isObject(listener)) {
7096 throw new TypeError("'listener' should be a function or an object.")
7099 const listeners = getListeners(this);
7100 const optionsIsObj = isObject(options);
7101 const capture = optionsIsObj
7102 ? Boolean(options.capture)
7104 const listenerType = capture ? CAPTURE : BUBBLE;
7108 passive: optionsIsObj && Boolean(options.passive),
7109 once: optionsIsObj && Boolean(options.once),
7113 // Set it as the first node if the first node is null.
7114 let node = listeners.get(eventName);
7115 if (node === undefined) {
7116 listeners.set(eventName, newNode);
7120 // Traverse to the tail while checking duplication..
7122 while (node != null) {
7124 node.listener === listener &&
7125 node.listenerType === listenerType
7127 // Should ignore duplication.
7135 prev.next = newNode;
7139 * Remove a given listener from this event target.
7140 * @param {string} eventName The event name to remove.
7141 * @param {Function} listener The listener to remove.
7142 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
7145 removeEventListener(eventName, listener, options) {
7146 if (listener == null) {
7150 const listeners = getListeners(this);
7151 const capture = isObject(options)
7152 ? Boolean(options.capture)
7154 const listenerType = capture ? CAPTURE : BUBBLE;
7157 let node = listeners.get(eventName);
7158 while (node != null) {
7160 node.listener === listener &&
7161 node.listenerType === listenerType
7163 if (prev !== null) {
7164 prev.next = node.next;
7165 } else if (node.next !== null) {
7166 listeners.set(eventName, node.next);
7168 listeners.delete(eventName);
7179 * Dispatch a given event.
7180 * @param {Event|{type:string}} event The event to dispatch.
7181 * @returns {boolean} `false` if canceled.
7183 dispatchEvent(event) {
7184 if (event == null || typeof event.type !== "string") {
7185 throw new TypeError('"event.type" should be a string.')
7188 // If listeners aren't registered, terminate.
7189 const listeners = getListeners(this);
7190 const eventName = event.type;
7191 let node = listeners.get(eventName);
7196 // Since we cannot rewrite several properties, so wrap object.
7197 const wrappedEvent = wrapEvent(this, event);
7199 // This doesn't process capturing phase and bubbling phase.
7200 // This isn't participating in a tree.
7202 while (node != null) {
7203 // Remove this listener if it's once
7205 if (prev !== null) {
7206 prev.next = node.next;
7207 } else if (node.next !== null) {
7208 listeners.set(eventName, node.next);
7210 listeners.delete(eventName);
7216 // Call this listener
7219 node.passive ? node.listener : null
7221 if (typeof node.listener === "function") {
7223 node.listener.call(this, wrappedEvent);
7226 typeof console !== "undefined" &&
7227 typeof console.error === "function"
7233 node.listenerType !== ATTRIBUTE &&
7234 typeof node.listener.handleEvent === "function"
7236 node.listener.handleEvent(wrappedEvent);
7239 // Break if `event.stopImmediatePropagation` was called.
7240 if (isStopped(wrappedEvent)) {
7246 setPassiveListener(wrappedEvent, null);
7247 setEventPhase(wrappedEvent, 0);
7248 setCurrentTarget(wrappedEvent, null);
7250 return !wrappedEvent.defaultPrevented
7254 // `constructor` is not enumerable.
7255 Object.defineProperty(EventTarget.prototype, "constructor", {
7261 // Ensure `eventTarget instanceof window.EventTarget` is `true`.
7263 typeof window !== "undefined" &&
7264 typeof window.EventTarget !== "undefined"
7266 Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
7269 exports.defineEventAttribute = defineEventAttribute;
7270 exports.EventTarget = EventTarget;
7271 exports.default = EventTarget;
7273 module.exports = EventTarget
7274 module.exports.EventTarget = module.exports["default"] = EventTarget
7275 module.exports.defineEventAttribute = defineEventAttribute
7276 //# sourceMappingURL=event-target-shim.js.map
7281 /***/ (function(module, exports) {
7283 module.exports = require("child_process");
7287 /***/ (function(module, exports) {
7289 module.exports = require("fs");
7293 /***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) {
7296 __webpack_require__.r(__webpack_exports__);
7297 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Headers", function() { return Headers; });
7298 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Request", function() { return Request; });
7299 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Response", function() { return Response; });
7300 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FetchError", function() { return FetchError; });
7301 /* harmony import */ var stream__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
7302 /* harmony import */ var http__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45);
7303 /* harmony import */ var url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(46);
7304 /* harmony import */ var https__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(47);
7305 /* harmony import */ var zlib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(48);
7312 // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
7314 // fix for "Readable" isn't a named export issue
7315 const Readable = stream__WEBPACK_IMPORTED_MODULE_0__.Readable;
7317 const BUFFER = Symbol('buffer');
7318 const TYPE = Symbol('type');
7324 const blobParts = arguments[0];
7325 const options = arguments[1];
7331 const a = blobParts;
7332 const length = Number(a.length);
7333 for (let i = 0; i < length; i++) {
7334 const element = a[i];
7336 if (element instanceof Buffer) {
7338 } else if (ArrayBuffer.isView(element)) {
7339 buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
7340 } else if (element instanceof ArrayBuffer) {
7341 buffer = Buffer.from(element);
7342 } else if (element instanceof Blob) {
7343 buffer = element[BUFFER];
7345 buffer = Buffer.from(typeof element === 'string' ? element : String(element));
7347 size += buffer.length;
7348 buffers.push(buffer);
7352 this[BUFFER] = Buffer.concat(buffers);
7354 let type = options && options.type !== undefined && String(options.type).toLowerCase();
7355 if (type && !/[^\u0020-\u007E]/.test(type)) {
7360 return this[BUFFER].length;
7366 return Promise.resolve(this[BUFFER].toString());
7369 const buf = this[BUFFER];
7370 const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
7371 return Promise.resolve(ab);
7374 const readable = new Readable();
7375 readable._read = function () {};
7376 readable.push(this[BUFFER]);
7377 readable.push(null);
7381 return '[object Blob]';
7384 const size = this.size;
7386 const start = arguments[0];
7387 const end = arguments[1];
7388 let relativeStart, relativeEnd;
7389 if (start === undefined) {
7391 } else if (start < 0) {
7392 relativeStart = Math.max(size + start, 0);
7394 relativeStart = Math.min(start, size);
7396 if (end === undefined) {
7398 } else if (end < 0) {
7399 relativeEnd = Math.max(size + end, 0);
7401 relativeEnd = Math.min(end, size);
7403 const span = Math.max(relativeEnd - relativeStart, 0);
7405 const buffer = this[BUFFER];
7406 const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
7407 const blob = new Blob([], { type: arguments[2] });
7408 blob[BUFFER] = slicedBuffer;
7413 Object.defineProperties(Blob.prototype, {
7414 size: { enumerable: true },
7415 type: { enumerable: true },
7416 slice: { enumerable: true }
7419 Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
7429 * FetchError interface for operational errors
7433 * Create FetchError instance
7435 * @param String message Error message for human
7436 * @param String type Error type for machine
7437 * @param String systemError For Node.js system error
7438 * @return FetchError
7440 function FetchError(message, type, systemError) {
7441 Error.call(this, message);
7443 this.message = message;
7446 // when err.type is `system`, err.code contains system error code
7448 this.code = this.errno = systemError.code;
7451 // hide custom error implementation details from end-users
7452 Error.captureStackTrace(this, this.constructor);
7455 FetchError.prototype = Object.create(Error.prototype);
7456 FetchError.prototype.constructor = FetchError;
7457 FetchError.prototype.name = 'FetchError';
7461 convert = require('encoding').convert;
7464 const INTERNALS = Symbol('Body internals');
7466 // fix an issue where "PassThrough" isn't a named export for node <10
7467 const PassThrough = stream__WEBPACK_IMPORTED_MODULE_0__.PassThrough;
7472 * Ref: https://fetch.spec.whatwg.org/#body
7474 * @param Stream body Readable stream
7475 * @param Object opts Response options
7478 function Body(body) {
7481 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
7482 _ref$size = _ref.size;
7484 let size = _ref$size === undefined ? 0 : _ref$size;
7485 var _ref$timeout = _ref.timeout;
7486 let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
7489 // body is undefined or null
7491 } else if (isURLSearchParams(body)) {
7492 // body is a URLSearchParams
7493 body = Buffer.from(body.toString());
7494 } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
7495 // body is ArrayBuffer
7496 body = Buffer.from(body);
7497 } else if (ArrayBuffer.isView(body)) {
7498 // body is ArrayBufferView
7499 body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
7500 } else if (body instanceof stream__WEBPACK_IMPORTED_MODULE_0__) ; else {
7501 // none of the above
7502 // coerce to string then buffer
7503 body = Buffer.from(String(body));
7511 this.timeout = timeout;
7513 if (body instanceof stream__WEBPACK_IMPORTED_MODULE_0__) {
7514 body.on('error', function (err) {
7515 const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
7516 _this[INTERNALS].error = error;
7523 return this[INTERNALS].body;
7527 return this[INTERNALS].disturbed;
7531 * Decode response as ArrayBuffer
7536 return consumeBody.call(this).then(function (buf) {
7537 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
7542 * Return raw response as Blob
7547 let ct = this.headers && this.headers.get('content-type') || '';
7548 return consumeBody.call(this).then(function (buf) {
7549 return Object.assign(
7552 type: ct.toLowerCase()
7560 * Decode response as json
7567 return consumeBody.call(this).then(function (buffer) {
7569 return JSON.parse(buffer.toString());
7571 return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
7577 * Decode response as text
7582 return consumeBody.call(this).then(function (buffer) {
7583 return buffer.toString();
7588 * Decode response as buffer (non-spec api)
7593 return consumeBody.call(this);
7597 * Decode response as text, while automatically detecting the encoding and
7598 * trying to decode to UTF-8 (non-spec api)
7605 return consumeBody.call(this).then(function (buffer) {
7606 return convertBody(buffer, _this3.headers);
7611 // In browsers, all properties are enumerable.
7612 Object.defineProperties(Body.prototype, {
7613 body: { enumerable: true },
7614 bodyUsed: { enumerable: true },
7615 arrayBuffer: { enumerable: true },
7616 blob: { enumerable: true },
7617 json: { enumerable: true },
7618 text: { enumerable: true }
7621 Body.mixIn = function (proto) {
7622 for (const name of Object.getOwnPropertyNames(Body.prototype)) {
7623 // istanbul ignore else: future proof
7624 if (!(name in proto)) {
7625 const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
7626 Object.defineProperty(proto, name, desc);
7632 * Consume and convert an entire Body to a Buffer.
7634 * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
7638 function consumeBody() {
7641 if (this[INTERNALS].disturbed) {
7642 return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
7645 this[INTERNALS].disturbed = true;
7647 if (this[INTERNALS].error) {
7648 return Body.Promise.reject(this[INTERNALS].error);
7651 let body = this.body;
7654 if (body === null) {
7655 return Body.Promise.resolve(Buffer.alloc(0));
7660 body = body.stream();
7664 if (Buffer.isBuffer(body)) {
7665 return Body.Promise.resolve(body);
7668 // istanbul ignore if: should never happen
7669 if (!(body instanceof stream__WEBPACK_IMPORTED_MODULE_0__)) {
7670 return Body.Promise.resolve(Buffer.alloc(0));
7674 // get ready to actually consume the body
7679 return new Body.Promise(function (resolve, reject) {
7682 // allow timeout on slow response body
7683 if (_this4.timeout) {
7684 resTimeout = setTimeout(function () {
7686 reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
7690 // handle stream errors
7691 body.on('error', function (err) {
7692 if (err.name === 'AbortError') {
7693 // if the request was aborted, reject with this Error
7697 // other errors, such as incorrect content-encoding
7698 reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
7702 body.on('data', function (chunk) {
7703 if (abort || chunk === null) {
7707 if (_this4.size && accumBytes + chunk.length > _this4.size) {
7709 reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
7713 accumBytes += chunk.length;
7717 body.on('end', function () {
7722 clearTimeout(resTimeout);
7725 resolve(Buffer.concat(accum, accumBytes));
7727 // handle streams that have accumulated too much data (issue #414)
7728 reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
7735 * Detect buffer encoding and convert to target encoding
7736 * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
7738 * @param Buffer buffer Incoming buffer
7739 * @param String encoding Target encoding
7742 function convertBody(buffer, headers) {
7743 if (typeof convert !== 'function') {
7744 throw new Error('The package `encoding` must be installed to use the textConverted() function');
7747 const ct = headers.get('content-type');
7748 let charset = 'utf-8';
7753 res = /charset=([^;]*)/i.exec(ct);
7756 // no charset in content type, peek at response body for at most 1024 bytes
7757 str = buffer.slice(0, 1024).toString();
7761 res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
7766 res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
7769 res = /charset=(.*)/i.exec(res.pop());
7775 res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
7780 charset = res.pop();
7782 // prevent decode issues when sites use incorrect encoding
7783 // ref: https://hsivonen.fi/encoding-menu/
7784 if (charset === 'gb2312' || charset === 'gbk') {
7785 charset = 'gb18030';
7789 // turn raw buffers into a single utf-8 buffer
7790 return convert(buffer, 'UTF-8', charset).toString();
7794 * Detect a URLSearchParams object
7795 * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
7797 * @param Object obj Object to detect by type or brand
7800 function isURLSearchParams(obj) {
7801 // Duck-typing as a necessary condition.
7802 if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
7806 // Brand-checking and more duck-typing as optional condition.
7807 return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
7811 * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
7815 function isBlob(obj) {
7816 return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
7820 * Clone body given Res/Req instance
7822 * @param Mixed instance Response or Request instance
7825 function clone(instance) {
7827 let body = instance.body;
7829 // don't allow cloning a used body
7830 if (instance.bodyUsed) {
7831 throw new Error('cannot clone body after it is used');
7834 // check that body is a stream and not form-data object
7835 // note: we can't clone the form-data object without having it as a dependency
7836 if (body instanceof stream__WEBPACK_IMPORTED_MODULE_0__ && typeof body.getBoundary !== 'function') {
7837 // tee instance body
7838 p1 = new PassThrough();
7839 p2 = new PassThrough();
7842 // set instance body to teed body and return the other teed body
7843 instance[INTERNALS].body = p1;
7851 * Performs the operation "extract a `Content-Type` value from |object|" as
7852 * specified in the specification:
7853 * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
7855 * This function assumes that instance.body is present.
7857 * @param Mixed instance Any options.body input
7859 function extractContentType(body) {
7860 if (body === null) {
7863 } else if (typeof body === 'string') {
7865 return 'text/plain;charset=UTF-8';
7866 } else if (isURLSearchParams(body)) {
7867 // body is a URLSearchParams
7868 return 'application/x-www-form-urlencoded;charset=UTF-8';
7869 } else if (isBlob(body)) {
7871 return body.type || null;
7872 } else if (Buffer.isBuffer(body)) {
7875 } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
7876 // body is ArrayBuffer
7878 } else if (ArrayBuffer.isView(body)) {
7879 // body is ArrayBufferView
7881 } else if (typeof body.getBoundary === 'function') {
7882 // detect form data input from form-data module
7883 return `multipart/form-data;boundary=${body.getBoundary()}`;
7884 } else if (body instanceof stream__WEBPACK_IMPORTED_MODULE_0__) {
7886 // can't really do much about this
7889 // Body constructor defaults other things to string
7890 return 'text/plain;charset=UTF-8';
7895 * The Fetch Standard treats this as if "total bytes" is a property on the body.
7896 * For us, we have to explicitly get it with a function.
7898 * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
7900 * @param Body instance Instance of Body
7901 * @return Number? Number of bytes, or null if not possible
7903 function getTotalBytes(instance) {
7904 const body = instance.body;
7907 if (body === null) {
7910 } else if (isBlob(body)) {
7912 } else if (Buffer.isBuffer(body)) {
7915 } else if (body && typeof body.getLengthSync === 'function') {
7916 // detect form data input from form-data module
7917 if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
7918 body.hasKnownLength && body.hasKnownLength()) {
7920 return body.getLengthSync();
7930 * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
7932 * @param Body instance Instance of Body
7935 function writeToStream(dest, instance) {
7936 const body = instance.body;
7939 if (body === null) {
7942 } else if (isBlob(body)) {
7943 body.stream().pipe(dest);
7944 } else if (Buffer.isBuffer(body)) {
7955 Body.Promise = global.Promise;
7960 * Headers class offers convenient helpers
7963 const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
7964 const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
7966 function validateName(name) {
7968 if (invalidTokenRegex.test(name) || name === '') {
7969 throw new TypeError(`${name} is not a legal HTTP header name`);
7973 function validateValue(value) {
7975 if (invalidHeaderCharRegex.test(value)) {
7976 throw new TypeError(`${value} is not a legal HTTP header value`);
7981 * Find the key in the map object given a header name.
7983 * Returns undefined if not found.
7985 * @param String name Header name
7986 * @return String|Undefined
7988 function find(map, name) {
7989 name = name.toLowerCase();
7990 for (const key in map) {
7991 if (key.toLowerCase() === name) {
7998 const MAP = Symbol('map');
8003 * @param Object headers Response headers
8007 let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
8009 this[MAP] = Object.create(null);
8011 if (init instanceof Headers) {
8012 const rawHeaders = init.raw();
8013 const headerNames = Object.keys(rawHeaders);
8015 for (const headerName of headerNames) {
8016 for (const value of rawHeaders[headerName]) {
8017 this.append(headerName, value);
8024 // We don't worry about converting prop to ByteString here as append()
8026 if (init == null) ; else if (typeof init === 'object') {
8027 const method = init[Symbol.iterator];
8028 if (method != null) {
8029 if (typeof method !== 'function') {
8030 throw new TypeError('Header pairs must be iterable');
8033 // sequence<sequence<ByteString>>
8034 // Note: per spec we have to first exhaust the lists then process them
8036 for (const pair of init) {
8037 if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
8038 throw new TypeError('Each header pair must be iterable');
8040 pairs.push(Array.from(pair));
8043 for (const pair of pairs) {
8044 if (pair.length !== 2) {
8045 throw new TypeError('Each header pair must be a name/value tuple');
8047 this.append(pair[0], pair[1]);
8050 // record<ByteString, ByteString>
8051 for (const key of Object.keys(init)) {
8052 const value = init[key];
8053 this.append(key, value);
8057 throw new TypeError('Provided initializer must be an object');
8062 * Return combined header value given name
8064 * @param String name Header name
8070 const key = find(this[MAP], name);
8071 if (key === undefined) {
8075 return this[MAP][key].join(', ');
8079 * Iterate over all headers
8081 * @param Function callback Executed for each item with parameters (value, name, thisArg)
8082 * @param Boolean thisArg `this` context for callback function
8086 let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
8088 let pairs = getHeaders(this);
8090 while (i < pairs.length) {
8091 var _pairs$i = pairs[i];
8092 const name = _pairs$i[0],
8093 value = _pairs$i[1];
8095 callback.call(thisArg, value, name, this);
8096 pairs = getHeaders(this);
8102 * Overwrite header values given name
8104 * @param String name Header name
8105 * @param String value Header value
8112 validateValue(value);
8113 const key = find(this[MAP], name);
8114 this[MAP][key !== undefined ? key : name] = [value];
8118 * Append a value onto existing header
8120 * @param String name Header name
8121 * @param String value Header value
8124 append(name, value) {
8128 validateValue(value);
8129 const key = find(this[MAP], name);
8130 if (key !== undefined) {
8131 this[MAP][key].push(value);
8133 this[MAP][name] = [value];
8138 * Check for header name existence
8140 * @param String name Header name
8146 return find(this[MAP], name) !== undefined;
8150 * Delete all header values given name
8152 * @param String name Header name
8158 const key = find(this[MAP], name);
8159 if (key !== undefined) {
8160 delete this[MAP][key];
8165 * Return raw headers (non-spec api)
8174 * Get an iterator on keys.
8179 return createHeadersIterator(this, 'key');
8183 * Get an iterator on values.
8188 return createHeadersIterator(this, 'value');
8192 * Get an iterator on entries.
8194 * This is the default iterator of the Headers object.
8198 [Symbol.iterator]() {
8199 return createHeadersIterator(this, 'key+value');
8202 Headers.prototype.entries = Headers.prototype[Symbol.iterator];
8204 Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
8211 Object.defineProperties(Headers.prototype, {
8212 get: { enumerable: true },
8213 forEach: { enumerable: true },
8214 set: { enumerable: true },
8215 append: { enumerable: true },
8216 has: { enumerable: true },
8217 delete: { enumerable: true },
8218 keys: { enumerable: true },
8219 values: { enumerable: true },
8220 entries: { enumerable: true }
8223 function getHeaders(headers) {
8224 let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
8226 const keys = Object.keys(headers[MAP]).sort();
8227 return keys.map(kind === 'key' ? function (k) {
8228 return k.toLowerCase();
8229 } : kind === 'value' ? function (k) {
8230 return headers[MAP][k].join(', ');
8232 return [k.toLowerCase(), headers[MAP][k].join(', ')];
8236 const INTERNAL = Symbol('internal');
8238 function createHeadersIterator(target, kind) {
8239 const iterator = Object.create(HeadersIteratorPrototype);
8240 iterator[INTERNAL] = {
8248 const HeadersIteratorPrototype = Object.setPrototypeOf({
8250 // istanbul ignore if
8251 if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
8252 throw new TypeError('Value of `this` is not a HeadersIterator');
8255 var _INTERNAL = this[INTERNAL];
8256 const target = _INTERNAL.target,
8257 kind = _INTERNAL.kind,
8258 index = _INTERNAL.index;
8260 const values = getHeaders(target, kind);
8261 const len = values.length;
8269 this[INTERNAL].index = index + 1;
8272 value: values[index],
8276 }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
8278 Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
8279 value: 'HeadersIterator',
8286 * Export the Headers object in a form that Node.js can consume.
8288 * @param Headers headers
8291 function exportNodeCompatibleHeaders(headers) {
8292 const obj = Object.assign({ __proto__: null }, headers[MAP]);
8294 // http.request() only supports string as Host header. This hack makes
8295 // specifying custom Host header possible.
8296 const hostHeaderKey = find(headers[MAP], 'Host');
8297 if (hostHeaderKey !== undefined) {
8298 obj[hostHeaderKey] = obj[hostHeaderKey][0];
8305 * Create a Headers object from an object of headers, ignoring those that do
8306 * not conform to HTTP grammar productions.
8308 * @param Object obj Object of headers
8311 function createHeadersLenient(obj) {
8312 const headers = new Headers();
8313 for (const name of Object.keys(obj)) {
8314 if (invalidTokenRegex.test(name)) {
8317 if (Array.isArray(obj[name])) {
8318 for (const val of obj[name]) {
8319 if (invalidHeaderCharRegex.test(val)) {
8322 if (headers[MAP][name] === undefined) {
8323 headers[MAP][name] = [val];
8325 headers[MAP][name].push(val);
8328 } else if (!invalidHeaderCharRegex.test(obj[name])) {
8329 headers[MAP][name] = [obj[name]];
8335 const INTERNALS$1 = Symbol('Response internals');
8337 // fix an issue where "STATUS_CODES" aren't a named export for node <10
8338 const STATUS_CODES = http__WEBPACK_IMPORTED_MODULE_1__.STATUS_CODES;
8343 * @param Stream body Readable stream
8344 * @param Object opts Response options
8349 let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
8350 let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
8352 Body.call(this, body, opts);
8354 const status = opts.status || 200;
8355 const headers = new Headers(opts.headers);
8357 if (body != null && !headers.has('Content-Type')) {
8358 const contentType = extractContentType(body);
8360 headers.append('Content-Type', contentType);
8364 this[INTERNALS$1] = {
8367 statusText: opts.statusText || STATUS_CODES[status],
8369 counter: opts.counter
8374 return this[INTERNALS$1].url || '';
8378 return this[INTERNALS$1].status;
8382 * Convenience property representing if the request ended normally
8385 return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
8389 return this[INTERNALS$1].counter > 0;
8393 return this[INTERNALS$1].statusText;
8397 return this[INTERNALS$1].headers;
8401 * Clone this response
8406 return new Response(clone(this), {
8408 status: this.status,
8409 statusText: this.statusText,
8410 headers: this.headers,
8412 redirected: this.redirected
8417 Body.mixIn(Response.prototype);
8419 Object.defineProperties(Response.prototype, {
8420 url: { enumerable: true },
8421 status: { enumerable: true },
8422 ok: { enumerable: true },
8423 redirected: { enumerable: true },
8424 statusText: { enumerable: true },
8425 headers: { enumerable: true },
8426 clone: { enumerable: true }
8429 Object.defineProperty(Response.prototype, Symbol.toStringTag, {
8436 const INTERNALS$2 = Symbol('Request internals');
8438 // fix an issue where "format", "parse" aren't a named export for node <10
8439 const parse_url = url__WEBPACK_IMPORTED_MODULE_2__.parse;
8440 const format_url = url__WEBPACK_IMPORTED_MODULE_2__.format;
8442 const streamDestructionSupported = 'destroy' in stream__WEBPACK_IMPORTED_MODULE_0__.Readable.prototype;
8445 * Check if a value is an instance of Request.
8447 * @param Mixed input
8450 function isRequest(input) {
8451 return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
8454 function isAbortSignal(signal) {
8455 const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
8456 return !!(proto && proto.constructor.name === 'AbortSignal');
8462 * @param Mixed input Url or Request instance
8463 * @param Object init Custom options
8467 constructor(input) {
8468 let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
8473 if (!isRequest(input)) {
8474 if (input && input.href) {
8475 // in order to support Node.js' Url objects; though WHATWG's URL objects
8476 // will fall into this branch also (since their `toString()` will return
8477 // `href` property anyway)
8478 parsedURL = parse_url(input.href);
8480 // coerce input to a string before attempting to parse
8481 parsedURL = parse_url(`${input}`);
8485 parsedURL = parse_url(input.url);
8488 let method = init.method || input.method || 'GET';
8489 method = method.toUpperCase();
8491 if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
8492 throw new TypeError('Request with GET/HEAD method cannot have body');
8495 let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
8497 Body.call(this, inputBody, {
8498 timeout: init.timeout || input.timeout || 0,
8499 size: init.size || input.size || 0
8502 const headers = new Headers(init.headers || input.headers || {});
8504 if (inputBody != null && !headers.has('Content-Type')) {
8505 const contentType = extractContentType(inputBody);
8507 headers.append('Content-Type', contentType);
8511 let signal = isRequest(input) ? input.signal : null;
8512 if ('signal' in init) signal = init.signal;
8514 if (signal != null && !isAbortSignal(signal)) {
8515 throw new TypeError('Expected signal to be an instanceof AbortSignal');
8518 this[INTERNALS$2] = {
8520 redirect: init.redirect || input.redirect || 'follow',
8526 // node-fetch-only options
8527 this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
8528 this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
8529 this.counter = init.counter || input.counter || 0;
8530 this.agent = init.agent || input.agent;
8534 return this[INTERNALS$2].method;
8538 return format_url(this[INTERNALS$2].parsedURL);
8542 return this[INTERNALS$2].headers;
8546 return this[INTERNALS$2].redirect;
8550 return this[INTERNALS$2].signal;
8554 * Clone this request
8559 return new Request(this);
8563 Body.mixIn(Request.prototype);
8565 Object.defineProperty(Request.prototype, Symbol.toStringTag, {
8572 Object.defineProperties(Request.prototype, {
8573 method: { enumerable: true },
8574 url: { enumerable: true },
8575 headers: { enumerable: true },
8576 redirect: { enumerable: true },
8577 clone: { enumerable: true },
8578 signal: { enumerable: true }
8582 * Convert a Request to Node.js http request options.
8584 * @param Request A Request instance
8585 * @return Object The options object to be passed to http.request
8587 function getNodeRequestOptions(request) {
8588 const parsedURL = request[INTERNALS$2].parsedURL;
8589 const headers = new Headers(request[INTERNALS$2].headers);
8592 if (!headers.has('Accept')) {
8593 headers.set('Accept', '*/*');
8597 if (!parsedURL.protocol || !parsedURL.hostname) {
8598 throw new TypeError('Only absolute URLs are supported');
8601 if (!/^https?:$/.test(parsedURL.protocol)) {
8602 throw new TypeError('Only HTTP(S) protocols are supported');
8605 if (request.signal && request.body instanceof stream__WEBPACK_IMPORTED_MODULE_0__.Readable && !streamDestructionSupported) {
8606 throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
8609 // HTTP-network-or-cache fetch steps 2.4-2.7
8610 let contentLengthValue = null;
8611 if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
8612 contentLengthValue = '0';
8614 if (request.body != null) {
8615 const totalBytes = getTotalBytes(request);
8616 if (typeof totalBytes === 'number') {
8617 contentLengthValue = String(totalBytes);
8620 if (contentLengthValue) {
8621 headers.set('Content-Length', contentLengthValue);
8624 // HTTP-network-or-cache fetch step 2.11
8625 if (!headers.has('User-Agent')) {
8626 headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
8629 // HTTP-network-or-cache fetch step 2.15
8630 if (request.compress && !headers.has('Accept-Encoding')) {
8631 headers.set('Accept-Encoding', 'gzip,deflate');
8634 let agent = request.agent;
8635 if (typeof agent === 'function') {
8636 agent = agent(parsedURL);
8639 if (!headers.has('Connection') && !agent) {
8640 headers.set('Connection', 'close');
8643 // HTTP-network fetch step 4.2
8644 // chunked encoding is handled by Node.js
8646 return Object.assign({}, parsedURL, {
8647 method: request.method,
8648 headers: exportNodeCompatibleHeaders(headers),
8656 * AbortError interface for cancelled requests
8660 * Create AbortError instance
8662 * @param String message Error message for human
8663 * @return AbortError
8665 function AbortError(message) {
8666 Error.call(this, message);
8668 this.type = 'aborted';
8669 this.message = message;
8671 // hide custom error implementation details from end-users
8672 Error.captureStackTrace(this, this.constructor);
8675 AbortError.prototype = Object.create(Error.prototype);
8676 AbortError.prototype.constructor = AbortError;
8677 AbortError.prototype.name = 'AbortError';
8679 // fix an issue where "PassThrough", "resolve" aren't a named export for node <10
8680 const PassThrough$1 = stream__WEBPACK_IMPORTED_MODULE_0__.PassThrough;
8681 const resolve_url = url__WEBPACK_IMPORTED_MODULE_2__.resolve;
8686 * @param Mixed url Absolute url or Request instance
8687 * @param Object opts Fetch options
8690 function fetch(url, opts) {
8692 // allow custom promise
8693 if (!fetch.Promise) {
8694 throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
8697 Body.Promise = fetch.Promise;
8699 // wrap http.request into fetch
8700 return new fetch.Promise(function (resolve, reject) {
8701 // build request object
8702 const request = new Request(url, opts);
8703 const options = getNodeRequestOptions(request);
8705 const send = (options.protocol === 'https:' ? https__WEBPACK_IMPORTED_MODULE_3__ : http__WEBPACK_IMPORTED_MODULE_1__).request;
8706 const signal = request.signal;
8708 let response = null;
8710 const abort = function abort() {
8711 let error = new AbortError('The user aborted a request.');
8713 if (request.body && request.body instanceof stream__WEBPACK_IMPORTED_MODULE_0__.Readable) {
8714 request.body.destroy(error);
8716 if (!response || !response.body) return;
8717 response.body.emit('error', error);
8720 if (signal && signal.aborted) {
8725 const abortAndFinalize = function abortAndFinalize() {
8731 const req = send(options);
8735 signal.addEventListener('abort', abortAndFinalize);
8738 function finalize() {
8740 if (signal) signal.removeEventListener('abort', abortAndFinalize);
8741 clearTimeout(reqTimeout);
8744 if (request.timeout) {
8745 req.once('socket', function (socket) {
8746 reqTimeout = setTimeout(function () {
8747 reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
8749 }, request.timeout);
8753 req.on('error', function (err) {
8754 reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
8758 req.on('response', function (res) {
8759 clearTimeout(reqTimeout);
8761 const headers = createHeadersLenient(res.headers);
8763 // HTTP fetch step 5
8764 if (fetch.isRedirect(res.statusCode)) {
8765 // HTTP fetch step 5.2
8766 const location = headers.get('Location');
8768 // HTTP fetch step 5.3
8769 const locationURL = location === null ? null : resolve_url(request.url, location);
8771 // HTTP fetch step 5.5
8772 switch (request.redirect) {
8774 reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
8778 // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
8779 if (locationURL !== null) {
8780 // handle corrupted header
8782 headers.set('Location', locationURL);
8784 // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
8790 // HTTP-redirect fetch step 2
8791 if (locationURL === null) {
8795 // HTTP-redirect fetch step 5
8796 if (request.counter >= request.follow) {
8797 reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
8802 // HTTP-redirect fetch step 6 (counter increment)
8803 // Create a new Request object.
8804 const requestOpts = {
8805 headers: new Headers(request.headers),
8806 follow: request.follow,
8807 counter: request.counter + 1,
8808 agent: request.agent,
8809 compress: request.compress,
8810 method: request.method,
8812 signal: request.signal,
8813 timeout: request.timeout
8816 // HTTP-redirect fetch step 9
8817 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
8818 reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
8823 // HTTP-redirect fetch step 11
8824 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
8825 requestOpts.method = 'GET';
8826 requestOpts.body = undefined;
8827 requestOpts.headers.delete('content-length');
8830 // HTTP-redirect fetch step 15
8831 resolve(fetch(new Request(locationURL, requestOpts)));
8838 res.once('end', function () {
8839 if (signal) signal.removeEventListener('abort', abortAndFinalize);
8841 let body = res.pipe(new PassThrough$1());
8843 const response_options = {
8845 status: res.statusCode,
8846 statusText: res.statusMessage,
8849 timeout: request.timeout,
8850 counter: request.counter
8853 // HTTP-network fetch step 12.1.1.3
8854 const codings = headers.get('Content-Encoding');
8856 // HTTP-network fetch step 12.1.1.4: handle content codings
8858 // in following scenarios we ignore compression support
8859 // 1. compression support is disabled
8861 // 3. no Content-Encoding header
8862 // 4. no content response (204)
8863 // 5. content not modified response (304)
8864 if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
8865 response = new Response(body, response_options);
8871 // Be less strict when decoding compressed responses, since sometimes
8872 // servers send slightly invalid responses that are still accepted
8873 // by common browsers.
8874 // Always using Z_SYNC_FLUSH is what cURL does.
8875 const zlibOptions = {
8876 flush: zlib__WEBPACK_IMPORTED_MODULE_4__.Z_SYNC_FLUSH,
8877 finishFlush: zlib__WEBPACK_IMPORTED_MODULE_4__.Z_SYNC_FLUSH
8881 if (codings == 'gzip' || codings == 'x-gzip') {
8882 body = body.pipe(zlib__WEBPACK_IMPORTED_MODULE_4__.createGunzip(zlibOptions));
8883 response = new Response(body, response_options);
8889 if (codings == 'deflate' || codings == 'x-deflate') {
8890 // handle the infamous raw deflate response from old servers
8891 // a hack for old IIS and Apache servers
8892 const raw = res.pipe(new PassThrough$1());
8893 raw.once('data', function (chunk) {
8894 // see http://stackoverflow.com/questions/37519828
8895 if ((chunk[0] & 0x0F) === 0x08) {
8896 body = body.pipe(zlib__WEBPACK_IMPORTED_MODULE_4__.createInflate());
8898 body = body.pipe(zlib__WEBPACK_IMPORTED_MODULE_4__.createInflateRaw());
8900 response = new Response(body, response_options);
8907 if (codings == 'br' && typeof zlib__WEBPACK_IMPORTED_MODULE_4__.createBrotliDecompress === 'function') {
8908 body = body.pipe(zlib__WEBPACK_IMPORTED_MODULE_4__.createBrotliDecompress());
8909 response = new Response(body, response_options);
8914 // otherwise, use response as-is
8915 response = new Response(body, response_options);
8919 writeToStream(req, request);
8923 * Redirect code matching
8925 * @param Number code Status code
8928 fetch.isRedirect = function (code) {
8929 return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
8933 fetch.Promise = global.Promise;
8935 /* harmony default export */ __webpack_exports__["default"] = (fetch);
8941 /***/ (function(module, exports) {
8943 module.exports = require("stream");
8947 /***/ (function(module, exports) {
8949 module.exports = require("http");
8953 /***/ (function(module, exports) {
8955 module.exports = require("url");
8959 /***/ (function(module, exports) {
8961 module.exports = require("https");
8965 /***/ (function(module, exports) {
8967 module.exports = require("zlib");
8971 /***/ (function(module, exports, __webpack_require__) {
8976 const fs = __webpack_require__(42);
8977 const { Readable } = __webpack_require__(44);
8978 const sysPath = __webpack_require__(2);
8979 const { promisify } = __webpack_require__(50);
8980 const picomatch = __webpack_require__(51);
8982 const readdir = promisify(fs.readdir);
8983 const stat = promisify(fs.stat);
8984 const lstat = promisify(fs.lstat);
8985 const realpath = promisify(fs.realpath);
8988 * @typedef {Object} EntryInfo
8989 * @property {String} path
8990 * @property {String} fullPath
8991 * @property {fs.Stats=} stats
8992 * @property {fs.Dirent=} dirent
8993 * @property {String} basename
8997 const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']);
8998 const FILE_TYPE = 'files';
8999 const DIR_TYPE = 'directories';
9000 const FILE_DIR_TYPE = 'files_directories';
9001 const EVERYTHING_TYPE = 'all';
9002 const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
9004 const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
9006 const normalizeFilter = filter => {
9007 if (filter === undefined) return;
9008 if (typeof filter === 'function') return filter;
9010 if (typeof filter === 'string') {
9011 const glob = picomatch(filter.trim());
9012 return entry => glob(entry.basename);
9015 if (Array.isArray(filter)) {
9016 const positive = [];
9017 const negative = [];
9018 for (const item of filter) {
9019 const trimmed = item.trim();
9020 if (trimmed.charAt(0) === BANG) {
9021 negative.push(picomatch(trimmed.slice(1)));
9023 positive.push(picomatch(trimmed));
9027 if (negative.length > 0) {
9028 if (positive.length > 0) {
9030 positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
9032 return entry => !negative.some(f => f(entry.basename));
9034 return entry => positive.some(f => f(entry.basename));
9038 class ReaddirpStream extends Readable {
9039 static get defaultOptions() {
9042 /* eslint-disable no-unused-vars */
9043 fileFilter: (path) => true,
9044 directoryFilter: (path) => true,
9045 /* eslint-enable no-unused-vars */
9053 constructor(options = {}) {
9057 highWaterMark: options.highWaterMark || 4096
9059 const opts = { ...ReaddirpStream.defaultOptions, ...options };
9060 const { root, type } = opts;
9062 this._fileFilter = normalizeFilter(opts.fileFilter);
9063 this._directoryFilter = normalizeFilter(opts.directoryFilter);
9065 const statMethod = opts.lstat ? lstat : stat;
9066 // Use bigint stats if it's windows and stat() supports options (node 10+).
9067 if (process.platform === 'win32' && stat.length === 3) {
9068 this._stat = path => statMethod(path, { bigint: true });
9070 this._stat = statMethod;
9073 this._maxDepth = opts.depth;
9074 this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
9075 this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
9076 this._wantsEverything = type === EVERYTHING_TYPE;
9077 this._root = sysPath.resolve(root);
9078 this._isDirent = ('Dirent' in fs) && !opts.alwaysStat;
9079 this._statsProp = this._isDirent ? 'dirent' : 'stats';
9080 this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
9082 // Launch stream with one parent, the root dir.
9083 this.parents = [this._exploreDir(root, 1)];
9084 this.reading = false;
9085 this.parent = undefined;
9088 async _read(batch) {
9089 if (this.reading) return;
9090 this.reading = true;
9093 while (!this.destroyed && batch > 0) {
9094 const { path, depth, files = [] } = this.parent || {};
9096 if (files.length > 0) {
9097 const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
9098 for (const entry of await Promise.all(slice)) {
9099 if (this.destroyed) return;
9101 const entryType = await this._getEntryType(entry);
9102 if (entryType === 'directory' && this._directoryFilter(entry)) {
9103 if (depth <= this._maxDepth) {
9104 this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
9107 if (this._wantsDir) {
9111 } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
9112 if (this._wantsFile) {
9119 const parent = this.parents.pop();
9124 this.parent = await parent;
9125 if (this.destroyed) return;
9129 this.destroy(error);
9131 this.reading = false;
9135 async _exploreDir(path, depth) {
9138 files = await readdir(path, this._rdOptions);
9140 this._onError(error);
9142 return {files, depth, path};
9145 async _formatEntry(dirent, path) {
9148 const basename = this._isDirent ? dirent.name : dirent;
9149 const fullPath = sysPath.resolve(sysPath.join(path, basename));
9150 entry = {path: sysPath.relative(this._root, fullPath), fullPath, basename};
9151 entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
9159 if (isNormalFlowError(err) && !this.destroyed) {
9160 this.emit('warn', err);
9166 async _getEntryType(entry) {
9167 // entry may be undefined, because a warning or an error were emitted
9168 // and the statsProp is undefined
9169 const stats = entry && entry[this._statsProp];
9173 if (stats.isFile()) {
9176 if (stats.isDirectory()) {
9179 if (stats && stats.isSymbolicLink()) {
9181 const entryRealPath = await realpath(entry.fullPath);
9182 const entryRealPathStats = await lstat(entryRealPath);
9183 if (entryRealPathStats.isFile()) {
9186 if (entryRealPathStats.isDirectory()) {
9190 this._onError(error);
9195 _includeAsFile(entry) {
9196 const stats = entry && entry[this._statsProp];
9198 return stats && this._wantsEverything && !stats.isDirectory();
9203 * @typedef {Object} ReaddirpArguments
9204 * @property {Function=} fileFilter
9205 * @property {Function=} directoryFilter
9206 * @property {String=} type
9207 * @property {Number=} depth
9208 * @property {String=} root
9209 * @property {Boolean=} lstat
9210 * @property {Boolean=} bigint
9214 * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
9215 * @param {String} root Root directory
9216 * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
9218 const readdirp = (root, options = {}) => {
9219 let type = options.entryType || options.type;
9220 if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
9221 if (type) options.type = type;
9223 throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
9224 } else if (typeof root !== 'string') {
9225 throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
9226 } else if (type && !ALL_TYPES.includes(type)) {
9227 throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
9230 options.root = root;
9231 return new ReaddirpStream(options);
9234 const readdirpPromise = (root, options = {}) => {
9235 return new Promise((resolve, reject) => {
9237 readdirp(root, options)
9238 .on('data', entry => files.push(entry))
9239 .on('end', () => resolve(files))
9240 .on('error', error => reject(error));
9244 readdirp.promise = readdirpPromise;
9245 readdirp.ReaddirpStream = ReaddirpStream;
9246 readdirp.default = readdirp;
9248 module.exports = readdirp;
9253 /***/ (function(module, exports) {
9255 module.exports = require("util");
9259 /***/ (function(module, exports, __webpack_require__) {
9264 module.exports = __webpack_require__(52);
9269 /***/ (function(module, exports, __webpack_require__) {
9274 const path = __webpack_require__(2);
9275 const scan = __webpack_require__(53);
9276 const parse = __webpack_require__(56);
9277 const utils = __webpack_require__(54);
9278 const constants = __webpack_require__(55);
9279 const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
9282 * Creates a matcher function from one or more glob patterns. The
9283 * returned function takes a string to match as its first argument,
9284 * and returns true if the string is a match. The returned matcher
9285 * function also takes a boolean as the second argument that, when true,
9286 * returns an object with additional information.
9289 * const picomatch = require('picomatch');
9290 * // picomatch(glob[, options]);
9292 * const isMatch = picomatch('*.!(*a)');
9293 * console.log(isMatch('a.a')); //=> false
9294 * console.log(isMatch('a.b')); //=> true
9297 * @param {String|Array} `globs` One or more glob patterns.
9298 * @param {Object=} `options`
9299 * @return {Function=} Returns a matcher function.
9303 const picomatch = (glob, options, returnState = false) => {
9304 if (Array.isArray(glob)) {
9305 const fns = glob.map(input => picomatch(input, options, returnState));
9306 const arrayMatcher = str => {
9307 for (const isMatch of fns) {
9308 const state = isMatch(str);
9309 if (state) return state;
9313 return arrayMatcher;
9316 const isState = isObject(glob) && glob.tokens && glob.input;
9318 if (glob === '' || (typeof glob !== 'string' && !isState)) {
9319 throw new TypeError('Expected pattern to be a non-empty string');
9322 const opts = options || {};
9323 const posix = utils.isWindows(options);
9324 const regex = isState
9325 ? picomatch.compileRe(glob, options)
9326 : picomatch.makeRe(glob, options, false, true);
9328 const state = regex.state;
9331 let isIgnored = () => false;
9333 const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
9334 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
9337 const matcher = (input, returnObject = false) => {
9338 const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
9339 const result = { glob, state, regex, posix, input, output, match, isMatch };
9341 if (typeof opts.onResult === 'function') {
9342 opts.onResult(result);
9345 if (isMatch === false) {
9346 result.isMatch = false;
9347 return returnObject ? result : false;
9350 if (isIgnored(input)) {
9351 if (typeof opts.onIgnore === 'function') {
9352 opts.onIgnore(result);
9354 result.isMatch = false;
9355 return returnObject ? result : false;
9358 if (typeof opts.onMatch === 'function') {
9359 opts.onMatch(result);
9361 return returnObject ? result : true;
9365 matcher.state = state;
9372 * Test `input` with the given `regex`. This is used by the main
9373 * `picomatch()` function to test the input string.
9376 * const picomatch = require('picomatch');
9377 * // picomatch.test(input, regex[, options]);
9379 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
9380 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
9382 * @param {String} `input` String to test.
9383 * @param {RegExp} `regex`
9384 * @return {Object} Returns an object with matching info.
9388 picomatch.test = (input, regex, options, { glob, posix } = {}) => {
9389 if (typeof input !== 'string') {
9390 throw new TypeError('Expected input to be a string');
9394 return { isMatch: false, output: '' };
9397 const opts = options || {};
9398 const format = opts.format || (posix ? utils.toPosixSlashes : null);
9399 let match = input === glob;
9400 let output = (match && format) ? format(input) : input;
9402 if (match === false) {
9403 output = format ? format(input) : input;
9404 match = output === glob;
9407 if (match === false || opts.capture === true) {
9408 if (opts.matchBase === true || opts.basename === true) {
9409 match = picomatch.matchBase(input, regex, options, posix);
9411 match = regex.exec(output);
9415 return { isMatch: Boolean(match), match, output };
9419 * Match the basename of a filepath.
9422 * const picomatch = require('picomatch');
9423 * // picomatch.matchBase(input, glob[, options]);
9424 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
9426 * @param {String} `input` String to test.
9427 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
9432 picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
9433 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
9434 return regex.test(path.basename(input));
9438 * Returns true if **any** of the given glob `patterns` match the specified `string`.
9441 * const picomatch = require('picomatch');
9442 * // picomatch.isMatch(string, patterns[, options]);
9444 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
9445 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
9447 * @param {String|Array} str The string to test.
9448 * @param {String|Array} patterns One or more glob patterns to use for matching.
9449 * @param {Object} [options] See available [options](#options).
9450 * @return {Boolean} Returns true if any patterns match `str`
9454 picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
9457 * Parse a glob pattern to create the source string for a regular
9461 * const picomatch = require('picomatch');
9462 * const result = picomatch.parse(pattern[, options]);
9464 * @param {String} `pattern`
9465 * @param {Object} `options`
9466 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
9470 picomatch.parse = (pattern, options) => {
9471 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
9472 return parse(pattern, { ...options, fastpaths: false });
9476 * Scan a glob pattern to separate the pattern into segments.
9479 * const picomatch = require('picomatch');
9480 * // picomatch.scan(input[, options]);
9482 * const result = picomatch.scan('!./foo/*.js');
9483 * console.log(result);
9485 * input: '!./foo/*.js',
9493 * isGlobstar: false,
9496 * @param {String} `input` Glob pattern to scan.
9497 * @param {Object} `options`
9498 * @return {Object} Returns an object with
9502 picomatch.scan = (input, options) => scan(input, options);
9505 * Create a regular expression from a parsed glob pattern.
9508 * const picomatch = require('picomatch');
9509 * const state = picomatch.parse('*.js');
9510 * // picomatch.compileRe(state[, options]);
9512 * console.log(picomatch.compileRe(state));
9513 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
9515 * @param {String} `state` The object returned from the `.parse` method.
9516 * @param {Object} `options`
9517 * @return {RegExp} Returns a regex created from the given pattern.
9521 picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
9522 if (returnOutput === true) {
9523 return parsed.output;
9526 const opts = options || {};
9527 const prepend = opts.contains ? '' : '^';
9528 const append = opts.contains ? '' : '$';
9530 let source = `${prepend}(?:${parsed.output})${append}`;
9531 if (parsed && parsed.negated === true) {
9532 source = `^(?!${source}).*$`;
9535 const regex = picomatch.toRegex(source, options);
9536 if (returnState === true) {
9537 regex.state = parsed;
9543 picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
9544 if (!input || typeof input !== 'string') {
9545 throw new TypeError('Expected a non-empty string');
9548 const opts = options || {};
9549 let parsed = { negated: false, fastpaths: true };
9553 if (input.startsWith('./')) {
9554 input = input.slice(2);
9555 prefix = parsed.prefix = './';
9558 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
9559 output = parse.fastpaths(input, options);
9562 if (output === undefined) {
9563 parsed = parse(input, options);
9564 parsed.prefix = prefix + (parsed.prefix || '');
9566 parsed.output = output;
9569 return picomatch.compileRe(parsed, options, returnOutput, returnState);
9573 * Create a regular expression from the given regex source string.
9576 * const picomatch = require('picomatch');
9577 * // picomatch.toRegex(source[, options]);
9579 * const { output } = picomatch.parse('*.js');
9580 * console.log(picomatch.toRegex(output));
9581 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
9583 * @param {String} `source` Regular expression source string.
9584 * @param {Object} `options`
9589 picomatch.toRegex = (source, options) => {
9591 const opts = options || {};
9592 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
9594 if (options && options.debug === true) throw err;
9600 * Picomatch constants.
9604 picomatch.constants = constants;
9607 * Expose "picomatch"
9610 module.exports = picomatch;
9615 /***/ (function(module, exports, __webpack_require__) {
9620 const utils = __webpack_require__(54);
9622 CHAR_ASTERISK, /* * */
9624 CHAR_BACKWARD_SLASH, /* \ */
9627 CHAR_EXCLAMATION_MARK, /* ! */
9628 CHAR_FORWARD_SLASH, /* / */
9629 CHAR_LEFT_CURLY_BRACE, /* { */
9630 CHAR_LEFT_PARENTHESES, /* ( */
9631 CHAR_LEFT_SQUARE_BRACKET, /* [ */
9633 CHAR_QUESTION_MARK, /* ? */
9634 CHAR_RIGHT_CURLY_BRACE, /* } */
9635 CHAR_RIGHT_PARENTHESES, /* ) */
9636 CHAR_RIGHT_SQUARE_BRACKET /* ] */
9637 } = __webpack_require__(55);
9639 const isPathSeparator = code => {
9640 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
9643 const depth = token => {
9644 if (token.isPrefix !== true) {
9645 token.depth = token.isGlobstar ? Infinity : 1;
9650 * Quickly scans a glob pattern and returns an object with a handful of
9651 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
9652 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
9655 * const pm = require('picomatch');
9656 * console.log(pm.scan('foo/bar/*.js'));
9657 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
9659 * @param {String} `str`
9660 * @param {Object} `options`
9661 * @return {Object} Returns an object with tokens and regex source string.
9665 const scan = (input, options) => {
9666 const opts = options || {};
9668 const length = input.length - 1;
9669 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
9678 let isBrace = false;
9679 let isBracket = false;
9681 let isExtglob = false;
9682 let isGlobstar = false;
9683 let braceEscaped = false;
9684 let backslashes = false;
9685 let negated = false;
9686 let finished = false;
9690 let token = { value: '', depth: 0, isGlob: false };
9692 const eos = () => index >= length;
9693 const peek = () => str.charCodeAt(index + 1);
9694 const advance = () => {
9696 return str.charCodeAt(++index);
9699 while (index < length) {
9703 if (code === CHAR_BACKWARD_SLASH) {
9704 backslashes = token.backslashes = true;
9707 if (code === CHAR_LEFT_CURLY_BRACE) {
9708 braceEscaped = true;
9713 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
9716 while (eos() !== true && (code = advance())) {
9717 if (code === CHAR_BACKWARD_SLASH) {
9718 backslashes = token.backslashes = true;
9723 if (code === CHAR_LEFT_CURLY_BRACE) {
9728 if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
9729 isBrace = token.isBrace = true;
9730 isGlob = token.isGlob = true;
9733 if (scanToEnd === true) {
9740 if (braceEscaped !== true && code === CHAR_COMMA) {
9741 isBrace = token.isBrace = true;
9742 isGlob = token.isGlob = true;
9745 if (scanToEnd === true) {
9752 if (code === CHAR_RIGHT_CURLY_BRACE) {
9756 braceEscaped = false;
9757 isBrace = token.isBrace = true;
9764 if (scanToEnd === true) {
9771 if (code === CHAR_FORWARD_SLASH) {
9772 slashes.push(index);
9774 token = { value: '', depth: 0, isGlob: false };
9776 if (finished === true) continue;
9777 if (prev === CHAR_DOT && index === (start + 1)) {
9782 lastIndex = index + 1;
9786 if (opts.noext !== true) {
9787 const isExtglobChar = code === CHAR_PLUS
9789 || code === CHAR_ASTERISK
9790 || code === CHAR_QUESTION_MARK
9791 || code === CHAR_EXCLAMATION_MARK;
9793 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
9794 isGlob = token.isGlob = true;
9795 isExtglob = token.isExtglob = true;
9798 if (scanToEnd === true) {
9799 while (eos() !== true && (code = advance())) {
9800 if (code === CHAR_BACKWARD_SLASH) {
9801 backslashes = token.backslashes = true;
9806 if (code === CHAR_RIGHT_PARENTHESES) {
9807 isGlob = token.isGlob = true;
9818 if (code === CHAR_ASTERISK) {
9819 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
9820 isGlob = token.isGlob = true;
9823 if (scanToEnd === true) {
9829 if (code === CHAR_QUESTION_MARK) {
9830 isGlob = token.isGlob = true;
9833 if (scanToEnd === true) {
9839 if (code === CHAR_LEFT_SQUARE_BRACKET) {
9840 while (eos() !== true && (next = advance())) {
9841 if (next === CHAR_BACKWARD_SLASH) {
9842 backslashes = token.backslashes = true;
9847 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
9848 isBracket = token.isBracket = true;
9849 isGlob = token.isGlob = true;
9852 if (scanToEnd === true) {
9860 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
9861 negated = token.negated = true;
9866 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
9867 isGlob = token.isGlob = true;
9869 if (scanToEnd === true) {
9870 while (eos() !== true && (code = advance())) {
9871 if (code === CHAR_LEFT_PARENTHESES) {
9872 backslashes = token.backslashes = true;
9877 if (code === CHAR_RIGHT_PARENTHESES) {
9887 if (isGlob === true) {
9890 if (scanToEnd === true) {
9898 if (opts.noext === true) {
9908 prefix = str.slice(0, start);
9909 str = str.slice(start);
9913 if (base && isGlob === true && lastIndex > 0) {
9914 base = str.slice(0, lastIndex);
9915 glob = str.slice(lastIndex);
9916 } else if (isGlob === true) {
9923 if (base && base !== '' && base !== '/' && base !== str) {
9924 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
9925 base = base.slice(0, -1);
9929 if (opts.unescape === true) {
9930 if (glob) glob = utils.removeBackslashes(glob);
9932 if (base && backslashes === true) {
9933 base = utils.removeBackslashes(base);
9951 if (opts.tokens === true) {
9953 if (!isPathSeparator(code)) {
9956 state.tokens = tokens;
9959 if (opts.parts === true || opts.tokens === true) {
9962 for (let idx = 0; idx < slashes.length; idx++) {
9963 const n = prevIndex ? prevIndex + 1 : start;
9964 const i = slashes[idx];
9965 const value = input.slice(n, i);
9967 if (idx === 0 && start !== 0) {
9968 tokens[idx].isPrefix = true;
9969 tokens[idx].value = prefix;
9971 tokens[idx].value = value;
9974 state.maxDepth += tokens[idx].depth;
9976 if (idx !== 0 || value !== '') {
9982 if (prevIndex && prevIndex + 1 < input.length) {
9983 const value = input.slice(prevIndex + 1);
9987 tokens[tokens.length - 1].value = value;
9988 depth(tokens[tokens.length - 1]);
9989 state.maxDepth += tokens[tokens.length - 1].depth;
9993 state.slashes = slashes;
9994 state.parts = parts;
10000 module.exports = scan;
10005 /***/ (function(module, exports, __webpack_require__) {
10010 const path = __webpack_require__(2);
10011 const win32 = process.platform === 'win32';
10014 REGEX_REMOVE_BACKSLASH,
10015 REGEX_SPECIAL_CHARS,
10016 REGEX_SPECIAL_CHARS_GLOBAL
10017 } = __webpack_require__(55);
10019 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
10020 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
10021 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
10022 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
10023 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
10025 exports.removeBackslashes = str => {
10026 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
10027 return match === '\\' ? '' : match;
10031 exports.supportsLookbehinds = () => {
10032 const segs = process.version.slice(1).split('.').map(Number);
10033 if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
10039 exports.isWindows = options => {
10040 if (options && typeof options.windows === 'boolean') {
10041 return options.windows;
10043 return win32 === true || path.sep === '\\';
10046 exports.escapeLast = (input, char, lastIdx) => {
10047 const idx = input.lastIndexOf(char, lastIdx);
10048 if (idx === -1) return input;
10049 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
10050 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
10053 exports.removePrefix = (input, state = {}) => {
10054 let output = input;
10055 if (output.startsWith('./')) {
10056 output = output.slice(2);
10057 state.prefix = './';
10062 exports.wrapOutput = (input, state = {}, options = {}) => {
10063 const prepend = options.contains ? '' : '^';
10064 const append = options.contains ? '' : '$';
10066 let output = `${prepend}(?:${input})${append}`;
10067 if (state.negated === true) {
10068 output = `(?:^(?!${output}).*$)`;
10076 /***/ (function(module, exports, __webpack_require__) {
10081 const path = __webpack_require__(2);
10082 const WIN_SLASH = '\\\\/';
10083 const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
10089 const DOT_LITERAL = '\\.';
10090 const PLUS_LITERAL = '\\+';
10091 const QMARK_LITERAL = '\\?';
10092 const SLASH_LITERAL = '\\/';
10093 const ONE_CHAR = '(?=.)';
10094 const QMARK = '[^/]';
10095 const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
10096 const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
10097 const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
10098 const NO_DOT = `(?!${DOT_LITERAL})`;
10099 const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
10100 const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
10101 const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
10102 const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
10103 const STAR = `${QMARK}*?`;
10105 const POSIX_CHARS = {
10124 * Windows glob regex
10127 const WINDOWS_CHARS = {
10130 SLASH_LITERAL: `[${WIN_SLASH}]`,
10131 QMARK: WIN_NO_SLASH,
10132 STAR: `${WIN_NO_SLASH}*?`,
10133 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
10134 NO_DOT: `(?!${DOT_LITERAL})`,
10135 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
10136 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
10137 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
10138 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
10139 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
10140 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
10144 * POSIX Bracket Regex
10147 const POSIX_REGEX_SOURCE = {
10148 alnum: 'a-zA-Z0-9',
10150 ascii: '\\x00-\\x7F',
10152 cntrl: '\\x00-\\x1F\\x7F',
10154 graph: '\\x21-\\x7E',
10156 print: '\\x20-\\x7E ',
10157 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
10158 space: ' \\t\\r\\n\\v\\f',
10160 word: 'A-Za-z0-9_',
10161 xdigit: 'A-Fa-f0-9'
10165 MAX_LENGTH: 1024 * 64,
10166 POSIX_REGEX_SOURCE,
10168 // regular expressions
10169 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
10170 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
10171 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
10172 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
10173 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
10174 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
10176 // Replace globs with equivalent patterns to reduce parsing time.
10184 CHAR_0: 48, /* 0 */
10185 CHAR_9: 57, /* 9 */
10188 CHAR_UPPERCASE_A: 65, /* A */
10189 CHAR_LOWERCASE_A: 97, /* a */
10190 CHAR_UPPERCASE_Z: 90, /* Z */
10191 CHAR_LOWERCASE_Z: 122, /* z */
10193 CHAR_LEFT_PARENTHESES: 40, /* ( */
10194 CHAR_RIGHT_PARENTHESES: 41, /* ) */
10196 CHAR_ASTERISK: 42, /* * */
10198 // Non-alphabetic chars.
10199 CHAR_AMPERSAND: 38, /* & */
10200 CHAR_AT: 64, /* @ */
10201 CHAR_BACKWARD_SLASH: 92, /* \ */
10202 CHAR_CARRIAGE_RETURN: 13, /* \r */
10203 CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
10204 CHAR_COLON: 58, /* : */
10205 CHAR_COMMA: 44, /* , */
10206 CHAR_DOT: 46, /* . */
10207 CHAR_DOUBLE_QUOTE: 34, /* " */
10208 CHAR_EQUAL: 61, /* = */
10209 CHAR_EXCLAMATION_MARK: 33, /* ! */
10210 CHAR_FORM_FEED: 12, /* \f */
10211 CHAR_FORWARD_SLASH: 47, /* / */
10212 CHAR_GRAVE_ACCENT: 96, /* ` */
10213 CHAR_HASH: 35, /* # */
10214 CHAR_HYPHEN_MINUS: 45, /* - */
10215 CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
10216 CHAR_LEFT_CURLY_BRACE: 123, /* { */
10217 CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
10218 CHAR_LINE_FEED: 10, /* \n */
10219 CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
10220 CHAR_PERCENT: 37, /* % */
10221 CHAR_PLUS: 43, /* + */
10222 CHAR_QUESTION_MARK: 63, /* ? */
10223 CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
10224 CHAR_RIGHT_CURLY_BRACE: 125, /* } */
10225 CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
10226 CHAR_SEMICOLON: 59, /* ; */
10227 CHAR_SINGLE_QUOTE: 39, /* ' */
10228 CHAR_SPACE: 32, /* */
10229 CHAR_TAB: 9, /* \t */
10230 CHAR_UNDERSCORE: 95, /* _ */
10231 CHAR_VERTICAL_LINE: 124, /* | */
10232 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
10237 * Create EXTGLOB_CHARS
10240 extglobChars(chars) {
10242 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
10243 '?': { type: 'qmark', open: '(?:', close: ')?' },
10244 '+': { type: 'plus', open: '(?:', close: ')+' },
10245 '*': { type: 'star', open: '(?:', close: ')*' },
10246 '@': { type: 'at', open: '(?:', close: ')' }
10251 * Create GLOB_CHARS
10255 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
10262 /***/ (function(module, exports, __webpack_require__) {
10267 const constants = __webpack_require__(55);
10268 const utils = __webpack_require__(54);
10276 POSIX_REGEX_SOURCE,
10277 REGEX_NON_SPECIAL_CHARS,
10278 REGEX_SPECIAL_CHARS_BACKREF,
10286 const expandRange = (args, options) => {
10287 if (typeof options.expandRange === 'function') {
10288 return options.expandRange(...args, options);
10292 const value = `[${args.join('-')}]`;
10295 /* eslint-disable-next-line no-new */
10298 return args.map(v => utils.escapeRegex(v)).join('..');
10305 * Create the message for a syntax error
10308 const syntaxError = (type, char) => {
10309 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
10313 * Parse the given input string.
10314 * @param {String} input
10315 * @param {Object} options
10319 const parse = (input, options) => {
10320 if (typeof input !== 'string') {
10321 throw new TypeError('Expected a string');
10324 input = REPLACEMENTS[input] || input;
10326 const opts = { ...options };
10327 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
10329 let len = input.length;
10331 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
10334 const bos = { type: 'bos', value: '', output: opts.prepend || '' };
10335 const tokens = [bos];
10337 const capture = opts.capture ? '' : '?:';
10338 const win32 = utils.isWindows(options);
10340 // create constants based on platform, for windows or posix
10341 const PLATFORM_CHARS = constants.globChars(win32);
10342 const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
10357 } = PLATFORM_CHARS;
10359 const globstar = (opts) => {
10360 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
10363 const nodot = opts.dot ? '' : NO_DOT;
10364 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
10365 let star = opts.bash === true ? globstar(opts) : STAR;
10367 if (opts.capture) {
10368 star = `(${star})`;
10371 // minimatch options support
10372 if (typeof opts.noext === 'boolean') {
10373 opts.noextglob = opts.noext;
10380 dot: opts.dot === true,
10394 input = utils.removePrefix(input, state);
10395 len = input.length;
10397 const extglobs = [];
10404 * Tokenizing helpers
10407 const eos = () => state.index === len - 1;
10408 const peek = state.peek = (n = 1) => input[state.index + n];
10409 const advance = state.advance = () => input[++state.index];
10410 const remaining = () => input.slice(state.index + 1);
10411 const consume = (value = '', num = 0) => {
10412 state.consumed += value;
10413 state.index += num;
10415 const append = token => {
10416 state.output += token.output != null ? token.output : token.value;
10417 consume(token.value);
10420 const negate = () => {
10423 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
10429 if (count % 2 === 0) {
10433 state.negated = true;
10438 const increment = type => {
10443 const decrement = type => {
10449 * Push tokens onto the tokens array. This helper speeds up
10450 * tokenizing by 1) helping us avoid backtracking as much as possible,
10451 * and 2) helping us avoid creating extra tokens when consecutive
10452 * characters are plain text. This improves performance and simplifies
10456 const push = tok => {
10457 if (prev.type === 'globstar') {
10458 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
10459 const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
10461 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
10462 state.output = state.output.slice(0, -prev.output.length);
10463 prev.type = 'star';
10465 prev.output = star;
10466 state.output += prev.output;
10470 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
10471 extglobs[extglobs.length - 1].inner += tok.value;
10474 if (tok.value || tok.output) append(tok);
10475 if (prev && prev.type === 'text' && tok.type === 'text') {
10476 prev.value += tok.value;
10477 prev.output = (prev.output || '') + tok.value;
10486 const extglobOpen = (type, value) => {
10487 const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
10490 token.parens = state.parens;
10491 token.output = state.output;
10492 const output = (opts.capture ? '(' : '') + token.open;
10494 increment('parens');
10495 push({ type, value, output: state.output ? '' : ONE_CHAR });
10496 push({ type: 'paren', extglob: true, value: advance(), output });
10497 extglobs.push(token);
10500 const extglobClose = token => {
10501 let output = token.close + (opts.capture ? ')' : '');
10503 if (token.type === 'negate') {
10504 let extglobStar = star;
10506 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
10507 extglobStar = globstar(opts);
10510 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
10511 output = token.close = `)$))${extglobStar}`;
10514 if (token.prev.type === 'bos' && eos()) {
10515 state.negatedExtglob = true;
10519 push({ type: 'paren', extglob: true, value, output });
10520 decrement('parens');
10527 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
10528 let backslashes = false;
10530 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
10531 if (first === '\\') {
10532 backslashes = true;
10536 if (first === '?') {
10538 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
10541 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
10543 return QMARK.repeat(chars.length);
10546 if (first === '.') {
10547 return DOT_LITERAL.repeat(chars.length);
10550 if (first === '*') {
10552 return esc + first + (rest ? star : '');
10556 return esc ? m : `\\${m}`;
10559 if (backslashes === true) {
10560 if (opts.unescape === true) {
10561 output = output.replace(/\\/g, '');
10563 output = output.replace(/\\+/g, m => {
10564 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
10569 if (output === input && opts.contains === true) {
10570 state.output = input;
10574 state.output = utils.wrapOutput(output, state, options);
10579 * Tokenize input until we reach end-of-string
10585 if (value === '\u0000') {
10590 * Escaped characters
10593 if (value === '\\') {
10594 const next = peek();
10596 if (next === '/' && opts.bash !== true) {
10600 if (next === '.' || next === ';') {
10606 push({ type: 'text', value });
10610 // collapse slashes to reduce potential for exploits
10611 const match = /^\\+/.exec(remaining());
10614 if (match && match[0].length > 2) {
10615 slashes = match[0].length;
10616 state.index += slashes;
10617 if (slashes % 2 !== 0) {
10622 if (opts.unescape === true) {
10623 value = advance() || '';
10625 value += advance() || '';
10628 if (state.brackets === 0) {
10629 push({ type: 'text', value });
10635 * If we're inside a regex character class, continue
10636 * until we reach the closing bracket.
10639 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
10640 if (opts.posix !== false && value === ':') {
10641 const inner = prev.value.slice(1);
10642 if (inner.includes('[')) {
10645 if (inner.includes(':')) {
10646 const idx = prev.value.lastIndexOf('[');
10647 const pre = prev.value.slice(0, idx);
10648 const rest = prev.value.slice(idx + 2);
10649 const posix = POSIX_REGEX_SOURCE[rest];
10651 prev.value = pre + posix;
10652 state.backtrack = true;
10655 if (!bos.output && tokens.indexOf(prev) === 1) {
10656 bos.output = ONE_CHAR;
10664 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
10665 value = `\\${value}`;
10668 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
10669 value = `\\${value}`;
10672 if (opts.posix === true && value === '!' && prev.value === '[') {
10676 prev.value += value;
10682 * If we're inside a quoted string, continue
10683 * until we reach the closing double quote.
10686 if (state.quotes === 1 && value !== '"') {
10687 value = utils.escapeRegex(value);
10688 prev.value += value;
10697 if (value === '"') {
10698 state.quotes = state.quotes === 1 ? 0 : 1;
10699 if (opts.keepQuotes === true) {
10700 push({ type: 'text', value });
10709 if (value === '(') {
10710 increment('parens');
10711 push({ type: 'paren', value });
10715 if (value === ')') {
10716 if (state.parens === 0 && opts.strictBrackets === true) {
10717 throw new SyntaxError(syntaxError('opening', '('));
10720 const extglob = extglobs[extglobs.length - 1];
10721 if (extglob && state.parens === extglob.parens + 1) {
10722 extglobClose(extglobs.pop());
10726 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
10727 decrement('parens');
10735 if (value === '[') {
10736 if (opts.nobracket === true || !remaining().includes(']')) {
10737 if (opts.nobracket !== true && opts.strictBrackets === true) {
10738 throw new SyntaxError(syntaxError('closing', ']'));
10741 value = `\\${value}`;
10743 increment('brackets');
10746 push({ type: 'bracket', value });
10750 if (value === ']') {
10751 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
10752 push({ type: 'text', value, output: `\\${value}` });
10756 if (state.brackets === 0) {
10757 if (opts.strictBrackets === true) {
10758 throw new SyntaxError(syntaxError('opening', '['));
10761 push({ type: 'text', value, output: `\\${value}` });
10765 decrement('brackets');
10767 const prevValue = prev.value.slice(1);
10768 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
10769 value = `/${value}`;
10772 prev.value += value;
10775 // when literal brackets are explicitly disabled
10776 // assume we should match with a regex character class
10777 if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
10781 const escaped = utils.escapeRegex(prev.value);
10782 state.output = state.output.slice(0, -prev.value.length);
10784 // when literal brackets are explicitly enabled
10785 // assume we should escape the brackets to match literal characters
10786 if (opts.literalBrackets === true) {
10787 state.output += escaped;
10788 prev.value = escaped;
10792 // when the user specifies nothing, try to match both
10793 prev.value = `(${capture}${escaped}|${prev.value})`;
10794 state.output += prev.value;
10802 if (value === '{' && opts.nobrace !== true) {
10803 increment('braces');
10809 outputIndex: state.output.length,
10810 tokensIndex: state.tokens.length
10818 if (value === '}') {
10819 const brace = braces[braces.length - 1];
10821 if (opts.nobrace === true || !brace) {
10822 push({ type: 'text', value, output: value });
10828 if (brace.dots === true) {
10829 const arr = tokens.slice();
10832 for (let i = arr.length - 1; i >= 0; i--) {
10834 if (arr[i].type === 'brace') {
10837 if (arr[i].type !== 'dots') {
10838 range.unshift(arr[i].value);
10842 output = expandRange(range, opts);
10843 state.backtrack = true;
10846 if (brace.comma !== true && brace.dots !== true) {
10847 const out = state.output.slice(0, brace.outputIndex);
10848 const toks = state.tokens.slice(brace.tokensIndex);
10849 brace.value = brace.output = '\\{';
10850 value = output = '\\}';
10851 state.output = out;
10852 for (const t of toks) {
10853 state.output += (t.output || t.value);
10857 push({ type: 'brace', value, output });
10858 decrement('braces');
10867 if (value === '|') {
10868 if (extglobs.length > 0) {
10869 extglobs[extglobs.length - 1].conditions++;
10871 push({ type: 'text', value });
10879 if (value === ',') {
10880 let output = value;
10882 const brace = braces[braces.length - 1];
10883 if (brace && stack[stack.length - 1] === 'braces') {
10884 brace.comma = true;
10888 push({ type: 'comma', value, output });
10896 if (value === '/') {
10897 // if the beginning of the glob is "./", advance the start
10898 // to the current index, and don't add the "./" characters
10899 // to the state. This greatly simplifies lookbehinds when
10900 // checking for BOS characters like "!" and "." (not "./")
10901 if (prev.type === 'dot' && state.index === state.start + 1) {
10902 state.start = state.index + 1;
10903 state.consumed = '';
10906 prev = bos; // reset "prev" to the first token
10910 push({ type: 'slash', value, output: SLASH_LITERAL });
10918 if (value === '.') {
10919 if (state.braces > 0 && prev.type === 'dot') {
10920 if (prev.value === '.') prev.output = DOT_LITERAL;
10921 const brace = braces[braces.length - 1];
10922 prev.type = 'dots';
10923 prev.output += value;
10924 prev.value += value;
10929 if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
10930 push({ type: 'text', value, output: DOT_LITERAL });
10934 push({ type: 'dot', value, output: DOT_LITERAL });
10942 if (value === '?') {
10943 const isGroup = prev && prev.value === '(';
10944 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
10945 extglobOpen('qmark', value);
10949 if (prev && prev.type === 'paren') {
10950 const next = peek();
10951 let output = value;
10953 if (next === '<' && !utils.supportsLookbehinds()) {
10954 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
10957 if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
10958 output = `\\${value}`;
10961 push({ type: 'text', value, output });
10965 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
10966 push({ type: 'qmark', value, output: QMARK_NO_DOT });
10970 push({ type: 'qmark', value, output: QMARK });
10978 if (value === '!') {
10979 if (opts.noextglob !== true && peek() === '(') {
10980 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
10981 extglobOpen('negate', value);
10986 if (opts.nonegate !== true && state.index === 0) {
10996 if (value === '+') {
10997 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
10998 extglobOpen('plus', value);
11002 if ((prev && prev.value === '(') || opts.regex === false) {
11003 push({ type: 'plus', value, output: PLUS_LITERAL });
11007 if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
11008 push({ type: 'plus', value });
11012 push({ type: 'plus', value: PLUS_LITERAL });
11020 if (value === '@') {
11021 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
11022 push({ type: 'at', extglob: true, value, output: '' });
11026 push({ type: 'text', value });
11034 if (value !== '*') {
11035 if (value === '$' || value === '^') {
11036 value = `\\${value}`;
11039 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
11042 state.index += match[0].length;
11045 push({ type: 'text', value });
11053 if (prev && (prev.type === 'globstar' || prev.star === true)) {
11054 prev.type = 'star';
11056 prev.value += value;
11057 prev.output = star;
11058 state.backtrack = true;
11059 state.globstar = true;
11064 let rest = remaining();
11065 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
11066 extglobOpen('star', value);
11070 if (prev.type === 'star') {
11071 if (opts.noglobstar === true) {
11076 const prior = prev.prev;
11077 const before = prior.prev;
11078 const isStart = prior.type === 'slash' || prior.type === 'bos';
11079 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
11081 if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
11082 push({ type: 'star', value, output: '' });
11086 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
11087 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
11088 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
11089 push({ type: 'star', value, output: '' });
11093 // strip consecutive `/**/`
11094 while (rest.slice(0, 3) === '/**') {
11095 const after = input[state.index + 4];
11096 if (after && after !== '/') {
11099 rest = rest.slice(3);
11103 if (prior.type === 'bos' && eos()) {
11104 prev.type = 'globstar';
11105 prev.value += value;
11106 prev.output = globstar(opts);
11107 state.output = prev.output;
11108 state.globstar = true;
11113 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
11114 state.output = state.output.slice(0, -(prior.output + prev.output).length);
11115 prior.output = `(?:${prior.output}`;
11117 prev.type = 'globstar';
11118 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
11119 prev.value += value;
11120 state.globstar = true;
11121 state.output += prior.output + prev.output;
11126 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
11127 const end = rest[1] !== void 0 ? '|$' : '';
11129 state.output = state.output.slice(0, -(prior.output + prev.output).length);
11130 prior.output = `(?:${prior.output}`;
11132 prev.type = 'globstar';
11133 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
11134 prev.value += value;
11136 state.output += prior.output + prev.output;
11137 state.globstar = true;
11139 consume(value + advance());
11141 push({ type: 'slash', value: '/', output: '' });
11145 if (prior.type === 'bos' && rest[0] === '/') {
11146 prev.type = 'globstar';
11147 prev.value += value;
11148 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
11149 state.output = prev.output;
11150 state.globstar = true;
11151 consume(value + advance());
11152 push({ type: 'slash', value: '/', output: '' });
11156 // remove single star from output
11157 state.output = state.output.slice(0, -prev.output.length);
11159 // reset previous token to globstar
11160 prev.type = 'globstar';
11161 prev.output = globstar(opts);
11162 prev.value += value;
11164 // reset output with globstar
11165 state.output += prev.output;
11166 state.globstar = true;
11171 const token = { type: 'star', value, output: star };
11173 if (opts.bash === true) {
11174 token.output = '.*?';
11175 if (prev.type === 'bos' || prev.type === 'slash') {
11176 token.output = nodot + token.output;
11182 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
11183 token.output = value;
11188 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
11189 if (prev.type === 'dot') {
11190 state.output += NO_DOT_SLASH;
11191 prev.output += NO_DOT_SLASH;
11193 } else if (opts.dot === true) {
11194 state.output += NO_DOTS_SLASH;
11195 prev.output += NO_DOTS_SLASH;
11198 state.output += nodot;
11199 prev.output += nodot;
11202 if (peek() !== '*') {
11203 state.output += ONE_CHAR;
11204 prev.output += ONE_CHAR;
11211 while (state.brackets > 0) {
11212 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
11213 state.output = utils.escapeLast(state.output, '[');
11214 decrement('brackets');
11217 while (state.parens > 0) {
11218 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
11219 state.output = utils.escapeLast(state.output, '(');
11220 decrement('parens');
11223 while (state.braces > 0) {
11224 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
11225 state.output = utils.escapeLast(state.output, '{');
11226 decrement('braces');
11229 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
11230 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
11233 // rebuild the output if we had to backtrack at any point
11234 if (state.backtrack === true) {
11237 for (const token of state.tokens) {
11238 state.output += token.output != null ? token.output : token.value;
11240 if (token.suffix) {
11241 state.output += token.suffix;
11250 * Fast paths for creating regular expressions for common glob patterns.
11251 * This can significantly speed up processing and has very little downside
11252 * impact when none of the fast paths match.
11255 parse.fastpaths = (input, options) => {
11256 const opts = { ...options };
11257 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
11258 const len = input.length;
11260 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
11263 input = REPLACEMENTS[input] || input;
11264 const win32 = utils.isWindows(options);
11266 // create constants based on platform, for windows or posix
11277 } = constants.globChars(win32);
11279 const nodot = opts.dot ? NO_DOTS : NO_DOT;
11280 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
11281 const capture = opts.capture ? '' : '?:';
11282 const state = { negated: false, prefix: '' };
11283 let star = opts.bash === true ? '.*?' : STAR;
11285 if (opts.capture) {
11286 star = `(${star})`;
11289 const globstar = (opts) => {
11290 if (opts.noglobstar === true) return star;
11291 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
11294 const create = str => {
11297 return `${nodot}${ONE_CHAR}${star}`;
11300 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
11303 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
11306 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
11309 return nodot + globstar(opts);
11312 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
11315 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
11318 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
11321 const match = /^(.*?)\.(\w+)$/.exec(str);
11322 if (!match) return;
11324 const source = create(match[1]);
11325 if (!source) return;
11327 return source + DOT_LITERAL + match[2];
11332 const output = utils.removePrefix(input, state);
11333 let source = create(output);
11335 if (source && opts.strictSlashes !== true) {
11336 source += `${SLASH_LITERAL}?`;
11342 module.exports = parse;
11347 /***/ (function(module, exports, __webpack_require__) {
11349 const assert = __webpack_require__(58)
11350 const path = __webpack_require__(2)
11351 const fs = __webpack_require__(42)
11352 let glob = undefined
11354 glob = __webpack_require__(59)
11356 // treat glob as optional.
11359 const defaultGlobOpts = {
11364 // for EMFILE handling
11367 const isWindows = (process.platform === "win32")
11369 const defaults = options => {
11378 methods.forEach(m => {
11379 options[m] = options[m] || fs[m]
11381 options[m] = options[m] || fs[m]
11384 options.maxBusyTries = options.maxBusyTries || 3
11385 options.emfileWait = options.emfileWait || 1000
11386 if (options.glob === false) {
11387 options.disableGlob = true
11389 if (options.disableGlob !== true && glob === undefined) {
11390 throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')
11392 options.disableGlob = options.disableGlob || false
11393 options.glob = options.glob || defaultGlobOpts
11396 const rimraf = (p, options, cb) => {
11397 if (typeof options === 'function') {
11402 assert(p, 'rimraf: missing path')
11403 assert.equal(typeof p, 'string', 'rimraf: path should be a string')
11404 assert.equal(typeof cb, 'function', 'rimraf: callback function required')
11405 assert(options, 'rimraf: invalid options argument provided')
11406 assert.equal(typeof options, 'object', 'rimraf: options should be object')
11411 let errState = null
11414 const next = (er) => {
11415 errState = errState || er
11420 const afterGlob = (er, results) => {
11428 results.forEach(p => {
11429 const CB = (er) => {
11431 if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") &&
11432 busyTries < options.maxBusyTries) {
11434 // try again, with the same exact callback as this one.
11435 return setTimeout(() => rimraf_(p, options, CB), busyTries * 100)
11438 // this one won't happen if graceful-fs is used.
11439 if (er.code === "EMFILE" && timeout < options.emfileWait) {
11440 return setTimeout(() => rimraf_(p, options, CB), timeout ++)
11444 if (er.code === "ENOENT") er = null
11450 rimraf_(p, options, CB)
11454 if (options.disableGlob || !glob.hasMagic(p))
11455 return afterGlob(null, [p])
11457 options.lstat(p, (er, stat) => {
11459 return afterGlob(null, [p])
11461 glob(p, options.glob, afterGlob)
11466 // Two possible strategies.
11467 // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
11468 // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
11470 // Both result in an extra syscall when you guess wrong. However, there
11471 // are likely far more normal files in the world than directories. This
11472 // is based on the assumption that a the average number of files per
11473 // directory is >= 1.
11475 // If anyone ever complains about this, then I guess the strategy could
11476 // be made configurable somehow. But until then, YAGNI.
11477 const rimraf_ = (p, options, cb) => {
11480 assert(typeof cb === 'function')
11482 // sunos lets the root user unlink directories, which is... weird.
11483 // so we have to lstat here and make sure it's not a dir.
11484 options.lstat(p, (er, st) => {
11485 if (er && er.code === "ENOENT")
11488 // Windows can EPERM on stat. Life is suffering.
11489 if (er && er.code === "EPERM" && isWindows)
11490 fixWinEPERM(p, options, er, cb)
11492 if (st && st.isDirectory())
11493 return rmdir(p, options, er, cb)
11495 options.unlink(p, er => {
11497 if (er.code === "ENOENT")
11499 if (er.code === "EPERM")
11501 ? fixWinEPERM(p, options, er, cb)
11502 : rmdir(p, options, er, cb)
11503 if (er.code === "EISDIR")
11504 return rmdir(p, options, er, cb)
11511 const fixWinEPERM = (p, options, er, cb) => {
11514 assert(typeof cb === 'function')
11516 options.chmod(p, 0o666, er2 => {
11518 cb(er2.code === "ENOENT" ? null : er)
11520 options.stat(p, (er3, stats) => {
11522 cb(er3.code === "ENOENT" ? null : er)
11523 else if (stats.isDirectory())
11524 rmdir(p, options, er, cb)
11526 options.unlink(p, cb)
11531 const fixWinEPERMSync = (p, options, er) => {
11536 options.chmodSync(p, 0o666)
11538 if (er2.code === "ENOENT")
11546 stats = options.statSync(p)
11548 if (er3.code === "ENOENT")
11554 if (stats.isDirectory())
11555 rmdirSync(p, options, er)
11557 options.unlinkSync(p)
11560 const rmdir = (p, options, originalEr, cb) => {
11563 assert(typeof cb === 'function')
11565 // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
11566 // if we guessed wrong, and it's not a directory, then
11567 // raise the original error.
11568 options.rmdir(p, er => {
11569 if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
11570 rmkids(p, options, cb)
11571 else if (er && er.code === "ENOTDIR")
11578 const rmkids = (p, options, cb) => {
11581 assert(typeof cb === 'function')
11583 options.readdir(p, (er, files) => {
11586 let n = files.length
11588 return options.rmdir(p, cb)
11590 files.forEach(f => {
11591 rimraf(path.join(p, f), options, er => {
11595 return cb(errState = er)
11597 options.rmdir(p, cb)
11603 // this looks simpler, and is strictly *faster*, but will
11604 // tie up the JavaScript thread and fail on excessively
11605 // deep directory trees.
11606 const rimrafSync = (p, options) => {
11607 options = options || {}
11610 assert(p, 'rimraf: missing path')
11611 assert.equal(typeof p, 'string', 'rimraf: path should be a string')
11612 assert(options, 'rimraf: missing options')
11613 assert.equal(typeof options, 'object', 'rimraf: options should be object')
11617 if (options.disableGlob || !glob.hasMagic(p)) {
11621 options.lstatSync(p)
11624 results = glob.sync(p, options.glob)
11628 if (!results.length)
11631 for (let i = 0; i < results.length; i++) {
11632 const p = results[i]
11636 st = options.lstatSync(p)
11638 if (er.code === "ENOENT")
11641 // Windows can EPERM on stat. Life is suffering.
11642 if (er.code === "EPERM" && isWindows)
11643 fixWinEPERMSync(p, options, er)
11647 // sunos lets the root user unlink directories, which is... weird.
11648 if (st && st.isDirectory())
11649 rmdirSync(p, options, null)
11651 options.unlinkSync(p)
11653 if (er.code === "ENOENT")
11655 if (er.code === "EPERM")
11656 return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
11657 if (er.code !== "EISDIR")
11660 rmdirSync(p, options, er)
11665 const rmdirSync = (p, options, originalEr) => {
11670 options.rmdirSync(p)
11672 if (er.code === "ENOENT")
11674 if (er.code === "ENOTDIR")
11676 if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
11677 rmkidsSync(p, options)
11681 const rmkidsSync = (p, options) => {
11684 options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options))
11686 // We only end up here once we got ENOTEMPTY at least once, and
11687 // at this point, we are guaranteed to have removed all the kids.
11688 // So, we know that it won't be ENOENT or ENOTDIR or anything else.
11689 // try really hard to delete stuff on windows, because it has a
11690 // PROFOUNDLY annoying habit of not closing handles promptly when
11691 // files are deleted, resulting in spurious ENOTEMPTY errors.
11692 const retries = isWindows ? 100 : 1
11697 const ret = options.rmdirSync(p, options)
11701 if (++i < retries && threw)
11707 module.exports = rimraf
11708 rimraf.sync = rimrafSync
11713 /***/ (function(module, exports) {
11715 module.exports = require("assert");
11719 /***/ (function(module, exports, __webpack_require__) {
11723 // 1. Get the minimatch set
11724 // 2. For each pattern in the set, PROCESS(pattern, false)
11725 // 3. Store matches per-set, then uniq them
11727 // PROCESS(pattern, inGlobStar)
11728 // Get the first [n] items from pattern that are all strings
11729 // Join these together. This is PREFIX.
11730 // If there is no more remaining, then stat(PREFIX) and
11731 // add to matches if it succeeds. END.
11733 // If inGlobStar and PREFIX is symlink and points to dir
11734 // set ENTRIES = []
11735 // else readdir(PREFIX) as ENTRIES
11739 // If pattern[n] is GLOBSTAR
11740 // // handle the case where the globstar match is empty
11741 // // by pruning it out, and testing the resulting pattern
11742 // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
11743 // // handle other cases.
11744 // for ENTRY in ENTRIES (not dotfiles)
11745 // // attach globstar + tail onto the entry
11746 // // Mark that this entry is a globstar match
11747 // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
11749 // else // not globstar
11750 // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
11751 // Test ENTRY against pattern[n]
11752 // If fails, continue
11753 // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
11756 // Cache all stats and readdirs results to minimize syscall. Since all
11757 // we ever care about is existence and directory-ness, we can just keep
11758 // `true` for files, and [children,...] for directories, or `false` for
11759 // things that don't exist.
11761 module.exports = glob
11763 var fs = __webpack_require__(42)
11764 var rp = __webpack_require__(60)
11765 var minimatch = __webpack_require__(62)
11766 var Minimatch = minimatch.Minimatch
11767 var inherits = __webpack_require__(66)
11768 var EE = __webpack_require__(68).EventEmitter
11769 var path = __webpack_require__(2)
11770 var assert = __webpack_require__(58)
11771 var isAbsolute = __webpack_require__(69)
11772 var globSync = __webpack_require__(70)
11773 var common = __webpack_require__(71)
11774 var alphasort = common.alphasort
11775 var alphasorti = common.alphasorti
11776 var setopts = common.setopts
11777 var ownProp = common.ownProp
11778 var inflight = __webpack_require__(72)
11779 var util = __webpack_require__(50)
11780 var childrenIgnored = common.childrenIgnored
11781 var isIgnored = common.isIgnored
11783 var once = __webpack_require__(74)
11785 function glob (pattern, options, cb) {
11786 if (typeof options === 'function') cb = options, options = {}
11787 if (!options) options = {}
11789 if (options.sync) {
11791 throw new TypeError('callback provided to sync glob')
11792 return globSync(pattern, options)
11795 return new Glob(pattern, options, cb)
11798 glob.sync = globSync
11799 var GlobSync = glob.GlobSync = globSync.GlobSync
11804 function extend (origin, add) {
11805 if (add === null || typeof add !== 'object') {
11809 var keys = Object.keys(add)
11810 var i = keys.length
11812 origin[keys[i]] = add[keys[i]]
11817 glob.hasMagic = function (pattern, options_) {
11818 var options = extend({}, options_)
11819 options.noprocess = true
11821 var g = new Glob(pattern, options)
11822 var set = g.minimatch.set
11827 if (set.length > 1)
11830 for (var j = 0; j < set[0].length; j++) {
11831 if (typeof set[0][j] !== 'string')
11840 function Glob (pattern, options, cb) {
11841 if (typeof options === 'function') {
11846 if (options && options.sync) {
11848 throw new TypeError('callback provided to sync glob')
11849 return new GlobSync(pattern, options)
11852 if (!(this instanceof Glob))
11853 return new Glob(pattern, options, cb)
11855 setopts(this, pattern, options)
11856 this._didRealPath = false
11858 // process each pattern in the minimatch set
11859 var n = this.minimatch.set.length
11861 // The matches are stored as {<filename>: true,...} so that
11862 // duplicates are automagically pruned.
11863 // Later, we do an Object.keys() on these.
11864 // Keep them as a list so we can fill in when nonull is set.
11865 this.matches = new Array(n)
11867 if (typeof cb === 'function') {
11869 this.on('error', cb)
11870 this.on('end', function (matches) {
11876 this._processing = 0
11878 this._emitQueue = []
11879 this._processQueue = []
11880 this.paused = false
11882 if (this.noprocess)
11889 for (var i = 0; i < n; i ++) {
11890 this._process(this.minimatch.set[i], i, false, done)
11896 if (self._processing <= 0) {
11898 process.nextTick(function () {
11908 Glob.prototype._finish = function () {
11909 assert(this instanceof Glob)
11913 if (this.realpath && !this._didRealpath)
11914 return this._realpath()
11916 common.finish(this)
11917 this.emit('end', this.found)
11920 Glob.prototype._realpath = function () {
11921 if (this._didRealpath)
11924 this._didRealpath = true
11926 var n = this.matches.length
11928 return this._finish()
11931 for (var i = 0; i < this.matches.length; i++)
11932 this._realpathSet(i, next)
11940 Glob.prototype._realpathSet = function (index, cb) {
11941 var matchset = this.matches[index]
11945 var found = Object.keys(matchset)
11947 var n = found.length
11952 var set = this.matches[index] = Object.create(null)
11953 found.forEach(function (p, i) {
11954 // If there's a problem with the stat, then it means that
11955 // one or more of the links in the realpath couldn't be
11956 // resolved. just return the abs value in that case.
11957 p = self._makeAbs(p)
11958 rp.realpath(p, self.realpathCache, function (er, real) {
11961 else if (er.syscall === 'stat')
11964 self.emit('error', er) // srsly wtf right here
11967 self.matches[index] = set
11974 Glob.prototype._mark = function (p) {
11975 return common.mark(this, p)
11978 Glob.prototype._makeAbs = function (f) {
11979 return common.makeAbs(this, f)
11982 Glob.prototype.abort = function () {
11983 this.aborted = true
11987 Glob.prototype.pause = function () {
11988 if (!this.paused) {
11994 Glob.prototype.resume = function () {
11996 this.emit('resume')
11997 this.paused = false
11998 if (this._emitQueue.length) {
11999 var eq = this._emitQueue.slice(0)
12000 this._emitQueue.length = 0
12001 for (var i = 0; i < eq.length; i ++) {
12003 this._emitMatch(e[0], e[1])
12006 if (this._processQueue.length) {
12007 var pq = this._processQueue.slice(0)
12008 this._processQueue.length = 0
12009 for (var i = 0; i < pq.length; i ++) {
12012 this._process(p[0], p[1], p[2], p[3])
12018 Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
12019 assert(this instanceof Glob)
12020 assert(typeof cb === 'function')
12027 this._processQueue.push([pattern, index, inGlobStar, cb])
12031 //console.error('PROCESS %d', this._processing, pattern)
12033 // Get the first [n] parts of pattern that are all strings.
12035 while (typeof pattern[n] === 'string') {
12038 // now n is the index of the first one that is *not* a string.
12040 // see if there's anything else
12043 // if not, then this is rather simple
12044 case pattern.length:
12045 this._processSimple(pattern.join('/'), index, cb)
12049 // pattern *starts* with some non-trivial item.
12050 // going to readdir(cwd), but not include the prefix in matches.
12055 // pattern has some string bits in the front.
12056 // whatever it starts with, whether that's 'absolute' like /foo/bar,
12057 // or 'relative' like '../baz'
12058 prefix = pattern.slice(0, n).join('/')
12062 var remain = pattern.slice(n)
12064 // get the list of entries.
12066 if (prefix === null)
12068 else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
12069 if (!prefix || !isAbsolute(prefix))
12070 prefix = '/' + prefix
12075 var abs = this._makeAbs(read)
12077 //if ignored, skip _processing
12078 if (childrenIgnored(this, read))
12081 var isGlobStar = remain[0] === minimatch.GLOBSTAR
12083 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
12085 this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
12088 Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
12090 this._readdir(abs, inGlobStar, function (er, entries) {
12091 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
12095 Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
12097 // if the abs isn't a dir, then nothing can match!
12101 // It will only match dot entries if it starts with a dot, or if
12102 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
12104 var negate = !!this.minimatch.negate
12105 var rawGlob = pn._glob
12106 var dotOk = this.dot || rawGlob.charAt(0) === '.'
12108 var matchedEntries = []
12109 for (var i = 0; i < entries.length; i++) {
12111 if (e.charAt(0) !== '.' || dotOk) {
12113 if (negate && !prefix) {
12119 matchedEntries.push(e)
12123 //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
12125 var len = matchedEntries.length
12126 // If there are no matched entries, then nothing matches.
12130 // if this is the last remaining pattern bit, then no need for
12131 // an additional stat *unless* the user has specified mark or
12132 // stat explicitly. We know they exist, since readdir returned
12135 if (remain.length === 1 && !this.mark && !this.stat) {
12136 if (!this.matches[index])
12137 this.matches[index] = Object.create(null)
12139 for (var i = 0; i < len; i ++) {
12140 var e = matchedEntries[i]
12142 if (prefix !== '/')
12143 e = prefix + '/' + e
12148 if (e.charAt(0) === '/' && !this.nomount) {
12149 e = path.join(this.root, e)
12151 this._emitMatch(index, e)
12153 // This was the last one, and no stats were needed
12157 // now test all matched entries as stand-ins for that part
12160 for (var i = 0; i < len; i ++) {
12161 var e = matchedEntries[i]
12164 if (prefix !== '/')
12165 e = prefix + '/' + e
12169 this._process([e].concat(remain), index, inGlobStar, cb)
12174 Glob.prototype._emitMatch = function (index, e) {
12178 if (isIgnored(this, e))
12182 this._emitQueue.push([index, e])
12186 var abs = isAbsolute(e) ? e : this._makeAbs(e)
12194 if (this.matches[index][e])
12198 var c = this.cache[abs]
12199 if (c === 'DIR' || Array.isArray(c))
12203 this.matches[index][e] = true
12205 var st = this.statCache[abs]
12207 this.emit('stat', e, st)
12209 this.emit('match', e)
12212 Glob.prototype._readdirInGlobStar = function (abs, cb) {
12216 // follow all symlinked directories forever
12217 // just proceed as if this is a non-globstar situation
12219 return this._readdir(abs, false, cb)
12221 var lstatkey = 'lstat\0' + abs
12223 var lstatcb = inflight(lstatkey, lstatcb_)
12226 fs.lstat(abs, lstatcb)
12228 function lstatcb_ (er, lstat) {
12229 if (er && er.code === 'ENOENT')
12232 var isSym = lstat && lstat.isSymbolicLink()
12233 self.symlinks[abs] = isSym
12235 // If it's not a symlink or a dir, then it's definitely a regular file.
12236 // don't bother doing a readdir in that case.
12237 if (!isSym && lstat && !lstat.isDirectory()) {
12238 self.cache[abs] = 'FILE'
12241 self._readdir(abs, false, cb)
12245 Glob.prototype._readdir = function (abs, inGlobStar, cb) {
12249 cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
12253 //console.error('RD %j %j', +inGlobStar, abs)
12254 if (inGlobStar && !ownProp(this.symlinks, abs))
12255 return this._readdirInGlobStar(abs, cb)
12257 if (ownProp(this.cache, abs)) {
12258 var c = this.cache[abs]
12259 if (!c || c === 'FILE')
12262 if (Array.isArray(c))
12267 fs.readdir(abs, readdirCb(this, abs, cb))
12270 function readdirCb (self, abs, cb) {
12271 return function (er, entries) {
12273 self._readdirError(abs, er, cb)
12275 self._readdirEntries(abs, entries, cb)
12279 Glob.prototype._readdirEntries = function (abs, entries, cb) {
12283 // if we haven't asked to stat everything, then just
12284 // assume that everything in there exists, so we can avoid
12285 // having to stat it a second time.
12286 if (!this.mark && !this.stat) {
12287 for (var i = 0; i < entries.length; i ++) {
12293 this.cache[e] = true
12297 this.cache[abs] = entries
12298 return cb(null, entries)
12301 Glob.prototype._readdirError = function (f, er, cb) {
12305 // handle errors, and cache the information
12307 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
12308 case 'ENOTDIR': // totally normal. means it *does* exist.
12309 var abs = this._makeAbs(f)
12310 this.cache[abs] = 'FILE'
12311 if (abs === this.cwdAbs) {
12312 var error = new Error(er.code + ' invalid cwd ' + this.cwd)
12313 error.path = this.cwd
12314 error.code = er.code
12315 this.emit('error', error)
12320 case 'ENOENT': // not terribly unusual
12322 case 'ENAMETOOLONG':
12324 this.cache[this._makeAbs(f)] = false
12327 default: // some unusual error. Treat as failure.
12328 this.cache[this._makeAbs(f)] = false
12330 this.emit('error', er)
12331 // If the error is handled, then we abort
12332 // if not, we threw out of here
12336 console.error('glob error', er)
12343 Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
12345 this._readdir(abs, inGlobStar, function (er, entries) {
12346 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
12351 Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
12352 //console.error('pgs2', prefix, remain[0], entries)
12354 // no entries means not a dir, so it can never have matches
12355 // foo.txt/** doesn't match foo.txt
12359 // test without the globstar, and with every child both below
12360 // and replacing the globstar.
12361 var remainWithoutGlobStar = remain.slice(1)
12362 var gspref = prefix ? [ prefix ] : []
12363 var noGlobStar = gspref.concat(remainWithoutGlobStar)
12365 // the noGlobStar pattern exits the inGlobStar state
12366 this._process(noGlobStar, index, false, cb)
12368 var isSym = this.symlinks[abs]
12369 var len = entries.length
12371 // If it's a symlink, and we're in a globstar, then stop
12372 if (isSym && inGlobStar)
12375 for (var i = 0; i < len; i++) {
12377 if (e.charAt(0) === '.' && !this.dot)
12380 // these two cases enter the inGlobStar state
12381 var instead = gspref.concat(entries[i], remainWithoutGlobStar)
12382 this._process(instead, index, true, cb)
12384 var below = gspref.concat(entries[i], remain)
12385 this._process(below, index, true, cb)
12391 Glob.prototype._processSimple = function (prefix, index, cb) {
12392 // XXX review this. Shouldn't it be doing the mounting etc
12393 // before doing stat? kinda weird?
12395 this._stat(prefix, function (er, exists) {
12396 self._processSimple2(prefix, index, er, exists, cb)
12399 Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
12401 //console.error('ps2', prefix, exists)
12403 if (!this.matches[index])
12404 this.matches[index] = Object.create(null)
12406 // If it doesn't exist, then just mark the lack of results
12410 if (prefix && isAbsolute(prefix) && !this.nomount) {
12411 var trail = /[\/\\]$/.test(prefix)
12412 if (prefix.charAt(0) === '/') {
12413 prefix = path.join(this.root, prefix)
12415 prefix = path.resolve(this.root, prefix)
12421 if (process.platform === 'win32')
12422 prefix = prefix.replace(/\\/g, '/')
12424 // Mark this as a match
12425 this._emitMatch(index, prefix)
12429 // Returns either 'DIR', 'FILE', or false
12430 Glob.prototype._stat = function (f, cb) {
12431 var abs = this._makeAbs(f)
12432 var needDir = f.slice(-1) === '/'
12434 if (f.length > this.maxLength)
12437 if (!this.stat && ownProp(this.cache, abs)) {
12438 var c = this.cache[abs]
12440 if (Array.isArray(c))
12443 // It exists, but maybe not how we need it
12444 if (!needDir || c === 'DIR')
12447 if (needDir && c === 'FILE')
12450 // otherwise we have to stat, because maybe c=true
12451 // if we know it exists, but not what it is.
12455 var stat = this.statCache[abs]
12456 if (stat !== undefined) {
12457 if (stat === false)
12458 return cb(null, stat)
12460 var type = stat.isDirectory() ? 'DIR' : 'FILE'
12461 if (needDir && type === 'FILE')
12464 return cb(null, type, stat)
12469 var statcb = inflight('stat\0' + abs, lstatcb_)
12471 fs.lstat(abs, statcb)
12473 function lstatcb_ (er, lstat) {
12474 if (lstat && lstat.isSymbolicLink()) {
12475 // If it's a symlink, then treat it as the target, unless
12476 // the target does not exist, then treat it as a file.
12477 return fs.stat(abs, function (er, stat) {
12479 self._stat2(f, abs, null, lstat, cb)
12481 self._stat2(f, abs, er, stat, cb)
12484 self._stat2(f, abs, er, lstat, cb)
12489 Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
12490 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
12491 this.statCache[abs] = false
12495 var needDir = f.slice(-1) === '/'
12496 this.statCache[abs] = stat
12498 if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
12499 return cb(null, false, stat)
12503 c = stat.isDirectory() ? 'DIR' : 'FILE'
12504 this.cache[abs] = this.cache[abs] || c
12506 if (needDir && c === 'FILE')
12509 return cb(null, c, stat)
12515 /***/ (function(module, exports, __webpack_require__) {
12517 module.exports = realpath
12518 realpath.realpath = realpath
12519 realpath.sync = realpathSync
12520 realpath.realpathSync = realpathSync
12521 realpath.monkeypatch = monkeypatch
12522 realpath.unmonkeypatch = unmonkeypatch
12524 var fs = __webpack_require__(42)
12525 var origRealpath = fs.realpath
12526 var origRealpathSync = fs.realpathSync
12528 var version = process.version
12529 var ok = /^v[0-5]\./.test(version)
12530 var old = __webpack_require__(61)
12532 function newError (er) {
12533 return er && er.syscall === 'realpath' && (
12534 er.code === 'ELOOP' ||
12535 er.code === 'ENOMEM' ||
12536 er.code === 'ENAMETOOLONG'
12540 function realpath (p, cache, cb) {
12542 return origRealpath(p, cache, cb)
12545 if (typeof cache === 'function') {
12549 origRealpath(p, cache, function (er, result) {
12550 if (newError(er)) {
12551 old.realpath(p, cache, cb)
12558 function realpathSync (p, cache) {
12560 return origRealpathSync(p, cache)
12564 return origRealpathSync(p, cache)
12566 if (newError(er)) {
12567 return old.realpathSync(p, cache)
12574 function monkeypatch () {
12575 fs.realpath = realpath
12576 fs.realpathSync = realpathSync
12579 function unmonkeypatch () {
12580 fs.realpath = origRealpath
12581 fs.realpathSync = origRealpathSync
12587 /***/ (function(module, exports, __webpack_require__) {
12589 // Copyright Joyent, Inc. and other Node contributors.
12591 // Permission is hereby granted, free of charge, to any person obtaining a
12592 // copy of this software and associated documentation files (the
12593 // "Software"), to deal in the Software without restriction, including
12594 // without limitation the rights to use, copy, modify, merge, publish,
12595 // distribute, sublicense, and/or sell copies of the Software, and to permit
12596 // persons to whom the Software is furnished to do so, subject to the
12597 // following conditions:
12599 // The above copyright notice and this permission notice shall be included
12600 // in all copies or substantial portions of the Software.
12602 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12603 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12604 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12605 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12606 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12607 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12608 // USE OR OTHER DEALINGS IN THE SOFTWARE.
12610 var pathModule = __webpack_require__(2);
12611 var isWindows = process.platform === 'win32';
12612 var fs = __webpack_require__(42);
12614 // JavaScript implementation of realpath, ported from node pre-v6
12616 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
12618 function rethrow() {
12619 // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
12620 // is fairly slow to generate.
12623 var backtrace = new Error;
12624 callback = debugCallback;
12626 callback = missingCallback;
12630 function debugCallback(err) {
12632 backtrace.message = err.message;
12634 missingCallback(err);
12638 function missingCallback(err) {
12640 if (process.throwDeprecation)
12641 throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
12642 else if (!process.noDeprecation) {
12643 var msg = 'fs: missing callback ' + (err.stack || err.message);
12644 if (process.traceDeprecation)
12645 console.trace(msg);
12647 console.error(msg);
12653 function maybeCallback(cb) {
12654 return typeof cb === 'function' ? cb : rethrow();
12657 var normalize = pathModule.normalize;
12659 // Regexp that finds the next partion of a (partial) path
12660 // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
12662 var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
12664 var nextPartRe = /(.*?)(?:[\/]+|$)/g;
12667 // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
12669 var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
12671 var splitRootRe = /^[\/]*/;
12674 exports.realpathSync = function realpathSync(p, cache) {
12675 // make p is absolute
12676 p = pathModule.resolve(p);
12678 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
12686 // current character position in p
12688 // the partial path so far, including a trailing slash if any
12690 // the partial path without a trailing slash (except when pointing at a root)
12692 // the partial path scanned in the previous round, with slash
12699 var m = splitRootRe.exec(p);
12705 // On windows, check that the root exists. On unix there is no need.
12706 if (isWindows && !knownHard[base]) {
12707 fs.lstatSync(base);
12708 knownHard[base] = true;
12712 // walk down the path, swapping out linked pathparts for their real
12714 // NB: p.length changes.
12715 while (pos < p.length) {
12716 // find the next part
12717 nextPartRe.lastIndex = pos;
12718 var result = nextPartRe.exec(p);
12719 previous = current;
12720 current += result[0];
12721 base = previous + result[1];
12722 pos = nextPartRe.lastIndex;
12724 // continue if not a symlink
12725 if (knownHard[base] || (cache && cache[base] === base)) {
12730 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
12731 // some known symbolic link. no need to stat again.
12732 resolvedLink = cache[base];
12734 var stat = fs.lstatSync(base);
12735 if (!stat.isSymbolicLink()) {
12736 knownHard[base] = true;
12737 if (cache) cache[base] = base;
12741 // read the link if it wasn't read before
12742 // dev/ino always return 0 on windows, so skip the check.
12743 var linkTarget = null;
12745 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
12746 if (seenLinks.hasOwnProperty(id)) {
12747 linkTarget = seenLinks[id];
12750 if (linkTarget === null) {
12752 linkTarget = fs.readlinkSync(base);
12754 resolvedLink = pathModule.resolve(previous, linkTarget);
12755 // track this, if given a cache.
12756 if (cache) cache[base] = resolvedLink;
12757 if (!isWindows) seenLinks[id] = linkTarget;
12760 // resolve the link, then start over
12761 p = pathModule.resolve(resolvedLink, p.slice(pos));
12765 if (cache) cache[original] = p;
12771 exports.realpath = function realpath(p, cache, cb) {
12772 if (typeof cb !== 'function') {
12773 cb = maybeCallback(cache);
12777 // make p is absolute
12778 p = pathModule.resolve(p);
12780 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
12781 return process.nextTick(cb.bind(null, null, cache[p]));
12788 // current character position in p
12790 // the partial path so far, including a trailing slash if any
12792 // the partial path without a trailing slash (except when pointing at a root)
12794 // the partial path scanned in the previous round, with slash
12801 var m = splitRootRe.exec(p);
12807 // On windows, check that the root exists. On unix there is no need.
12808 if (isWindows && !knownHard[base]) {
12809 fs.lstat(base, function(err) {
12810 if (err) return cb(err);
12811 knownHard[base] = true;
12815 process.nextTick(LOOP);
12819 // walk down the path, swapping out linked pathparts for their real
12822 // stop if scanned past end of path
12823 if (pos >= p.length) {
12824 if (cache) cache[original] = p;
12825 return cb(null, p);
12828 // find the next part
12829 nextPartRe.lastIndex = pos;
12830 var result = nextPartRe.exec(p);
12831 previous = current;
12832 current += result[0];
12833 base = previous + result[1];
12834 pos = nextPartRe.lastIndex;
12836 // continue if not a symlink
12837 if (knownHard[base] || (cache && cache[base] === base)) {
12838 return process.nextTick(LOOP);
12841 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
12842 // known symbolic link. no need to stat again.
12843 return gotResolvedLink(cache[base]);
12846 return fs.lstat(base, gotStat);
12849 function gotStat(err, stat) {
12850 if (err) return cb(err);
12852 // if not a symlink, skip to the next path part
12853 if (!stat.isSymbolicLink()) {
12854 knownHard[base] = true;
12855 if (cache) cache[base] = base;
12856 return process.nextTick(LOOP);
12859 // stat & read the link if not read before
12860 // call gotTarget as soon as the link target is known
12861 // dev/ino always return 0 on windows, so skip the check.
12863 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
12864 if (seenLinks.hasOwnProperty(id)) {
12865 return gotTarget(null, seenLinks[id], base);
12868 fs.stat(base, function(err) {
12869 if (err) return cb(err);
12871 fs.readlink(base, function(err, target) {
12872 if (!isWindows) seenLinks[id] = target;
12873 gotTarget(err, target);
12878 function gotTarget(err, target, base) {
12879 if (err) return cb(err);
12881 var resolvedLink = pathModule.resolve(previous, target);
12882 if (cache) cache[base] = resolvedLink;
12883 gotResolvedLink(resolvedLink);
12886 function gotResolvedLink(resolvedLink) {
12887 // resolve the link, then start over
12888 p = pathModule.resolve(resolvedLink, p.slice(pos));
12896 /***/ (function(module, exports, __webpack_require__) {
12898 module.exports = minimatch
12899 minimatch.Minimatch = Minimatch
12901 var path = { sep: '/' }
12903 path = __webpack_require__(2)
12906 var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
12907 var expand = __webpack_require__(63)
12910 '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
12911 '?': { open: '(?:', close: ')?' },
12912 '+': { open: '(?:', close: ')+' },
12913 '*': { open: '(?:', close: ')*' },
12914 '@': { open: '(?:', close: ')' }
12917 // any single thing other than /
12918 // don't need to escape / when using new RegExp()
12921 // * => any number of characters
12922 var star = qmark + '*?'
12924 // ** when dots are allowed. Anything goes, except .. and .
12925 // not (^ or / followed by one or two dots followed by $ or /),
12926 // followed by anything, any number of times.
12927 var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
12929 // not a ^ or / followed by a dot,
12930 // followed by anything, any number of times.
12931 var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
12933 // characters that need to be escaped in RegExp.
12934 var reSpecials = charSet('().*{}+?[]^$\\!')
12936 // "abc" -> { a:true, b:true, c:true }
12937 function charSet (s) {
12938 return s.split('').reduce(function (set, c) {
12944 // normalizes slashes.
12945 var slashSplit = /\/+/
12947 minimatch.filter = filter
12948 function filter (pattern, options) {
12949 options = options || {}
12950 return function (p, i, list) {
12951 return minimatch(p, pattern, options)
12955 function ext (a, b) {
12959 Object.keys(b).forEach(function (k) {
12962 Object.keys(a).forEach(function (k) {
12968 minimatch.defaults = function (def) {
12969 if (!def || !Object.keys(def).length) return minimatch
12971 var orig = minimatch
12973 var m = function minimatch (p, pattern, options) {
12974 return orig.minimatch(p, pattern, ext(def, options))
12977 m.Minimatch = function Minimatch (pattern, options) {
12978 return new orig.Minimatch(pattern, ext(def, options))
12984 Minimatch.defaults = function (def) {
12985 if (!def || !Object.keys(def).length) return Minimatch
12986 return minimatch.defaults(def).Minimatch
12989 function minimatch (p, pattern, options) {
12990 if (typeof pattern !== 'string') {
12991 throw new TypeError('glob pattern string required')
12994 if (!options) options = {}
12996 // shortcut: comments match nothing.
12997 if (!options.nocomment && pattern.charAt(0) === '#') {
13001 // "" only matches ""
13002 if (pattern.trim() === '') return p === ''
13004 return new Minimatch(pattern, options).match(p)
13007 function Minimatch (pattern, options) {
13008 if (!(this instanceof Minimatch)) {
13009 return new Minimatch(pattern, options)
13012 if (typeof pattern !== 'string') {
13013 throw new TypeError('glob pattern string required')
13016 if (!options) options = {}
13017 pattern = pattern.trim()
13019 // windows support: need to use /, not \
13020 if (path.sep !== '/') {
13021 pattern = pattern.split(path.sep).join('/')
13024 this.options = options
13026 this.pattern = pattern
13028 this.negate = false
13029 this.comment = false
13032 // make the set of regexps etc.
13036 Minimatch.prototype.debug = function () {}
13038 Minimatch.prototype.make = make
13040 // don't do it more than once.
13041 if (this._made) return
13043 var pattern = this.pattern
13044 var options = this.options
13046 // empty patterns and comments match nothing.
13047 if (!options.nocomment && pattern.charAt(0) === '#') {
13048 this.comment = true
13056 // step 1: figure out negation, etc.
13059 // step 2: expand braces
13060 var set = this.globSet = this.braceExpand()
13062 if (options.debug) this.debug = console.error
13064 this.debug(this.pattern, set)
13066 // step 3: now we have a set, so turn each one into a series of path-portion
13067 // matching patterns.
13068 // These will be regexps, except in the case of "**", which is
13069 // set to the GLOBSTAR object for globstar behavior,
13070 // and will not contain any / characters
13071 set = this.globParts = set.map(function (s) {
13072 return s.split(slashSplit)
13075 this.debug(this.pattern, set)
13077 // glob --> regexps
13078 set = set.map(function (s, si, set) {
13079 return s.map(this.parse, this)
13082 this.debug(this.pattern, set)
13084 // filter out everything that didn't compile properly.
13085 set = set.filter(function (s) {
13086 return s.indexOf(false) === -1
13089 this.debug(this.pattern, set)
13094 Minimatch.prototype.parseNegate = parseNegate
13095 function parseNegate () {
13096 var pattern = this.pattern
13098 var options = this.options
13099 var negateOffset = 0
13101 if (options.nonegate) return
13103 for (var i = 0, l = pattern.length
13104 ; i < l && pattern.charAt(i) === '!'
13110 if (negateOffset) this.pattern = pattern.substr(negateOffset)
13111 this.negate = negate
13114 // Brace expansion:
13115 // a{b,c}d -> abd acd
13116 // a{b,}c -> abc ac
13117 // a{0..3}d -> a0d a1d a2d a3d
13118 // a{b,c{d,e}f}g -> abg acdfg acefg
13119 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
13121 // Invalid sets are not expanded.
13122 // a{2..}b -> a{2..}b
13124 minimatch.braceExpand = function (pattern, options) {
13125 return braceExpand(pattern, options)
13128 Minimatch.prototype.braceExpand = braceExpand
13130 function braceExpand (pattern, options) {
13132 if (this instanceof Minimatch) {
13133 options = this.options
13139 pattern = typeof pattern === 'undefined'
13140 ? this.pattern : pattern
13142 if (typeof pattern === 'undefined') {
13143 throw new TypeError('undefined pattern')
13146 if (options.nobrace ||
13147 !pattern.match(/\{.*\}/)) {
13148 // shortcut. no need to expand.
13152 return expand(pattern)
13155 // parse a component of the expanded set.
13156 // At this point, no pattern may contain "/" in it
13157 // so we're going to return a 2d array, where each entry is the full
13158 // pattern, split on '/', and then turned into a regular expression.
13159 // A regexp is made at the end which joins each array with an
13160 // escaped /, and another full one which joins each regexp with |.
13162 // Following the lead of Bash 4.1, note that "**" only has special meaning
13163 // when it is the *only* thing in a path portion. Otherwise, any series
13164 // of * is equivalent to a single *. Globstar behavior is enabled by
13165 // default, and can be disabled by setting options.noglobstar.
13166 Minimatch.prototype.parse = parse
13168 function parse (pattern, isSub) {
13169 if (pattern.length > 1024 * 64) {
13170 throw new TypeError('pattern is too long')
13173 var options = this.options
13176 if (!options.noglobstar && pattern === '**') return GLOBSTAR
13177 if (pattern === '') return ''
13180 var hasMagic = !!options.nocase
13181 var escaping = false
13182 // ? => one single character
13183 var patternListStack = []
13184 var negativeLists = []
13186 var inClass = false
13187 var reClassStart = -1
13188 var classStart = -1
13189 // . and .. never match anything that doesn't start with .,
13190 // even when options.dot is set.
13191 var patternStart = pattern.charAt(0) === '.' ? '' // anything
13192 // not (start or / followed by . or .. followed by / or end)
13193 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
13197 function clearStateChar () {
13199 // we had some state-tracking character
13200 // that wasn't consumed by this pass.
13201 switch (stateChar) {
13211 re += '\\' + stateChar
13214 self.debug('clearStateChar %j %j', stateChar, re)
13219 for (var i = 0, len = pattern.length, c
13220 ; (i < len) && (c = pattern.charAt(i))
13222 this.debug('%s\t%s %s %j', pattern, i, re, c)
13224 // skip over any that are escaped.
13225 if (escaping && reSpecials[c]) {
13233 // completely not allowed, even escaped.
13234 // Should already be path-split by now.
13242 // the various stateChar values
13243 // for the "extglob" stuff.
13249 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
13251 // all of those are literals inside a class, except that
13252 // the glob [!a] means [^a] in regexp
13254 this.debug(' in class')
13255 if (c === '!' && i === classStart + 1) c = '^'
13260 // if we already have a stateChar, then it means
13261 // that there was something like ** or +? in there.
13262 // Handle the stateChar, then proceed with this one.
13263 self.debug('call clearStateChar %j', stateChar)
13266 // if extglob is disabled, then +(asdf|foo) isn't a thing.
13267 // just clear the statechar *now*, rather than even diving into
13268 // the patternList stuff.
13269 if (options.noext) clearStateChar()
13283 patternListStack.push({
13286 reStart: re.length,
13287 open: plTypes[stateChar].open,
13288 close: plTypes[stateChar].close
13290 // negation is (?:(?!js)[^/]*)
13291 re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
13292 this.debug('plType %j %j', stateChar, re)
13297 if (inClass || !patternListStack.length) {
13304 var pl = patternListStack.pop()
13305 // negation is (?:(?!js)[^/]*)
13306 // The others are (?:<pattern>)<type>
13308 if (pl.type === '!') {
13309 negativeLists.push(pl)
13311 pl.reEnd = re.length
13315 if (inClass || !patternListStack.length || escaping) {
13325 // these are mostly the same in regexp and glob
13327 // swallow any state-tracking char before the [
13337 reClassStart = re.length
13342 // a right bracket shall lose its special
13343 // meaning and represent itself in
13344 // a bracket expression if it occurs
13345 // first in the list. -- POSIX.2 2.8.3.2
13346 if (i === classStart + 1 || !inClass) {
13352 // handle the case where we left a class open.
13353 // "[z-a]" is valid, equivalent to "\[z-a\]"
13355 // split where the last [ was, make sure we don't have
13356 // an invalid re. if so, re-walk the contents of the
13357 // would-be class to re-translate any characters that
13358 // were passed through as-is
13359 // TODO: It would probably be faster to determine this
13360 // without a try/catch and a new RegExp, but it's tricky
13361 // to do safely. For now, this is safe and works.
13362 var cs = pattern.substring(classStart + 1, i)
13364 RegExp('[' + cs + ']')
13366 // not a valid class!
13367 var sp = this.parse(cs, SUBPARSE)
13368 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
13369 hasMagic = hasMagic || sp[1]
13375 // finish up the class.
13382 // swallow any state char that wasn't consumed
13388 } else if (reSpecials[c]
13389 && !(c === '^' && inClass)) {
13398 // handle the case where we left a class open.
13399 // "[abc" is valid, equivalent to "\[abc"
13401 // split where the last [ was, and escape it
13402 // this is a huge pita. We now have to re-walk
13403 // the contents of the would-be class to re-translate
13404 // any characters that were passed through as-is
13405 cs = pattern.substr(classStart + 1)
13406 sp = this.parse(cs, SUBPARSE)
13407 re = re.substr(0, reClassStart) + '\\[' + sp[0]
13408 hasMagic = hasMagic || sp[1]
13411 // handle the case where we had a +( thing at the *end*
13413 // each pattern list stack adds 3 chars, and we need to go through
13414 // and escape any | chars that were passed through as-is for the regexp.
13415 // Go through and escape them, taking care not to double-escape any
13416 // | chars that were already escaped.
13417 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
13418 var tail = re.slice(pl.reStart + pl.open.length)
13419 this.debug('setting tail', re, pl)
13420 // maybe some even number of \, then maybe 1 \, followed by a |
13421 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
13423 // the | isn't already escaped, so escape it.
13427 // need to escape all those slashes *again*, without escaping the
13428 // one that we need for escaping the | character. As it works out,
13429 // escaping an even number of slashes can be done by simply repeating
13430 // it exactly after itself. That's why this trick works.
13432 // I am sorry that you have to see this.
13433 return $1 + $1 + $2 + '|'
13436 this.debug('tail=%j\n %s', tail, tail, pl, re)
13437 var t = pl.type === '*' ? star
13438 : pl.type === '?' ? qmark
13442 re = re.slice(0, pl.reStart) + t + '\\(' + tail
13445 // handle trailing things that only matter at the very end.
13452 // only need to apply the nodot start if the re starts with
13453 // something that could conceivably capture a dot
13454 var addPatternStart = false
13455 switch (re.charAt(0)) {
13458 case '(': addPatternStart = true
13461 // Hack to work around lack of negative lookbehind in JS
13462 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
13463 // like 'a.xyz.yz' doesn't match. So, the first negative
13464 // lookahead, has to look ALL the way ahead, to the end of
13466 for (var n = negativeLists.length - 1; n > -1; n--) {
13467 var nl = negativeLists[n]
13469 var nlBefore = re.slice(0, nl.reStart)
13470 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
13471 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
13472 var nlAfter = re.slice(nl.reEnd)
13476 // Handle nested stuff like *(*.js|!(*.json)), where open parens
13477 // mean that we should *not* include the ) in the bit that is considered
13478 // "after" the negated section.
13479 var openParensBefore = nlBefore.split('(').length - 1
13480 var cleanAfter = nlAfter
13481 for (i = 0; i < openParensBefore; i++) {
13482 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
13484 nlAfter = cleanAfter
13487 if (nlAfter === '' && isSub !== SUBPARSE) {
13490 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
13494 // if the re is not "" at this point, then we need to make sure
13495 // it doesn't match against an empty path part.
13496 // Otherwise a/* will match a/, which it should not.
13497 if (re !== '' && hasMagic) {
13501 if (addPatternStart) {
13502 re = patternStart + re
13505 // parsing just a piece of a larger pattern.
13506 if (isSub === SUBPARSE) {
13507 return [re, hasMagic]
13510 // skip the regexp for non-magical patterns
13511 // unescape anything in it, though, so that it'll be
13512 // an exact match against a file etc.
13514 return globUnescape(pattern)
13517 var flags = options.nocase ? 'i' : ''
13519 var regExp = new RegExp('^' + re + '$', flags)
13521 // If it was an invalid regular expression, then it can't match
13522 // anything. This trick looks for a character after the end of
13523 // the string, which is of course impossible, except in multi-line
13524 // mode, but it's not a /m regex.
13525 return new RegExp('$.')
13528 regExp._glob = pattern
13534 minimatch.makeRe = function (pattern, options) {
13535 return new Minimatch(pattern, options || {}).makeRe()
13538 Minimatch.prototype.makeRe = makeRe
13539 function makeRe () {
13540 if (this.regexp || this.regexp === false) return this.regexp
13542 // at this point, this.set is a 2d array of partial
13543 // pattern strings, or "**".
13545 // It's better to use .match(). This function shouldn't
13546 // be used, really, but it's pretty convenient sometimes,
13547 // when you just want to work with a regex.
13551 this.regexp = false
13554 var options = this.options
13556 var twoStar = options.noglobstar ? star
13557 : options.dot ? twoStarDot
13559 var flags = options.nocase ? 'i' : ''
13561 var re = set.map(function (pattern) {
13562 return pattern.map(function (p) {
13563 return (p === GLOBSTAR) ? twoStar
13564 : (typeof p === 'string') ? regExpEscape(p)
13569 // must match entire pattern
13570 // ending in a * or ** will make it less strict.
13571 re = '^(?:' + re + ')$'
13573 // can match anything, as long as it's not this.
13574 if (this.negate) re = '^(?!' + re + ').*$'
13577 this.regexp = new RegExp(re, flags)
13579 this.regexp = false
13584 minimatch.match = function (list, pattern, options) {
13585 options = options || {}
13586 var mm = new Minimatch(pattern, options)
13587 list = list.filter(function (f) {
13590 if (mm.options.nonull && !list.length) {
13596 Minimatch.prototype.match = match
13597 function match (f, partial) {
13598 this.debug('match', f, this.pattern)
13599 // short-circuit in the case of busted things.
13601 if (this.comment) return false
13602 if (this.empty) return f === ''
13604 if (f === '/' && partial) return true
13606 var options = this.options
13608 // windows: need to use /, not \
13609 if (path.sep !== '/') {
13610 f = f.split(path.sep).join('/')
13613 // treat the test path as a set of pathparts.
13614 f = f.split(slashSplit)
13615 this.debug(this.pattern, 'split', f)
13617 // just ONE of the pattern sets in this.set needs to match
13618 // in order for it to be valid. If negating, then just one
13619 // match means that we have failed.
13620 // Either way, return on the first hit.
13623 this.debug(this.pattern, 'set', set)
13625 // Find the basename of the path by looking for the last non-empty segment
13628 for (i = f.length - 1; i >= 0; i--) {
13630 if (filename) break
13633 for (i = 0; i < set.length; i++) {
13634 var pattern = set[i]
13636 if (options.matchBase && pattern.length === 1) {
13639 var hit = this.matchOne(file, pattern, partial)
13641 if (options.flipNegate) return true
13642 return !this.negate
13646 // didn't get any hits. this is success if it's a negative
13647 // pattern, failure otherwise.
13648 if (options.flipNegate) return false
13652 // set partial to true to test if, for example,
13653 // "/a/b" matches the start of "/*/b/*/d"
13654 // Partial means, if you run out of file before you run
13655 // out of pattern, then that's fine, as long as all
13656 // the parts match.
13657 Minimatch.prototype.matchOne = function (file, pattern, partial) {
13658 var options = this.options
13660 this.debug('matchOne',
13661 { 'this': this, file: file, pattern: pattern })
13663 this.debug('matchOne', file.length, pattern.length)
13668 pl = pattern.length
13669 ; (fi < fl) && (pi < pl)
13671 this.debug('matchOne loop')
13672 var p = pattern[pi]
13675 this.debug(pattern, p, f)
13677 // should be impossible.
13678 // some invalid regexp stuff in the set.
13679 if (p === false) return false
13681 if (p === GLOBSTAR) {
13682 this.debug('GLOBSTAR', [pattern, p, f])
13685 // a/**/b/**/c would match the following:
13690 // To do this, take the rest of the pattern after
13691 // the **, and see if it would match the file remainder.
13692 // If so, return success.
13693 // If not, the ** "swallows" a segment, and try again.
13694 // This is recursively awful.
13696 // a/**/b/**/c matching a/b/x/y/z/c
13699 // - matchOne(b/x/y/z/c, b/**/c)
13702 // - matchOne(x/y/z/c, c) -> no
13703 // - matchOne(y/z/c, c) -> no
13704 // - matchOne(z/c, c) -> no
13705 // - matchOne(c, c) yes, hit
13709 this.debug('** at the end')
13710 // a ** at the end will just swallow the rest.
13711 // We have found a match.
13712 // however, it will not swallow /.x, unless
13713 // options.dot is set.
13714 // . and .. are *never* matched by **, for explosively
13715 // exponential reasons.
13716 for (; fi < fl; fi++) {
13717 if (file[fi] === '.' || file[fi] === '..' ||
13718 (!options.dot && file[fi].charAt(0) === '.')) return false
13723 // ok, let's see if we can swallow whatever we can.
13725 var swallowee = file[fr]
13727 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
13729 // XXX remove this slice. Just pass the start index.
13730 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
13731 this.debug('globstar found match!', fr, fl, swallowee)
13735 // can't swallow "." or ".." ever.
13736 // can only swallow ".foo" when explicitly asked.
13737 if (swallowee === '.' || swallowee === '..' ||
13738 (!options.dot && swallowee.charAt(0) === '.')) {
13739 this.debug('dot detected!', file, fr, pattern, pr)
13743 // ** swallows a segment, and continue.
13744 this.debug('globstar swallow a segment, and continue')
13749 // no match was found.
13750 // However, in partial mode, we can't say this is necessarily over.
13751 // If there's more *pattern* left, then
13754 this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
13755 if (fr === fl) return true
13760 // something other than **
13761 // non-magic patterns just have to match exactly
13762 // patterns with magic have been turned into regexps.
13764 if (typeof p === 'string') {
13765 if (options.nocase) {
13766 hit = f.toLowerCase() === p.toLowerCase()
13770 this.debug('string match', p, f, hit)
13773 this.debug('pattern match', p, f, hit)
13776 if (!hit) return false
13779 // Note: ending in / means that we'll get a final ""
13780 // at the end of the pattern. This can only match a
13781 // corresponding "" at the end of the file.
13782 // If the file ends in /, then it can only match a
13783 // a pattern that ends in /, unless the pattern just
13784 // doesn't have any more for it. But, a/b/ should *not*
13785 // match "a/b/*", even though "" matches against the
13786 // [^/]*? pattern, except in partial mode, where it might
13787 // simply not be reached yet.
13788 // However, a/b/ should still satisfy a/*
13790 // now either we fell off the end of the pattern, or we're done.
13791 if (fi === fl && pi === pl) {
13792 // ran out of pattern and filename at the same time.
13795 } else if (fi === fl) {
13796 // ran out of file, but still had pattern left.
13797 // this is ok if we're doing the match as part of
13798 // a glob fs traversal.
13800 } else if (pi === pl) {
13801 // ran out of pattern, still have file left.
13802 // this is only acceptable if we're on the very last
13803 // empty segment of a file with a trailing slash.
13804 // a/* should match a/b/
13805 var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
13806 return emptyFileEnd
13809 // should be unreachable.
13810 throw new Error('wtf?')
13813 // replace stuff like \* with *
13814 function globUnescape (s) {
13815 return s.replace(/\\(.)/g, '$1')
13818 function regExpEscape (s) {
13819 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
13825 /***/ (function(module, exports, __webpack_require__) {
13827 var concatMap = __webpack_require__(64);
13828 var balanced = __webpack_require__(65);
13830 module.exports = expandTop;
13832 var escSlash = '\0SLASH'+Math.random()+'\0';
13833 var escOpen = '\0OPEN'+Math.random()+'\0';
13834 var escClose = '\0CLOSE'+Math.random()+'\0';
13835 var escComma = '\0COMMA'+Math.random()+'\0';
13836 var escPeriod = '\0PERIOD'+Math.random()+'\0';
13838 function numeric(str) {
13839 return parseInt(str, 10) == str
13840 ? parseInt(str, 10)
13841 : str.charCodeAt(0);
13844 function escapeBraces(str) {
13845 return str.split('\\\\').join(escSlash)
13846 .split('\\{').join(escOpen)
13847 .split('\\}').join(escClose)
13848 .split('\\,').join(escComma)
13849 .split('\\.').join(escPeriod);
13852 function unescapeBraces(str) {
13853 return str.split(escSlash).join('\\')
13854 .split(escOpen).join('{')
13855 .split(escClose).join('}')
13856 .split(escComma).join(',')
13857 .split(escPeriod).join('.');
13861 // Basically just str.split(","), but handling cases
13862 // where we have nested braced sections, which should be
13863 // treated as individual members, like {a,{b,c},d}
13864 function parseCommaParts(str) {
13869 var m = balanced('{', '}', str);
13872 return str.split(',');
13877 var p = pre.split(',');
13879 p[p.length-1] += '{' + body + '}';
13880 var postParts = parseCommaParts(post);
13882 p[p.length-1] += postParts.shift();
13883 p.push.apply(p, postParts);
13886 parts.push.apply(parts, p);
13891 function expandTop(str) {
13895 // I don't know why Bash 4.3 does this, but it does.
13896 // Anything starting with {} will have the first two bytes preserved
13897 // but *only* at the top level, so {},a}b will not expand to anything,
13898 // but a{},b}c will be expanded to [a}c,abc].
13899 // One could argue that this is a bug in Bash, but since the goal of
13900 // this module is to match Bash's rules, we escape a leading {}
13901 if (str.substr(0, 2) === '{}') {
13902 str = '\\{\\}' + str.substr(2);
13905 return expand(escapeBraces(str), true).map(unescapeBraces);
13908 function identity(e) {
13912 function embrace(str) {
13913 return '{' + str + '}';
13915 function isPadded(el) {
13916 return /^-?0\d/.test(el);
13919 function lte(i, y) {
13922 function gte(i, y) {
13926 function expand(str, isTop) {
13927 var expansions = [];
13929 var m = balanced('{', '}', str);
13930 if (!m || /\$$/.test(m.pre)) return [str];
13932 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
13933 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
13934 var isSequence = isNumericSequence || isAlphaSequence;
13935 var isOptions = m.body.indexOf(',') >= 0;
13936 if (!isSequence && !isOptions) {
13938 if (m.post.match(/,.*\}/)) {
13939 str = m.pre + '{' + m.body + escClose + m.post;
13940 return expand(str);
13947 n = m.body.split(/\.\./);
13949 n = parseCommaParts(m.body);
13950 if (n.length === 1) {
13951 // x{{a,b}}y ==> x{a}y x{b}y
13952 n = expand(n[0], false).map(embrace);
13953 if (n.length === 1) {
13954 var post = m.post.length
13955 ? expand(m.post, false)
13957 return post.map(function(p) {
13958 return m.pre + n[0] + p;
13964 // at this point, n is the parts, and we know it's not a comma set
13965 // with a single entry.
13967 // no need to expand pre, since it is guaranteed to be free of brace-sets
13969 var post = m.post.length
13970 ? expand(m.post, false)
13976 var x = numeric(n[0]);
13977 var y = numeric(n[1]);
13978 var width = Math.max(n[0].length, n[1].length)
13979 var incr = n.length == 3
13980 ? Math.abs(numeric(n[2]))
13983 var reverse = y < x;
13988 var pad = n.some(isPadded);
13992 for (var i = x; test(i, y); i += incr) {
13994 if (isAlphaSequence) {
13995 c = String.fromCharCode(i);
14001 var need = width - c.length;
14003 var z = new Array(need + 1).join('0');
14005 c = '-' + z + c.slice(1);
14014 N = concatMap(n, function(el) { return expand(el, false) });
14017 for (var j = 0; j < N.length; j++) {
14018 for (var k = 0; k < post.length; k++) {
14019 var expansion = pre + N[j] + post[k];
14020 if (!isTop || isSequence || expansion)
14021 expansions.push(expansion);
14032 /***/ (function(module, exports) {
14034 module.exports = function (xs, fn) {
14036 for (var i = 0; i < xs.length; i++) {
14037 var x = fn(xs[i], i);
14038 if (isArray(x)) res.push.apply(res, x);
14044 var isArray = Array.isArray || function (xs) {
14045 return Object.prototype.toString.call(xs) === '[object Array]';
14051 /***/ (function(module, exports, __webpack_require__) {
14055 module.exports = balanced;
14056 function balanced(a, b, str) {
14057 if (a instanceof RegExp) a = maybeMatch(a, str);
14058 if (b instanceof RegExp) b = maybeMatch(b, str);
14060 var r = range(a, b, str);
14065 pre: str.slice(0, r[0]),
14066 body: str.slice(r[0] + a.length, r[1]),
14067 post: str.slice(r[1] + b.length)
14071 function maybeMatch(reg, str) {
14072 var m = str.match(reg);
14073 return m ? m[0] : null;
14076 balanced.range = range;
14077 function range(a, b, str) {
14078 var begs, beg, left, right, result;
14079 var ai = str.indexOf(a);
14080 var bi = str.indexOf(b, ai + 1);
14083 if (ai >= 0 && bi > 0) {
14087 while (i >= 0 && !result) {
14090 ai = str.indexOf(a, i + 1);
14091 } else if (begs.length == 1) {
14092 result = [ begs.pop(), bi ];
14100 bi = str.indexOf(b, i + 1);
14103 i = ai < bi && ai >= 0 ? ai : bi;
14107 result = [ left, right ];
14117 /***/ (function(module, exports, __webpack_require__) {
14120 var util = __webpack_require__(50);
14121 /* istanbul ignore next */
14122 if (typeof util.inherits !== 'function') throw '';
14123 module.exports = util.inherits;
14125 /* istanbul ignore next */
14126 module.exports = __webpack_require__(67);
14132 /***/ (function(module, exports) {
14134 if (typeof Object.create === 'function') {
14135 // implementation from standard node.js 'util' module
14136 module.exports = function inherits(ctor, superCtor) {
14138 ctor.super_ = superCtor
14139 ctor.prototype = Object.create(superCtor.prototype, {
14150 // old school shim for old browsers
14151 module.exports = function inherits(ctor, superCtor) {
14153 ctor.super_ = superCtor
14154 var TempCtor = function () {}
14155 TempCtor.prototype = superCtor.prototype
14156 ctor.prototype = new TempCtor()
14157 ctor.prototype.constructor = ctor
14165 /***/ (function(module, exports) {
14167 module.exports = require("events");
14171 /***/ (function(module, exports, __webpack_require__) {
14176 function posix(path) {
14177 return path.charAt(0) === '/';
14180 function win32(path) {
14181 // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
14182 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
14183 var result = splitDeviceRe.exec(path);
14184 var device = result[1] || '';
14185 var isUnc = Boolean(device && device.charAt(1) !== ':');
14187 // UNC paths are always absolute
14188 return Boolean(result[2] || isUnc);
14191 module.exports = process.platform === 'win32' ? win32 : posix;
14192 module.exports.posix = posix;
14193 module.exports.win32 = win32;
14198 /***/ (function(module, exports, __webpack_require__) {
14200 module.exports = globSync
14201 globSync.GlobSync = GlobSync
14203 var fs = __webpack_require__(42)
14204 var rp = __webpack_require__(60)
14205 var minimatch = __webpack_require__(62)
14206 var Minimatch = minimatch.Minimatch
14207 var Glob = __webpack_require__(59).Glob
14208 var util = __webpack_require__(50)
14209 var path = __webpack_require__(2)
14210 var assert = __webpack_require__(58)
14211 var isAbsolute = __webpack_require__(69)
14212 var common = __webpack_require__(71)
14213 var alphasort = common.alphasort
14214 var alphasorti = common.alphasorti
14215 var setopts = common.setopts
14216 var ownProp = common.ownProp
14217 var childrenIgnored = common.childrenIgnored
14218 var isIgnored = common.isIgnored
14220 function globSync (pattern, options) {
14221 if (typeof options === 'function' || arguments.length === 3)
14222 throw new TypeError('callback provided to sync glob\n'+
14223 'See: https://github.com/isaacs/node-glob/issues/167')
14225 return new GlobSync(pattern, options).found
14228 function GlobSync (pattern, options) {
14230 throw new Error('must provide pattern')
14232 if (typeof options === 'function' || arguments.length === 3)
14233 throw new TypeError('callback provided to sync glob\n'+
14234 'See: https://github.com/isaacs/node-glob/issues/167')
14236 if (!(this instanceof GlobSync))
14237 return new GlobSync(pattern, options)
14239 setopts(this, pattern, options)
14241 if (this.noprocess)
14244 var n = this.minimatch.set.length
14245 this.matches = new Array(n)
14246 for (var i = 0; i < n; i ++) {
14247 this._process(this.minimatch.set[i], i, false)
14252 GlobSync.prototype._finish = function () {
14253 assert(this instanceof GlobSync)
14254 if (this.realpath) {
14256 this.matches.forEach(function (matchset, index) {
14257 var set = self.matches[index] = Object.create(null)
14258 for (var p in matchset) {
14260 p = self._makeAbs(p)
14261 var real = rp.realpathSync(p, self.realpathCache)
14264 if (er.syscall === 'stat')
14265 set[self._makeAbs(p)] = true
14272 common.finish(this)
14276 GlobSync.prototype._process = function (pattern, index, inGlobStar) {
14277 assert(this instanceof GlobSync)
14279 // Get the first [n] parts of pattern that are all strings.
14281 while (typeof pattern[n] === 'string') {
14284 // now n is the index of the first one that is *not* a string.
14286 // See if there's anything else
14289 // if not, then this is rather simple
14290 case pattern.length:
14291 this._processSimple(pattern.join('/'), index)
14295 // pattern *starts* with some non-trivial item.
14296 // going to readdir(cwd), but not include the prefix in matches.
14301 // pattern has some string bits in the front.
14302 // whatever it starts with, whether that's 'absolute' like /foo/bar,
14303 // or 'relative' like '../baz'
14304 prefix = pattern.slice(0, n).join('/')
14308 var remain = pattern.slice(n)
14310 // get the list of entries.
14312 if (prefix === null)
14314 else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) {
14315 if (!prefix || !isAbsolute(prefix))
14316 prefix = '/' + prefix
14321 var abs = this._makeAbs(read)
14323 //if ignored, skip processing
14324 if (childrenIgnored(this, read))
14327 var isGlobStar = remain[0] === minimatch.GLOBSTAR
14329 this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
14331 this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
14335 GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
14336 var entries = this._readdir(abs, inGlobStar)
14338 // if the abs isn't a dir, then nothing can match!
14342 // It will only match dot entries if it starts with a dot, or if
14343 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
14345 var negate = !!this.minimatch.negate
14346 var rawGlob = pn._glob
14347 var dotOk = this.dot || rawGlob.charAt(0) === '.'
14349 var matchedEntries = []
14350 for (var i = 0; i < entries.length; i++) {
14352 if (e.charAt(0) !== '.' || dotOk) {
14354 if (negate && !prefix) {
14360 matchedEntries.push(e)
14364 var len = matchedEntries.length
14365 // If there are no matched entries, then nothing matches.
14369 // if this is the last remaining pattern bit, then no need for
14370 // an additional stat *unless* the user has specified mark or
14371 // stat explicitly. We know they exist, since readdir returned
14374 if (remain.length === 1 && !this.mark && !this.stat) {
14375 if (!this.matches[index])
14376 this.matches[index] = Object.create(null)
14378 for (var i = 0; i < len; i ++) {
14379 var e = matchedEntries[i]
14381 if (prefix.slice(-1) !== '/')
14382 e = prefix + '/' + e
14387 if (e.charAt(0) === '/' && !this.nomount) {
14388 e = path.join(this.root, e)
14390 this._emitMatch(index, e)
14392 // This was the last one, and no stats were needed
14396 // now test all matched entries as stand-ins for that part
14399 for (var i = 0; i < len; i ++) {
14400 var e = matchedEntries[i]
14403 newPattern = [prefix, e]
14406 this._process(newPattern.concat(remain), index, inGlobStar)
14411 GlobSync.prototype._emitMatch = function (index, e) {
14412 if (isIgnored(this, e))
14415 var abs = this._makeAbs(e)
14420 if (this.absolute) {
14424 if (this.matches[index][e])
14428 var c = this.cache[abs]
14429 if (c === 'DIR' || Array.isArray(c))
14433 this.matches[index][e] = true
14440 GlobSync.prototype._readdirInGlobStar = function (abs) {
14441 // follow all symlinked directories forever
14442 // just proceed as if this is a non-globstar situation
14444 return this._readdir(abs, false)
14450 lstat = fs.lstatSync(abs)
14452 if (er.code === 'ENOENT') {
14453 // lstat failed, doesn't exist
14458 var isSym = lstat && lstat.isSymbolicLink()
14459 this.symlinks[abs] = isSym
14461 // If it's not a symlink or a dir, then it's definitely a regular file.
14462 // don't bother doing a readdir in that case.
14463 if (!isSym && lstat && !lstat.isDirectory())
14464 this.cache[abs] = 'FILE'
14466 entries = this._readdir(abs, false)
14471 GlobSync.prototype._readdir = function (abs, inGlobStar) {
14474 if (inGlobStar && !ownProp(this.symlinks, abs))
14475 return this._readdirInGlobStar(abs)
14477 if (ownProp(this.cache, abs)) {
14478 var c = this.cache[abs]
14479 if (!c || c === 'FILE')
14482 if (Array.isArray(c))
14487 return this._readdirEntries(abs, fs.readdirSync(abs))
14489 this._readdirError(abs, er)
14494 GlobSync.prototype._readdirEntries = function (abs, entries) {
14495 // if we haven't asked to stat everything, then just
14496 // assume that everything in there exists, so we can avoid
14497 // having to stat it a second time.
14498 if (!this.mark && !this.stat) {
14499 for (var i = 0; i < entries.length; i ++) {
14505 this.cache[e] = true
14509 this.cache[abs] = entries
14511 // mark and cache dir-ness
14515 GlobSync.prototype._readdirError = function (f, er) {
14516 // handle errors, and cache the information
14518 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
14519 case 'ENOTDIR': // totally normal. means it *does* exist.
14520 var abs = this._makeAbs(f)
14521 this.cache[abs] = 'FILE'
14522 if (abs === this.cwdAbs) {
14523 var error = new Error(er.code + ' invalid cwd ' + this.cwd)
14524 error.path = this.cwd
14525 error.code = er.code
14530 case 'ENOENT': // not terribly unusual
14532 case 'ENAMETOOLONG':
14534 this.cache[this._makeAbs(f)] = false
14537 default: // some unusual error. Treat as failure.
14538 this.cache[this._makeAbs(f)] = false
14542 console.error('glob error', er)
14547 GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
14549 var entries = this._readdir(abs, inGlobStar)
14551 // no entries means not a dir, so it can never have matches
14552 // foo.txt/** doesn't match foo.txt
14556 // test without the globstar, and with every child both below
14557 // and replacing the globstar.
14558 var remainWithoutGlobStar = remain.slice(1)
14559 var gspref = prefix ? [ prefix ] : []
14560 var noGlobStar = gspref.concat(remainWithoutGlobStar)
14562 // the noGlobStar pattern exits the inGlobStar state
14563 this._process(noGlobStar, index, false)
14565 var len = entries.length
14566 var isSym = this.symlinks[abs]
14568 // If it's a symlink, and we're in a globstar, then stop
14569 if (isSym && inGlobStar)
14572 for (var i = 0; i < len; i++) {
14574 if (e.charAt(0) === '.' && !this.dot)
14577 // these two cases enter the inGlobStar state
14578 var instead = gspref.concat(entries[i], remainWithoutGlobStar)
14579 this._process(instead, index, true)
14581 var below = gspref.concat(entries[i], remain)
14582 this._process(below, index, true)
14586 GlobSync.prototype._processSimple = function (prefix, index) {
14587 // XXX review this. Shouldn't it be doing the mounting etc
14588 // before doing stat? kinda weird?
14589 var exists = this._stat(prefix)
14591 if (!this.matches[index])
14592 this.matches[index] = Object.create(null)
14594 // If it doesn't exist, then just mark the lack of results
14598 if (prefix && isAbsolute(prefix) && !this.nomount) {
14599 var trail = /[\/\\]$/.test(prefix)
14600 if (prefix.charAt(0) === '/') {
14601 prefix = path.join(this.root, prefix)
14603 prefix = path.resolve(this.root, prefix)
14609 if (process.platform === 'win32')
14610 prefix = prefix.replace(/\\/g, '/')
14612 // Mark this as a match
14613 this._emitMatch(index, prefix)
14616 // Returns either 'DIR', 'FILE', or false
14617 GlobSync.prototype._stat = function (f) {
14618 var abs = this._makeAbs(f)
14619 var needDir = f.slice(-1) === '/'
14621 if (f.length > this.maxLength)
14624 if (!this.stat && ownProp(this.cache, abs)) {
14625 var c = this.cache[abs]
14627 if (Array.isArray(c))
14630 // It exists, but maybe not how we need it
14631 if (!needDir || c === 'DIR')
14634 if (needDir && c === 'FILE')
14637 // otherwise we have to stat, because maybe c=true
14638 // if we know it exists, but not what it is.
14642 var stat = this.statCache[abs]
14646 lstat = fs.lstatSync(abs)
14648 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
14649 this.statCache[abs] = false
14654 if (lstat && lstat.isSymbolicLink()) {
14656 stat = fs.statSync(abs)
14665 this.statCache[abs] = stat
14669 c = stat.isDirectory() ? 'DIR' : 'FILE'
14671 this.cache[abs] = this.cache[abs] || c
14673 if (needDir && c === 'FILE')
14679 GlobSync.prototype._mark = function (p) {
14680 return common.mark(this, p)
14683 GlobSync.prototype._makeAbs = function (f) {
14684 return common.makeAbs(this, f)
14690 /***/ (function(module, exports, __webpack_require__) {
14692 exports.alphasort = alphasort
14693 exports.alphasorti = alphasorti
14694 exports.setopts = setopts
14695 exports.ownProp = ownProp
14696 exports.makeAbs = makeAbs
14697 exports.finish = finish
14698 exports.mark = mark
14699 exports.isIgnored = isIgnored
14700 exports.childrenIgnored = childrenIgnored
14702 function ownProp (obj, field) {
14703 return Object.prototype.hasOwnProperty.call(obj, field)
14706 var path = __webpack_require__(2)
14707 var minimatch = __webpack_require__(62)
14708 var isAbsolute = __webpack_require__(69)
14709 var Minimatch = minimatch.Minimatch
14711 function alphasorti (a, b) {
14712 return a.toLowerCase().localeCompare(b.toLowerCase())
14715 function alphasort (a, b) {
14716 return a.localeCompare(b)
14719 function setupIgnores (self, options) {
14720 self.ignore = options.ignore || []
14722 if (!Array.isArray(self.ignore))
14723 self.ignore = [self.ignore]
14725 if (self.ignore.length) {
14726 self.ignore = self.ignore.map(ignoreMap)
14730 // ignore patterns are always in dot:true mode.
14731 function ignoreMap (pattern) {
14732 var gmatcher = null
14733 if (pattern.slice(-3) === '/**') {
14734 var gpattern = pattern.replace(/(\/\*\*)+$/, '')
14735 gmatcher = new Minimatch(gpattern, { dot: true })
14739 matcher: new Minimatch(pattern, { dot: true }),
14744 function setopts (self, pattern, options) {
14748 // base-matching: just use globstar for that.
14749 if (options.matchBase && -1 === pattern.indexOf("/")) {
14750 if (options.noglobstar) {
14751 throw new Error("base matching requires globstar")
14753 pattern = "**/" + pattern
14756 self.silent = !!options.silent
14757 self.pattern = pattern
14758 self.strict = options.strict !== false
14759 self.realpath = !!options.realpath
14760 self.realpathCache = options.realpathCache || Object.create(null)
14761 self.follow = !!options.follow
14762 self.dot = !!options.dot
14763 self.mark = !!options.mark
14764 self.nodir = !!options.nodir
14767 self.sync = !!options.sync
14768 self.nounique = !!options.nounique
14769 self.nonull = !!options.nonull
14770 self.nosort = !!options.nosort
14771 self.nocase = !!options.nocase
14772 self.stat = !!options.stat
14773 self.noprocess = !!options.noprocess
14774 self.absolute = !!options.absolute
14776 self.maxLength = options.maxLength || Infinity
14777 self.cache = options.cache || Object.create(null)
14778 self.statCache = options.statCache || Object.create(null)
14779 self.symlinks = options.symlinks || Object.create(null)
14781 setupIgnores(self, options)
14783 self.changedCwd = false
14784 var cwd = process.cwd()
14785 if (!ownProp(options, "cwd"))
14788 self.cwd = path.resolve(options.cwd)
14789 self.changedCwd = self.cwd !== cwd
14792 self.root = options.root || path.resolve(self.cwd, "/")
14793 self.root = path.resolve(self.root)
14794 if (process.platform === "win32")
14795 self.root = self.root.replace(/\\/g, "/")
14797 // TODO: is an absolute `cwd` supposed to be resolved against `root`?
14798 // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
14799 self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
14800 if (process.platform === "win32")
14801 self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
14802 self.nomount = !!options.nomount
14804 // disable comments and negation in Minimatch.
14805 // Note that they are not supported in Glob itself anyway.
14806 options.nonegate = true
14807 options.nocomment = true
14809 self.minimatch = new Minimatch(pattern, options)
14810 self.options = self.minimatch.options
14813 function finish (self) {
14814 var nou = self.nounique
14815 var all = nou ? [] : Object.create(null)
14817 for (var i = 0, l = self.matches.length; i < l; i ++) {
14818 var matches = self.matches[i]
14819 if (!matches || Object.keys(matches).length === 0) {
14821 // do like the shell, and spit out the literal glob
14822 var literal = self.minimatch.globSet[i]
14826 all[literal] = true
14830 var m = Object.keys(matches)
14832 all.push.apply(all, m)
14834 m.forEach(function (m) {
14841 all = Object.keys(all)
14844 all = all.sort(self.nocase ? alphasorti : alphasort)
14846 // at *some* point we statted all of these
14848 for (var i = 0; i < all.length; i++) {
14849 all[i] = self._mark(all[i])
14852 all = all.filter(function (e) {
14853 var notDir = !(/\/$/.test(e))
14854 var c = self.cache[e] || self.cache[makeAbs(self, e)]
14856 notDir = c !== 'DIR' && !Array.isArray(c)
14862 if (self.ignore.length)
14863 all = all.filter(function(m) {
14864 return !isIgnored(self, m)
14870 function mark (self, p) {
14871 var abs = makeAbs(self, p)
14872 var c = self.cache[abs]
14875 var isDir = c === 'DIR' || Array.isArray(c)
14876 var slash = p.slice(-1) === '/'
14878 if (isDir && !slash)
14880 else if (!isDir && slash)
14884 var mabs = makeAbs(self, m)
14885 self.statCache[mabs] = self.statCache[abs]
14886 self.cache[mabs] = self.cache[abs]
14894 function makeAbs (self, f) {
14896 if (f.charAt(0) === '/') {
14897 abs = path.join(self.root, f)
14898 } else if (isAbsolute(f) || f === '') {
14900 } else if (self.changedCwd) {
14901 abs = path.resolve(self.cwd, f)
14903 abs = path.resolve(f)
14906 if (process.platform === 'win32')
14907 abs = abs.replace(/\\/g, '/')
14913 // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
14914 // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
14915 function isIgnored (self, path) {
14916 if (!self.ignore.length)
14919 return self.ignore.some(function(item) {
14920 return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
14924 function childrenIgnored (self, path) {
14925 if (!self.ignore.length)
14928 return self.ignore.some(function(item) {
14929 return !!(item.gmatcher && item.gmatcher.match(path))
14936 /***/ (function(module, exports, __webpack_require__) {
14938 var wrappy = __webpack_require__(73)
14939 var reqs = Object.create(null)
14940 var once = __webpack_require__(74)
14942 module.exports = wrappy(inflight)
14944 function inflight (key, cb) {
14950 return makeres(key)
14954 function makeres (key) {
14955 return once(function RES () {
14956 var cbs = reqs[key]
14957 var len = cbs.length
14958 var args = slice(arguments)
14960 // XXX It's somewhat ambiguous whether a new callback added in this
14961 // pass should be queued for later execution if something in the
14962 // list of callbacks throws, or if it should just be discarded.
14963 // However, it's such an edge case that it hardly matters, and either
14964 // choice is likely as surprising as the other.
14965 // As it happens, we do go ahead and schedule it for later execution.
14967 for (var i = 0; i < len; i++) {
14968 cbs[i].apply(null, args)
14971 if (cbs.length > len) {
14972 // added more in the interim.
14973 // de-zalgo, just in case, but don't call again.
14975 process.nextTick(function () {
14976 RES.apply(null, args)
14985 function slice (args) {
14986 var length = args.length
14989 for (var i = 0; i < length; i++) array[i] = args[i]
14996 /***/ (function(module, exports) {
14998 // Returns a wrapper function that returns a wrapped callback
14999 // The wrapper function should do some stuff, and return a
15000 // presumably different callback function.
15001 // This makes sure that own properties are retained, so that
15002 // decorations and such are not lost along the way.
15003 module.exports = wrappy
15004 function wrappy (fn, cb) {
15005 if (fn && cb) return wrappy(fn)(cb)
15007 if (typeof fn !== 'function')
15008 throw new TypeError('need wrapper function')
15010 Object.keys(fn).forEach(function (k) {
15016 function wrapper() {
15017 var args = new Array(arguments.length)
15018 for (var i = 0; i < args.length; i++) {
15019 args[i] = arguments[i]
15021 var ret = fn.apply(this, args)
15022 var cb = args[args.length-1]
15023 if (typeof ret === 'function' && ret !== cb) {
15024 Object.keys(cb).forEach(function (k) {
15035 /***/ (function(module, exports, __webpack_require__) {
15037 var wrappy = __webpack_require__(73)
15038 module.exports = wrappy(once)
15039 module.exports.strict = wrappy(onceStrict)
15041 once.proto = once(function () {
15042 Object.defineProperty(Function.prototype, 'once', {
15043 value: function () {
15049 Object.defineProperty(Function.prototype, 'onceStrict', {
15050 value: function () {
15051 return onceStrict(this)
15057 function once (fn) {
15058 var f = function () {
15059 if (f.called) return f.value
15061 return f.value = fn.apply(this, arguments)
15067 function onceStrict (fn) {
15068 var f = function () {
15070 throw new Error(f.onceError)
15072 return f.value = fn.apply(this, arguments)
15074 var name = fn.name || 'Function wrapped with `once`'
15075 f.onceError = name + " shouldn't be called more than once"
15083 /***/ (function(module, exports, __webpack_require__) {
15085 // just pre-load all the stuff that index.js lazily exports
15086 const internalRe = __webpack_require__(76)
15089 src: internalRe.src,
15090 tokens: internalRe.t,
15091 SEMVER_SPEC_VERSION: __webpack_require__(77).SEMVER_SPEC_VERSION,
15092 SemVer: __webpack_require__(79),
15093 compareIdentifiers: __webpack_require__(80).compareIdentifiers,
15094 rcompareIdentifiers: __webpack_require__(80).rcompareIdentifiers,
15095 parse: __webpack_require__(81),
15096 valid: __webpack_require__(82),
15097 clean: __webpack_require__(83),
15098 inc: __webpack_require__(84),
15099 diff: __webpack_require__(85),
15100 major: __webpack_require__(88),
15101 minor: __webpack_require__(89),
15102 patch: __webpack_require__(90),
15103 prerelease: __webpack_require__(91),
15104 compare: __webpack_require__(87),
15105 rcompare: __webpack_require__(92),
15106 compareLoose: __webpack_require__(93),
15107 compareBuild: __webpack_require__(94),
15108 sort: __webpack_require__(95),
15109 rsort: __webpack_require__(96),
15110 gt: __webpack_require__(97),
15111 lt: __webpack_require__(98),
15112 eq: __webpack_require__(86),
15113 neq: __webpack_require__(99),
15114 gte: __webpack_require__(100),
15115 lte: __webpack_require__(101),
15116 cmp: __webpack_require__(102),
15117 coerce: __webpack_require__(103),
15118 Comparator: __webpack_require__(104),
15119 Range: __webpack_require__(105),
15120 satisfies: __webpack_require__(106),
15121 toComparators: __webpack_require__(107),
15122 maxSatisfying: __webpack_require__(108),
15123 minSatisfying: __webpack_require__(109),
15124 minVersion: __webpack_require__(110),
15125 validRange: __webpack_require__(111),
15126 outside: __webpack_require__(112),
15127 gtr: __webpack_require__(113),
15128 ltr: __webpack_require__(114),
15129 intersects: __webpack_require__(115),
15130 simplifyRange: __webpack_require__(116),
15131 subset: __webpack_require__(117),
15137 /***/ (function(module, exports, __webpack_require__) {
15139 const { MAX_SAFE_COMPONENT_LENGTH } = __webpack_require__(77)
15140 const debug = __webpack_require__(78)
15141 exports = module.exports = {}
15143 // The actual regexps go on exports.re
15144 const re = exports.re = []
15145 const src = exports.src = []
15146 const t = exports.t = {}
15149 const createToken = (name, value, isGlobal) => {
15151 debug(index, value)
15154 re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
15157 // The following Regular Expressions can be used for tokenizing,
15158 // validating, and parsing SemVer version strings.
15160 // ## Numeric Identifier
15161 // A single `0`, or a non-zero digit followed by zero or more digits.
15163 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
15164 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
15166 // ## Non-numeric Identifier
15167 // Zero or more digits, followed by a letter or hyphen, and then zero or
15168 // more letters, digits, or hyphens.
15170 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
15173 // Three dot-separated numeric identifiers.
15175 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
15176 `(${src[t.NUMERICIDENTIFIER]})\\.` +
15177 `(${src[t.NUMERICIDENTIFIER]})`)
15179 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
15180 `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
15181 `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
15183 // ## Pre-release Version Identifier
15184 // A numeric identifier, or a non-numeric identifier.
15186 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
15187 }|${src[t.NONNUMERICIDENTIFIER]})`)
15189 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
15190 }|${src[t.NONNUMERICIDENTIFIER]})`)
15192 // ## Pre-release Version
15193 // Hyphen, followed by one or more dot-separated pre-release version
15196 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
15197 }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
15199 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
15200 }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
15202 // ## Build Metadata Identifier
15203 // Any combination of digits, letters, or hyphens.
15205 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
15207 // ## Build Metadata
15208 // Plus sign, followed by one or more period-separated build metadata
15211 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
15212 }(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
15214 // ## Full Version String
15215 // A main version, followed optionally by a pre-release version and
15218 // Note that the only major, minor, patch, and pre-release sections of
15219 // the version string are capturing groups. The build metadata is not a
15220 // capturing group, because it should not ever be used in version
15223 createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
15224 }${src[t.PRERELEASE]}?${
15227 createToken('FULL', `^${src[t.FULLPLAIN]}$`)
15229 // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
15230 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
15231 // common in the npm registry.
15232 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
15233 }${src[t.PRERELEASELOOSE]}?${
15236 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
15238 createToken('GTLT', '((?:<|>)?=?)')
15240 // Something like "2.*" or "1.2.x".
15241 // Note that "x.x" is a valid xRange identifer, meaning "any version"
15242 // Only the first item is strictly required.
15243 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
15244 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
15246 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
15247 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
15248 `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
15249 `(?:${src[t.PRERELEASE]})?${
15253 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
15254 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
15255 `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
15256 `(?:${src[t.PRERELEASELOOSE]})?${
15260 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
15261 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
15264 // Extract anything that could conceivably be a part of a valid semver
15265 createToken('COERCE', `${'(^|[^\\d])' +
15266 '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
15267 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
15268 `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
15270 createToken('COERCERTL', src[t.COERCE], true)
15273 // Meaning is "reasonably at or greater than"
15274 createToken('LONETILDE', '(?:~>?)')
15276 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
15277 exports.tildeTrimReplace = '$1~'
15279 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
15280 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
15283 // Meaning is "at least and backwards compatible with"
15284 createToken('LONECARET', '(?:\\^)')
15286 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
15287 exports.caretTrimReplace = '$1^'
15289 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
15290 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
15292 // A simple gt/lt/eq thing, or just "" to indicate "any version"
15293 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
15294 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
15296 // An expression to strip any whitespace between the gtlt and the thing
15297 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
15298 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
15299 }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
15300 exports.comparatorTrimReplace = '$1$2$3'
15302 // Something like `1.2.3 - 1.2.4`
15303 // Note that these all use the loose form, because they'll be
15304 // checked against either the strict or loose comparator form
15306 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
15308 `(${src[t.XRANGEPLAIN]})` +
15311 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
15313 `(${src[t.XRANGEPLAINLOOSE]})` +
15316 // Star ranges basically just allow anything at all.
15317 createToken('STAR', '(<|>)?=?\\s*\\*')
15318 // >=0.0.0 is like a star
15319 createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$')
15320 createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$')
15325 /***/ (function(module, exports) {
15327 // Note: this is the semver.org version of the spec that it implements
15328 // Not necessarily the package version of this code.
15329 const SEMVER_SPEC_VERSION = '2.0.0'
15331 const MAX_LENGTH = 256
15332 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
15333 /* istanbul ignore next */ 9007199254740991
15335 // Max safe segment length for coercion.
15336 const MAX_SAFE_COMPONENT_LENGTH = 16
15339 SEMVER_SPEC_VERSION,
15342 MAX_SAFE_COMPONENT_LENGTH
15348 /***/ (function(module, exports) {
15351 typeof process === 'object' &&
15353 process.env.NODE_DEBUG &&
15354 /\bsemver\b/i.test(process.env.NODE_DEBUG)
15355 ) ? (...args) => console.error('SEMVER', ...args)
15358 module.exports = debug
15363 /***/ (function(module, exports, __webpack_require__) {
15365 const debug = __webpack_require__(78)
15366 const { MAX_LENGTH, MAX_SAFE_INTEGER } = __webpack_require__(77)
15367 const { re, t } = __webpack_require__(76)
15369 const { compareIdentifiers } = __webpack_require__(80)
15371 constructor (version, options) {
15372 if (!options || typeof options !== 'object') {
15375 includePrerelease: false
15378 if (version instanceof SemVer) {
15379 if (version.loose === !!options.loose &&
15380 version.includePrerelease === !!options.includePrerelease) {
15383 version = version.version
15385 } else if (typeof version !== 'string') {
15386 throw new TypeError(`Invalid Version: ${version}`)
15389 if (version.length > MAX_LENGTH) {
15390 throw new TypeError(
15391 `version is longer than ${MAX_LENGTH} characters`
15395 debug('SemVer', version, options)
15396 this.options = options
15397 this.loose = !!options.loose
15398 // this isn't actually relevant for versions, but keep it so that we
15399 // don't run into trouble passing this.options around.
15400 this.includePrerelease = !!options.includePrerelease
15402 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
15405 throw new TypeError(`Invalid Version: ${version}`)
15410 // these are actually numbers
15415 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
15416 throw new TypeError('Invalid major version')
15419 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
15420 throw new TypeError('Invalid minor version')
15423 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
15424 throw new TypeError('Invalid patch version')
15427 // numberify any prerelease numeric ids
15429 this.prerelease = []
15431 this.prerelease = m[4].split('.').map((id) => {
15432 if (/^[0-9]+$/.test(id)) {
15434 if (num >= 0 && num < MAX_SAFE_INTEGER) {
15442 this.build = m[5] ? m[5].split('.') : []
15447 this.version = `${this.major}.${this.minor}.${this.patch}`
15448 if (this.prerelease.length) {
15449 this.version += `-${this.prerelease.join('.')}`
15451 return this.version
15455 return this.version
15459 debug('SemVer.compare', this.version, this.options, other)
15460 if (!(other instanceof SemVer)) {
15461 if (typeof other === 'string' && other === this.version) {
15464 other = new SemVer(other, this.options)
15467 if (other.version === this.version) {
15471 return this.compareMain(other) || this.comparePre(other)
15474 compareMain (other) {
15475 if (!(other instanceof SemVer)) {
15476 other = new SemVer(other, this.options)
15480 compareIdentifiers(this.major, other.major) ||
15481 compareIdentifiers(this.minor, other.minor) ||
15482 compareIdentifiers(this.patch, other.patch)
15486 comparePre (other) {
15487 if (!(other instanceof SemVer)) {
15488 other = new SemVer(other, this.options)
15491 // NOT having a prerelease is > having one
15492 if (this.prerelease.length && !other.prerelease.length) {
15494 } else if (!this.prerelease.length && other.prerelease.length) {
15496 } else if (!this.prerelease.length && !other.prerelease.length) {
15502 const a = this.prerelease[i]
15503 const b = other.prerelease[i]
15504 debug('prerelease compare', i, a, b)
15505 if (a === undefined && b === undefined) {
15507 } else if (b === undefined) {
15509 } else if (a === undefined) {
15511 } else if (a === b) {
15514 return compareIdentifiers(a, b)
15519 compareBuild (other) {
15520 if (!(other instanceof SemVer)) {
15521 other = new SemVer(other, this.options)
15526 const a = this.build[i]
15527 const b = other.build[i]
15528 debug('prerelease compare', i, a, b)
15529 if (a === undefined && b === undefined) {
15531 } else if (b === undefined) {
15533 } else if (a === undefined) {
15535 } else if (a === b) {
15538 return compareIdentifiers(a, b)
15543 // preminor will bump the version up to the next minor release, and immediately
15544 // down to pre-release. premajor and prepatch work the same way.
15545 inc (release, identifier) {
15548 this.prerelease.length = 0
15552 this.inc('pre', identifier)
15555 this.prerelease.length = 0
15558 this.inc('pre', identifier)
15561 // If this is already a prerelease, it will bump to the next version
15562 // drop any prereleases that might already exist, since they are not
15563 // relevant at this point.
15564 this.prerelease.length = 0
15565 this.inc('patch', identifier)
15566 this.inc('pre', identifier)
15568 // If the input is a non-prerelease version, this acts the same as
15571 if (this.prerelease.length === 0) {
15572 this.inc('patch', identifier)
15574 this.inc('pre', identifier)
15578 // If this is a pre-major version, bump up to the same major version.
15579 // Otherwise increment major.
15580 // 1.0.0-5 bumps to 1.0.0
15581 // 1.1.0 bumps to 2.0.0
15583 this.minor !== 0 ||
15584 this.patch !== 0 ||
15585 this.prerelease.length === 0
15591 this.prerelease = []
15594 // If this is a pre-minor version, bump up to the same minor version.
15595 // Otherwise increment minor.
15596 // 1.2.0-5 bumps to 1.2.0
15597 // 1.2.1 bumps to 1.3.0
15598 if (this.patch !== 0 || this.prerelease.length === 0) {
15602 this.prerelease = []
15605 // If this is not a pre-release version, it will increment the patch.
15606 // If it is a pre-release it will bump up to the same patch version.
15607 // 1.2.0-5 patches to 1.2.0
15608 // 1.2.0 patches to 1.2.1
15609 if (this.prerelease.length === 0) {
15612 this.prerelease = []
15614 // This probably shouldn't be used publicly.
15615 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
15617 if (this.prerelease.length === 0) {
15618 this.prerelease = [0]
15620 let i = this.prerelease.length
15622 if (typeof this.prerelease[i] === 'number') {
15623 this.prerelease[i]++
15628 // didn't increment anything
15629 this.prerelease.push(0)
15633 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
15634 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
15635 if (this.prerelease[0] === identifier) {
15636 if (isNaN(this.prerelease[1])) {
15637 this.prerelease = [identifier, 0]
15640 this.prerelease = [identifier, 0]
15646 throw new Error(`invalid increment argument: ${release}`)
15649 this.raw = this.version
15654 module.exports = SemVer
15659 /***/ (function(module, exports) {
15661 const numeric = /^[0-9]+$/
15662 const compareIdentifiers = (a, b) => {
15663 const anum = numeric.test(a)
15664 const bnum = numeric.test(b)
15666 if (anum && bnum) {
15672 : (anum && !bnum) ? -1
15673 : (bnum && !anum) ? 1
15678 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
15681 compareIdentifiers,
15682 rcompareIdentifiers
15688 /***/ (function(module, exports, __webpack_require__) {
15690 const {MAX_LENGTH} = __webpack_require__(77)
15691 const { re, t } = __webpack_require__(76)
15692 const SemVer = __webpack_require__(79)
15694 const parse = (version, options) => {
15695 if (!options || typeof options !== 'object') {
15698 includePrerelease: false
15702 if (version instanceof SemVer) {
15706 if (typeof version !== 'string') {
15710 if (version.length > MAX_LENGTH) {
15714 const r = options.loose ? re[t.LOOSE] : re[t.FULL]
15715 if (!r.test(version)) {
15720 return new SemVer(version, options)
15726 module.exports = parse
15731 /***/ (function(module, exports, __webpack_require__) {
15733 const parse = __webpack_require__(81)
15734 const valid = (version, options) => {
15735 const v = parse(version, options)
15736 return v ? v.version : null
15738 module.exports = valid
15743 /***/ (function(module, exports, __webpack_require__) {
15745 const parse = __webpack_require__(81)
15746 const clean = (version, options) => {
15747 const s = parse(version.trim().replace(/^[=v]+/, ''), options)
15748 return s ? s.version : null
15750 module.exports = clean
15755 /***/ (function(module, exports, __webpack_require__) {
15757 const SemVer = __webpack_require__(79)
15759 const inc = (version, release, options, identifier) => {
15760 if (typeof (options) === 'string') {
15761 identifier = options
15762 options = undefined
15766 return new SemVer(version, options).inc(release, identifier).version
15771 module.exports = inc
15776 /***/ (function(module, exports, __webpack_require__) {
15778 const parse = __webpack_require__(81)
15779 const eq = __webpack_require__(86)
15781 const diff = (version1, version2) => {
15782 if (eq(version1, version2)) {
15785 const v1 = parse(version1)
15786 const v2 = parse(version2)
15787 const hasPre = v1.prerelease.length || v2.prerelease.length
15788 const prefix = hasPre ? 'pre' : ''
15789 const defaultResult = hasPre ? 'prerelease' : ''
15790 for (const key in v1) {
15791 if (key === 'major' || key === 'minor' || key === 'patch') {
15792 if (v1[key] !== v2[key]) {
15793 return prefix + key
15797 return defaultResult // may be undefined
15800 module.exports = diff
15805 /***/ (function(module, exports, __webpack_require__) {
15807 const compare = __webpack_require__(87)
15808 const eq = (a, b, loose) => compare(a, b, loose) === 0
15809 module.exports = eq
15814 /***/ (function(module, exports, __webpack_require__) {
15816 const SemVer = __webpack_require__(79)
15817 const compare = (a, b, loose) =>
15818 new SemVer(a, loose).compare(new SemVer(b, loose))
15820 module.exports = compare
15825 /***/ (function(module, exports, __webpack_require__) {
15827 const SemVer = __webpack_require__(79)
15828 const major = (a, loose) => new SemVer(a, loose).major
15829 module.exports = major
15834 /***/ (function(module, exports, __webpack_require__) {
15836 const SemVer = __webpack_require__(79)
15837 const minor = (a, loose) => new SemVer(a, loose).minor
15838 module.exports = minor
15843 /***/ (function(module, exports, __webpack_require__) {
15845 const SemVer = __webpack_require__(79)
15846 const patch = (a, loose) => new SemVer(a, loose).patch
15847 module.exports = patch
15852 /***/ (function(module, exports, __webpack_require__) {
15854 const parse = __webpack_require__(81)
15855 const prerelease = (version, options) => {
15856 const parsed = parse(version, options)
15857 return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
15859 module.exports = prerelease
15864 /***/ (function(module, exports, __webpack_require__) {
15866 const compare = __webpack_require__(87)
15867 const rcompare = (a, b, loose) => compare(b, a, loose)
15868 module.exports = rcompare
15873 /***/ (function(module, exports, __webpack_require__) {
15875 const compare = __webpack_require__(87)
15876 const compareLoose = (a, b) => compare(a, b, true)
15877 module.exports = compareLoose
15882 /***/ (function(module, exports, __webpack_require__) {
15884 const SemVer = __webpack_require__(79)
15885 const compareBuild = (a, b, loose) => {
15886 const versionA = new SemVer(a, loose)
15887 const versionB = new SemVer(b, loose)
15888 return versionA.compare(versionB) || versionA.compareBuild(versionB)
15890 module.exports = compareBuild
15895 /***/ (function(module, exports, __webpack_require__) {
15897 const compareBuild = __webpack_require__(94)
15898 const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
15899 module.exports = sort
15904 /***/ (function(module, exports, __webpack_require__) {
15906 const compareBuild = __webpack_require__(94)
15907 const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
15908 module.exports = rsort
15913 /***/ (function(module, exports, __webpack_require__) {
15915 const compare = __webpack_require__(87)
15916 const gt = (a, b, loose) => compare(a, b, loose) > 0
15917 module.exports = gt
15922 /***/ (function(module, exports, __webpack_require__) {
15924 const compare = __webpack_require__(87)
15925 const lt = (a, b, loose) => compare(a, b, loose) < 0
15926 module.exports = lt
15931 /***/ (function(module, exports, __webpack_require__) {
15933 const compare = __webpack_require__(87)
15934 const neq = (a, b, loose) => compare(a, b, loose) !== 0
15935 module.exports = neq
15940 /***/ (function(module, exports, __webpack_require__) {
15942 const compare = __webpack_require__(87)
15943 const gte = (a, b, loose) => compare(a, b, loose) >= 0
15944 module.exports = gte
15949 /***/ (function(module, exports, __webpack_require__) {
15951 const compare = __webpack_require__(87)
15952 const lte = (a, b, loose) => compare(a, b, loose) <= 0
15953 module.exports = lte
15958 /***/ (function(module, exports, __webpack_require__) {
15960 const eq = __webpack_require__(86)
15961 const neq = __webpack_require__(99)
15962 const gt = __webpack_require__(97)
15963 const gte = __webpack_require__(100)
15964 const lt = __webpack_require__(98)
15965 const lte = __webpack_require__(101)
15967 const cmp = (a, op, b, loose) => {
15970 if (typeof a === 'object')
15972 if (typeof b === 'object')
15977 if (typeof a === 'object')
15979 if (typeof b === 'object')
15986 return eq(a, b, loose)
15989 return neq(a, b, loose)
15992 return gt(a, b, loose)
15995 return gte(a, b, loose)
15998 return lt(a, b, loose)
16001 return lte(a, b, loose)
16004 throw new TypeError(`Invalid operator: ${op}`)
16007 module.exports = cmp
16012 /***/ (function(module, exports, __webpack_require__) {
16014 const SemVer = __webpack_require__(79)
16015 const parse = __webpack_require__(81)
16016 const {re, t} = __webpack_require__(76)
16018 const coerce = (version, options) => {
16019 if (version instanceof SemVer) {
16023 if (typeof version === 'number') {
16024 version = String(version)
16027 if (typeof version !== 'string') {
16031 options = options || {}
16034 if (!options.rtl) {
16035 match = version.match(re[t.COERCE])
16037 // Find the right-most coercible string that does not share
16038 // a terminus with a more left-ward coercible string.
16039 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
16041 // Walk through the string checking with a /g regexp
16042 // Manually set the index so as to pick up overlapping matches.
16043 // Stop when we get a match that ends at the string end, since no
16044 // coercible string can be more right-ward without the same terminus.
16046 while ((next = re[t.COERCERTL].exec(version)) &&
16047 (!match || match.index + match[0].length !== version.length)
16050 next.index + next[0].length !== match.index + match[0].length) {
16053 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
16055 // leave it in a clean state
16056 re[t.COERCERTL].lastIndex = -1
16059 if (match === null)
16062 return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
16064 module.exports = coerce
16069 /***/ (function(module, exports, __webpack_require__) {
16071 const ANY = Symbol('SemVer ANY')
16072 // hoisted class for cyclic dependency
16074 static get ANY () {
16077 constructor (comp, options) {
16078 if (!options || typeof options !== 'object') {
16081 includePrerelease: false
16085 if (comp instanceof Comparator) {
16086 if (comp.loose === !!options.loose) {
16093 debug('comparator', comp, options)
16094 this.options = options
16095 this.loose = !!options.loose
16098 if (this.semver === ANY) {
16101 this.value = this.operator + this.semver.version
16104 debug('comp', this)
16108 const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
16109 const m = comp.match(r)
16112 throw new TypeError(`Invalid comparator: ${comp}`)
16115 this.operator = m[1] !== undefined ? m[1] : ''
16116 if (this.operator === '=') {
16120 // if it literally is just '>' or '' then allow anything.
16124 this.semver = new SemVer(m[2], this.options.loose)
16133 debug('Comparator.test', version, this.options.loose)
16135 if (this.semver === ANY || version === ANY) {
16139 if (typeof version === 'string') {
16141 version = new SemVer(version, this.options)
16147 return cmp(version, this.operator, this.semver, this.options)
16150 intersects (comp, options) {
16151 if (!(comp instanceof Comparator)) {
16152 throw new TypeError('a Comparator is required')
16155 if (!options || typeof options !== 'object') {
16158 includePrerelease: false
16162 if (this.operator === '') {
16163 if (this.value === '') {
16166 return new Range(comp.value, options).test(this.value)
16167 } else if (comp.operator === '') {
16168 if (comp.value === '') {
16171 return new Range(this.value, options).test(comp.semver)
16174 const sameDirectionIncreasing =
16175 (this.operator === '>=' || this.operator === '>') &&
16176 (comp.operator === '>=' || comp.operator === '>')
16177 const sameDirectionDecreasing =
16178 (this.operator === '<=' || this.operator === '<') &&
16179 (comp.operator === '<=' || comp.operator === '<')
16180 const sameSemVer = this.semver.version === comp.semver.version
16181 const differentDirectionsInclusive =
16182 (this.operator === '>=' || this.operator === '<=') &&
16183 (comp.operator === '>=' || comp.operator === '<=')
16184 const oppositeDirectionsLessThan =
16185 cmp(this.semver, '<', comp.semver, options) &&
16186 (this.operator === '>=' || this.operator === '>') &&
16187 (comp.operator === '<=' || comp.operator === '<')
16188 const oppositeDirectionsGreaterThan =
16189 cmp(this.semver, '>', comp.semver, options) &&
16190 (this.operator === '<=' || this.operator === '<') &&
16191 (comp.operator === '>=' || comp.operator === '>')
16194 sameDirectionIncreasing ||
16195 sameDirectionDecreasing ||
16196 (sameSemVer && differentDirectionsInclusive) ||
16197 oppositeDirectionsLessThan ||
16198 oppositeDirectionsGreaterThan
16203 module.exports = Comparator
16205 const {re, t} = __webpack_require__(76)
16206 const cmp = __webpack_require__(102)
16207 const debug = __webpack_require__(78)
16208 const SemVer = __webpack_require__(79)
16209 const Range = __webpack_require__(105)
16214 /***/ (function(module, exports, __webpack_require__) {
16216 // hoisted class for cyclic dependency
16218 constructor (range, options) {
16219 if (!options || typeof options !== 'object') {
16222 includePrerelease: false
16226 if (range instanceof Range) {
16228 range.loose === !!options.loose &&
16229 range.includePrerelease === !!options.includePrerelease
16233 return new Range(range.raw, options)
16237 if (range instanceof Comparator) {
16238 // just put it in the set and return
16239 this.raw = range.value
16240 this.set = [[range]]
16245 this.options = options
16246 this.loose = !!options.loose
16247 this.includePrerelease = !!options.includePrerelease
16249 // First, split based on boolean or ||
16252 .split(/\s*\|\|\s*/)
16253 // map the range to a 2d array of comparators
16254 .map(range => this.parseRange(range.trim()))
16255 // throw out any comparator lists that are empty
16256 // this generally means that it was not a valid range, which is allowed
16257 // in loose mode, but will still throw if the WHOLE range is invalid.
16258 .filter(c => c.length)
16260 if (!this.set.length) {
16261 throw new TypeError(`Invalid SemVer Range: ${range}`)
16268 this.range = this.set
16270 return comps.join(' ').trim()
16281 parseRange (range) {
16282 const loose = this.options.loose
16283 range = range.trim()
16284 // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
16285 const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
16286 range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
16287 debug('hyphen replace', range)
16288 // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
16289 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
16290 debug('comparator trim', range, re[t.COMPARATORTRIM])
16292 // `~ 1.2.3` => `~1.2.3`
16293 range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
16295 // `^ 1.2.3` => `^1.2.3`
16296 range = range.replace(re[t.CARETTRIM], caretTrimReplace)
16298 // normalize spaces
16299 range = range.split(/\s+/).join(' ')
16301 // At this point, the range is completely trimmed and
16302 // ready to be split into comparators.
16304 const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
16307 .map(comp => parseComparator(comp, this.options))
16310 .map(comp => replaceGTE0(comp, this.options))
16311 // in loose mode, throw out any that are not valid comparators
16312 .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true)
16313 .map(comp => new Comparator(comp, this.options))
16316 intersects (range, options) {
16317 if (!(range instanceof Range)) {
16318 throw new TypeError('a Range is required')
16321 return this.set.some((thisComparators) => {
16323 isSatisfiable(thisComparators, options) &&
16324 range.set.some((rangeComparators) => {
16326 isSatisfiable(rangeComparators, options) &&
16327 thisComparators.every((thisComparator) => {
16328 return rangeComparators.every((rangeComparator) => {
16329 return thisComparator.intersects(rangeComparator, options)
16338 // if ANY of the sets match ALL of its comparators, then pass
16344 if (typeof version === 'string') {
16346 version = new SemVer(version, this.options)
16352 for (let i = 0; i < this.set.length; i++) {
16353 if (testSet(this.set[i], version, this.options)) {
16360 module.exports = Range
16362 const Comparator = __webpack_require__(104)
16363 const debug = __webpack_require__(78)
16364 const SemVer = __webpack_require__(79)
16368 comparatorTrimReplace,
16371 } = __webpack_require__(76)
16373 // take a set of comparators and determine whether there
16374 // exists a version which can satisfy it
16375 const isSatisfiable = (comparators, options) => {
16377 const remainingComparators = comparators.slice()
16378 let testComparator = remainingComparators.pop()
16380 while (result && remainingComparators.length) {
16381 result = remainingComparators.every((otherComparator) => {
16382 return testComparator.intersects(otherComparator, options)
16385 testComparator = remainingComparators.pop()
16391 // comprised of xranges, tildes, stars, and gtlt's at this point.
16392 // already replaced the hyphen ranges
16393 // turn into a set of JUST comparators.
16394 const parseComparator = (comp, options) => {
16395 debug('comp', comp, options)
16396 comp = replaceCarets(comp, options)
16397 debug('caret', comp)
16398 comp = replaceTildes(comp, options)
16399 debug('tildes', comp)
16400 comp = replaceXRanges(comp, options)
16401 debug('xrange', comp)
16402 comp = replaceStars(comp, options)
16403 debug('stars', comp)
16407 const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
16409 // ~, ~> --> * (any, kinda silly)
16410 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
16411 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
16412 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
16413 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
16414 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
16415 const replaceTildes = (comp, options) =>
16416 comp.trim().split(/\s+/).map((comp) => {
16417 return replaceTilde(comp, options)
16420 const replaceTilde = (comp, options) => {
16421 const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
16422 return comp.replace(r, (_, M, m, p, pr) => {
16423 debug('tilde', comp, _, M, m, p, pr)
16428 } else if (isX(m)) {
16429 ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
16430 } else if (isX(p)) {
16431 // ~1.2 == >=1.2.0 <1.3.0-0
16432 ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
16434 debug('replaceTilde pr', pr)
16435 ret = `>=${M}.${m}.${p}-${pr
16436 } <${M}.${+m + 1}.0-0`
16438 // ~1.2.3 == >=1.2.3 <1.3.0-0
16439 ret = `>=${M}.${m}.${p
16440 } <${M}.${+m + 1}.0-0`
16443 debug('tilde return', ret)
16448 // ^ --> * (any, kinda silly)
16449 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
16450 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
16451 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
16452 // ^1.2.3 --> >=1.2.3 <2.0.0-0
16453 // ^1.2.0 --> >=1.2.0 <2.0.0-0
16454 const replaceCarets = (comp, options) =>
16455 comp.trim().split(/\s+/).map((comp) => {
16456 return replaceCaret(comp, options)
16459 const replaceCaret = (comp, options) => {
16460 debug('caret', comp, options)
16461 const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
16462 const z = options.includePrerelease ? '-0' : ''
16463 return comp.replace(r, (_, M, m, p, pr) => {
16464 debug('caret', comp, _, M, m, p, pr)
16469 } else if (isX(m)) {
16470 ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
16471 } else if (isX(p)) {
16473 ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
16475 ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
16478 debug('replaceCaret pr', pr)
16481 ret = `>=${M}.${m}.${p}-${pr
16482 } <${M}.${m}.${+p + 1}-0`
16484 ret = `>=${M}.${m}.${p}-${pr
16485 } <${M}.${+m + 1}.0-0`
16488 ret = `>=${M}.${m}.${p}-${pr
16489 } <${+M + 1}.0.0-0`
16495 ret = `>=${M}.${m}.${p
16496 }${z} <${M}.${m}.${+p + 1}-0`
16498 ret = `>=${M}.${m}.${p
16499 }${z} <${M}.${+m + 1}.0-0`
16502 ret = `>=${M}.${m}.${p
16503 } <${+M + 1}.0.0-0`
16507 debug('caret return', ret)
16512 const replaceXRanges = (comp, options) => {
16513 debug('replaceXRanges', comp, options)
16514 return comp.split(/\s+/).map((comp) => {
16515 return replaceXRange(comp, options)
16519 const replaceXRange = (comp, options) => {
16521 const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
16522 return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
16523 debug('xRange', comp, ret, gtlt, M, m, p, pr)
16525 const xm = xM || isX(m)
16526 const xp = xm || isX(p)
16529 if (gtlt === '=' && anyX) {
16533 // if we're including prereleases in the match, then we need
16534 // to fix this to -0, the lowest possible prerelease value
16535 pr = options.includePrerelease ? '-0' : ''
16538 if (gtlt === '>' || gtlt === '<') {
16539 // nothing is allowed
16542 // nothing is forbidden
16545 } else if (gtlt && anyX) {
16546 // we know patch is an x, because we have any x at all.
16547 // replace X with 0
16553 if (gtlt === '>') {
16565 } else if (gtlt === '<=') {
16566 // <=0.7.x is actually <0.8.0, since any 0.7.x should
16567 // pass. Similarly, <=7.x is actually <8.0.0, etc.
16579 ret = `${gtlt + M}.${m}.${p}${pr}`
16581 ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
16583 ret = `>=${M}.${m}.0${pr
16584 } <${M}.${+m + 1}.0-0`
16587 debug('xRange return', ret)
16593 // Because * is AND-ed with everything else in the comparator,
16594 // and '' means "any version", just remove the *s entirely.
16595 const replaceStars = (comp, options) => {
16596 debug('replaceStars', comp, options)
16597 // Looseness is ignored here. star is always as loose as it gets!
16598 return comp.trim().replace(re[t.STAR], '')
16601 const replaceGTE0 = (comp, options) => {
16602 debug('replaceGTE0', comp, options)
16604 .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
16607 // This function is passed to string.replace(re[t.HYPHENRANGE])
16608 // M, m, patch, prerelease, build
16609 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
16610 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
16611 // 1.2 - 3.4 => >=1.2.0 <3.5.0-0
16612 const hyphenReplace = incPr => ($0,
16613 from, fM, fm, fp, fpr, fb,
16614 to, tM, tm, tp, tpr, tb) => {
16617 } else if (isX(fm)) {
16618 from = `>=${fM}.0.0${incPr ? '-0' : ''}`
16619 } else if (isX(fp)) {
16620 from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
16624 from = `>=${from}${incPr ? '-0' : ''}`
16629 } else if (isX(tm)) {
16630 to = `<${+tM + 1}.0.0-0`
16631 } else if (isX(tp)) {
16632 to = `<${tM}.${+tm + 1}.0-0`
16634 to = `<=${tM}.${tm}.${tp}-${tpr}`
16635 } else if (incPr) {
16636 to = `<${tM}.${tm}.${+tp + 1}-0`
16641 return (`${from} ${to}`).trim()
16644 const testSet = (set, version, options) => {
16645 for (let i = 0; i < set.length; i++) {
16646 if (!set[i].test(version)) {
16651 if (version.prerelease.length && !options.includePrerelease) {
16652 // Find the set of versions that are allowed to have prereleases
16653 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
16654 // That should allow `1.2.3-pr.2` to pass.
16655 // However, `1.2.4-alpha.notready` should NOT be allowed,
16656 // even though it's within the range set by the comparators.
16657 for (let i = 0; i < set.length; i++) {
16658 debug(set[i].semver)
16659 if (set[i].semver === Comparator.ANY) {
16663 if (set[i].semver.prerelease.length > 0) {
16664 const allowed = set[i].semver
16665 if (allowed.major === version.major &&
16666 allowed.minor === version.minor &&
16667 allowed.patch === version.patch) {
16673 // Version has a -pre, but it's not one of the ones we like.
16683 /***/ (function(module, exports, __webpack_require__) {
16685 const Range = __webpack_require__(105)
16686 const satisfies = (version, range, options) => {
16688 range = new Range(range, options)
16692 return range.test(version)
16694 module.exports = satisfies
16699 /***/ (function(module, exports, __webpack_require__) {
16701 const Range = __webpack_require__(105)
16703 // Mostly just for testing and legacy API reasons
16704 const toComparators = (range, options) =>
16705 new Range(range, options).set
16706 .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
16708 module.exports = toComparators
16713 /***/ (function(module, exports, __webpack_require__) {
16715 const SemVer = __webpack_require__(79)
16716 const Range = __webpack_require__(105)
16718 const maxSatisfying = (versions, range, options) => {
16721 let rangeObj = null
16723 rangeObj = new Range(range, options)
16727 versions.forEach((v) => {
16728 if (rangeObj.test(v)) {
16729 // satisfies(v, range, options)
16730 if (!max || maxSV.compare(v) === -1) {
16731 // compare(max, v, true)
16733 maxSV = new SemVer(max, options)
16739 module.exports = maxSatisfying
16744 /***/ (function(module, exports, __webpack_require__) {
16746 const SemVer = __webpack_require__(79)
16747 const Range = __webpack_require__(105)
16748 const minSatisfying = (versions, range, options) => {
16751 let rangeObj = null
16753 rangeObj = new Range(range, options)
16757 versions.forEach((v) => {
16758 if (rangeObj.test(v)) {
16759 // satisfies(v, range, options)
16760 if (!min || minSV.compare(v) === 1) {
16761 // compare(min, v, true)
16763 minSV = new SemVer(min, options)
16769 module.exports = minSatisfying
16774 /***/ (function(module, exports, __webpack_require__) {
16776 const SemVer = __webpack_require__(79)
16777 const Range = __webpack_require__(105)
16778 const gt = __webpack_require__(97)
16780 const minVersion = (range, loose) => {
16781 range = new Range(range, loose)
16783 let minver = new SemVer('0.0.0')
16784 if (range.test(minver)) {
16788 minver = new SemVer('0.0.0-0')
16789 if (range.test(minver)) {
16794 for (let i = 0; i < range.set.length; ++i) {
16795 const comparators = range.set[i]
16797 comparators.forEach((comparator) => {
16798 // Clone to avoid manipulating the comparator's semver object.
16799 const compver = new SemVer(comparator.semver.version)
16800 switch (comparator.operator) {
16802 if (compver.prerelease.length === 0) {
16805 compver.prerelease.push(0)
16807 compver.raw = compver.format()
16811 if (!minver || gt(minver, compver)) {
16817 /* Ignore maximum versions */
16819 /* istanbul ignore next */
16821 throw new Error(`Unexpected operation: ${comparator.operator}`)
16826 if (minver && range.test(minver)) {
16832 module.exports = minVersion
16837 /***/ (function(module, exports, __webpack_require__) {
16839 const Range = __webpack_require__(105)
16840 const validRange = (range, options) => {
16842 // Return '*' instead of '' so that truthiness works.
16843 // This will throw if it's invalid anyway
16844 return new Range(range, options).range || '*'
16849 module.exports = validRange
16854 /***/ (function(module, exports, __webpack_require__) {
16856 const SemVer = __webpack_require__(79)
16857 const Comparator = __webpack_require__(104)
16858 const {ANY} = Comparator
16859 const Range = __webpack_require__(105)
16860 const satisfies = __webpack_require__(106)
16861 const gt = __webpack_require__(97)
16862 const lt = __webpack_require__(98)
16863 const lte = __webpack_require__(101)
16864 const gte = __webpack_require__(100)
16866 const outside = (version, range, hilo, options) => {
16867 version = new SemVer(version, options)
16868 range = new Range(range, options)
16870 let gtfn, ltefn, ltfn, comp, ecomp
16887 throw new TypeError('Must provide a hilo val of "<" or ">"')
16890 // If it satisifes the range it is not outside
16891 if (satisfies(version, range, options)) {
16895 // From now on, variable terms are as if we're in "gtr" mode.
16896 // but note that everything is flipped for the "ltr" function.
16898 for (let i = 0; i < range.set.length; ++i) {
16899 const comparators = range.set[i]
16904 comparators.forEach((comparator) => {
16905 if (comparator.semver === ANY) {
16906 comparator = new Comparator('>=0.0.0')
16908 high = high || comparator
16909 low = low || comparator
16910 if (gtfn(comparator.semver, high.semver, options)) {
16912 } else if (ltfn(comparator.semver, low.semver, options)) {
16917 // If the edge version comparator has a operator then our version
16918 // isn't outside it
16919 if (high.operator === comp || high.operator === ecomp) {
16923 // If the lowest version comparator has an operator and our version
16924 // is less than it then it isn't higher than the range
16925 if ((!low.operator || low.operator === comp) &&
16926 ltefn(version, low.semver)) {
16928 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
16935 module.exports = outside
16940 /***/ (function(module, exports, __webpack_require__) {
16942 // Determine if version is greater than all the versions possible in the range.
16943 const outside = __webpack_require__(112)
16944 const gtr = (version, range, options) => outside(version, range, '>', options)
16945 module.exports = gtr
16950 /***/ (function(module, exports, __webpack_require__) {
16952 const outside = __webpack_require__(112)
16953 // Determine if version is less than all the versions possible in the range
16954 const ltr = (version, range, options) => outside(version, range, '<', options)
16955 module.exports = ltr
16960 /***/ (function(module, exports, __webpack_require__) {
16962 const Range = __webpack_require__(105)
16963 const intersects = (r1, r2, options) => {
16964 r1 = new Range(r1, options)
16965 r2 = new Range(r2, options)
16966 return r1.intersects(r2)
16968 module.exports = intersects
16973 /***/ (function(module, exports, __webpack_require__) {
16975 // given a set of versions and a range, create a "simplified" range
16976 // that includes the same versions that the original range does
16977 // If the original range is shorter than the simplified one, return that.
16978 const satisfies = __webpack_require__(106)
16979 const compare = __webpack_require__(87)
16980 module.exports = (versions, range, options) => {
16984 const v = versions.sort((a, b) => compare(a, b, options))
16985 for (const version of v) {
16986 const included = satisfies(version, range, options)
16993 set.push([min, prev])
17000 set.push([min, null])
17003 for (const [min, max] of set) {
17006 else if (!max && min === v[0])
17009 ranges.push(`>=${min}`)
17010 else if (min === v[0])
17011 ranges.push(`<=${max}`)
17013 ranges.push(`${min} - ${max}`)
17015 const simplified = ranges.join(' || ')
17016 const original = typeof range.raw === 'string' ? range.raw : String(range)
17017 return simplified.length < original.length ? simplified : range
17023 /***/ (function(module, exports, __webpack_require__) {
17025 const Range = __webpack_require__(105)
17026 const { ANY } = __webpack_require__(104)
17027 const satisfies = __webpack_require__(106)
17028 const compare = __webpack_require__(87)
17030 // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
17031 // - Every simple range `r1, r2, ...` is a subset of some `R1, R2, ...`
17033 // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
17034 // - If c is only the ANY comparator
17035 // - If C is only the ANY comparator, return true
17036 // - Else return false
17037 // - Let EQ be the set of = comparators in c
17038 // - If EQ is more than one, return true (null set)
17039 // - Let GT be the highest > or >= comparator in c
17040 // - Let LT be the lowest < or <= comparator in c
17041 // - If GT and LT, and GT.semver > LT.semver, return true (null set)
17043 // - If GT, and EQ does not satisfy GT, return true (null set)
17044 // - If LT, and EQ does not satisfy LT, return true (null set)
17045 // - If EQ satisfies every C, return true
17046 // - Else return false
17048 // - If GT is lower than any > or >= comp in C, return false
17049 // - If GT is >=, and GT.semver does not satisfy every C, return false
17051 // - If LT.semver is greater than that of any > comp in C, return false
17052 // - If LT is <=, and LT.semver does not satisfy every C, return false
17053 // - If any C is a = range, and GT or LT are set, return false
17054 // - Else return true
17056 const subset = (sub, dom, options) => {
17057 sub = new Range(sub, options)
17058 dom = new Range(dom, options)
17059 let sawNonNull = false
17061 OUTER: for (const simpleSub of sub.set) {
17062 for (const simpleDom of dom.set) {
17063 const isSub = simpleSubset(simpleSub, simpleDom, options)
17064 sawNonNull = sawNonNull || isSub !== null
17068 // the null set is a subset of everything, but null simple ranges in
17069 // a complex range should be ignored. so if we saw a non-null range,
17070 // then we know this isn't a subset, but if EVERY simple range was null,
17071 // then it is a subset.
17078 const simpleSubset = (sub, dom, options) => {
17079 if (sub.length === 1 && sub[0].semver === ANY)
17080 return dom.length === 1 && dom[0].semver === ANY
17082 const eqSet = new Set()
17084 for (const c of sub) {
17085 if (c.operator === '>' || c.operator === '>=')
17086 gt = higherGT(gt, c, options)
17087 else if (c.operator === '<' || c.operator === '<=')
17088 lt = lowerLT(lt, c, options)
17090 eqSet.add(c.semver)
17093 if (eqSet.size > 1)
17098 gtltComp = compare(gt.semver, lt.semver, options)
17101 else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<='))
17105 // will iterate one or zero times
17106 for (const eq of eqSet) {
17107 if (gt && !satisfies(eq, String(gt), options))
17110 if (lt && !satisfies(eq, String(lt), options))
17113 for (const c of dom) {
17114 if (!satisfies(eq, String(c), options))
17121 let hasDomLT, hasDomGT
17122 for (const c of dom) {
17123 hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
17124 hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
17126 if (c.operator === '>' || c.operator === '>=') {
17127 higher = higherGT(gt, c, options)
17130 } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options))
17134 if (c.operator === '<' || c.operator === '<=') {
17135 lower = lowerLT(lt, c, options)
17138 } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options))
17141 if (!c.operator && (lt || gt) && gtltComp !== 0)
17145 // if there was a < or >, and nothing in the dom, then must be false
17146 // UNLESS it was limited by another range in the other direction.
17147 // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
17148 if (gt && hasDomLT && !lt && gtltComp !== 0)
17151 if (lt && hasDomGT && !gt && gtltComp !== 0)
17157 // >=1.2.3 is lower than >1.2.3
17158 const higherGT = (a, b, options) => {
17161 const comp = compare(a.semver, b.semver, options)
17162 return comp > 0 ? a
17164 : b.operator === '>' && a.operator === '>=' ? b
17168 // <=1.2.3 is higher than <1.2.3
17169 const lowerLT = (a, b, options) => {
17172 const comp = compare(a.semver, b.semver, options)
17173 return comp < 0 ? a
17175 : b.operator === '<' && a.operator === '<=' ? b
17179 module.exports = subset
17184 /***/ (function(module, exports, __webpack_require__) {
17188 // Polyfills for node 0.8
17189 __webpack_require__(119);
17190 __webpack_require__(120);
17191 __webpack_require__(121);
17194 exports.Parse = __webpack_require__(122);
17195 exports.ParseOne = __webpack_require__(186);
17196 exports.Extract = __webpack_require__(188);
17197 exports.Open = __webpack_require__(211);
17201 /***/ (function(module, exports, __webpack_require__) {
17206 var listenerCount = __webpack_require__(68).listenerCount
17207 // listenerCount isn't in node 0.10, so here's a basic polyfill
17208 listenerCount = listenerCount || function (ee, event) {
17209 var listeners = ee && ee._events && ee._events[event]
17210 if (Array.isArray(listeners)) {
17211 return listeners.length
17212 } else if (typeof listeners === 'function') {
17219 module.exports = listenerCount
17224 /***/ (function(module, exports, __webpack_require__) {
17229 if (!Buffer.prototype.indexOf) {
17230 Buffer.prototype.indexOf = function (value, offset) {
17231 offset = offset || 0;
17233 // Always wrap the input as a Buffer so that this method will support any
17234 // data type such as array octet, string or buffer.
17235 if (typeof value === "string" || value instanceof String) {
17236 value = new Buffer(value);
17237 } else if (typeof value === "number" || value instanceof Number) {
17238 value = new Buffer([ value ]);
17241 var len = value.length;
17243 for (var i = offset; i <= this.length - len; i++) {
17244 var mismatch = false;
17245 for (var j = 0; j < len; j++) {
17246 if (this[i + j] != value[j]) {
17261 function bufferLastIndexOf (value, offset) {
17263 // Always wrap the input as a Buffer so that this method will support any
17264 // data type such as array octet, string or buffer.
17265 if (typeof value === "string" || value instanceof String) {
17266 value = new Buffer(value);
17267 } else if (typeof value === "number" || value instanceof Number) {
17268 value = new Buffer([ value ]);
17271 var len = value.length;
17272 offset = offset || this.length - len;
17274 for (var i = offset; i >= 0; i--) {
17275 var mismatch = false;
17276 for (var j = 0; j < len; j++) {
17277 if (this[i + j] != value[j]) {
17292 if (Buffer.prototype.lastIndexOf) {
17293 // check Buffer#lastIndexOf is usable: https://github.com/nodejs/node/issues/4604
17294 if (new Buffer ("ABC").lastIndexOf ("ABC") === -1)
17295 Buffer.prototype.lastIndexOf = bufferLastIndexOf;
17297 Buffer.prototype.lastIndexOf = bufferLastIndexOf;
17303 /***/ (function(module, exports) {
17305 (function (global, undefined) {
17308 if (global.setImmediate) {
17312 var nextHandle = 1; // Spec says greater than zero
17313 var tasksByHandle = {};
17314 var currentlyRunningATask = false;
17315 var doc = global.document;
17316 var registerImmediate;
17318 function setImmediate(callback) {
17319 // Callback can either be a function or a string
17320 if (typeof callback !== "function") {
17321 callback = new Function("" + callback);
17323 // Copy function arguments
17324 var args = new Array(arguments.length - 1);
17325 for (var i = 0; i < args.length; i++) {
17326 args[i] = arguments[i + 1];
17328 // Store and register the task
17329 var task = { callback: callback, args: args };
17330 tasksByHandle[nextHandle] = task;
17331 registerImmediate(nextHandle);
17332 return nextHandle++;
17335 function clearImmediate(handle) {
17336 delete tasksByHandle[handle];
17339 function run(task) {
17340 var callback = task.callback;
17341 var args = task.args;
17342 switch (args.length) {
17350 callback(args[0], args[1]);
17353 callback(args[0], args[1], args[2]);
17356 callback.apply(undefined, args);
17361 function runIfPresent(handle) {
17362 // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
17363 // So if we're currently running a task, we'll need to delay this invocation.
17364 if (currentlyRunningATask) {
17365 // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
17366 // "too much recursion" error.
17367 setTimeout(runIfPresent, 0, handle);
17369 var task = tasksByHandle[handle];
17371 currentlyRunningATask = true;
17375 clearImmediate(handle);
17376 currentlyRunningATask = false;
17382 function installNextTickImplementation() {
17383 registerImmediate = function(handle) {
17384 process.nextTick(function () { runIfPresent(handle); });
17388 function canUsePostMessage() {
17389 // The test against `importScripts` prevents this implementation from being installed inside a web worker,
17390 // where `global.postMessage` means something completely different and can't be used for this purpose.
17391 if (global.postMessage && !global.importScripts) {
17392 var postMessageIsAsynchronous = true;
17393 var oldOnMessage = global.onmessage;
17394 global.onmessage = function() {
17395 postMessageIsAsynchronous = false;
17397 global.postMessage("", "*");
17398 global.onmessage = oldOnMessage;
17399 return postMessageIsAsynchronous;
17403 function installPostMessageImplementation() {
17404 // Installs an event handler on `global` for the `message` event: see
17405 // * https://developer.mozilla.org/en/DOM/window.postMessage
17406 // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
17408 var messagePrefix = "setImmediate$" + Math.random() + "$";
17409 var onGlobalMessage = function(event) {
17410 if (event.source === global &&
17411 typeof event.data === "string" &&
17412 event.data.indexOf(messagePrefix) === 0) {
17413 runIfPresent(+event.data.slice(messagePrefix.length));
17417 if (global.addEventListener) {
17418 global.addEventListener("message", onGlobalMessage, false);
17420 global.attachEvent("onmessage", onGlobalMessage);
17423 registerImmediate = function(handle) {
17424 global.postMessage(messagePrefix + handle, "*");
17428 function installMessageChannelImplementation() {
17429 var channel = new MessageChannel();
17430 channel.port1.onmessage = function(event) {
17431 var handle = event.data;
17432 runIfPresent(handle);
17435 registerImmediate = function(handle) {
17436 channel.port2.postMessage(handle);
17440 function installReadyStateChangeImplementation() {
17441 var html = doc.documentElement;
17442 registerImmediate = function(handle) {
17443 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
17444 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
17445 var script = doc.createElement("script");
17446 script.onreadystatechange = function () {
17447 runIfPresent(handle);
17448 script.onreadystatechange = null;
17449 html.removeChild(script);
17452 html.appendChild(script);
17456 function installSetTimeoutImplementation() {
17457 registerImmediate = function(handle) {
17458 setTimeout(runIfPresent, 0, handle);
17462 // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
17463 var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
17464 attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
17466 // Don't get fooled by e.g. browserify environments.
17467 if ({}.toString.call(global.process) === "[object process]") {
17468 // For Node.js before 0.9
17469 installNextTickImplementation();
17471 } else if (canUsePostMessage()) {
17472 // For non-IE10 modern browsers
17473 installPostMessageImplementation();
17475 } else if (global.MessageChannel) {
17476 // For web workers, where supported
17477 installMessageChannelImplementation();
17479 } else if (doc && "onreadystatechange" in doc.createElement("script")) {
17481 installReadyStateChangeImplementation();
17484 // For older browsers
17485 installSetTimeoutImplementation();
17488 attachTo.setImmediate = setImmediate;
17489 attachTo.clearImmediate = clearImmediate;
17490 }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
17495 /***/ (function(module, exports, __webpack_require__) {
17497 var util = __webpack_require__(50);
17498 var zlib = __webpack_require__(48);
17499 var Stream = __webpack_require__(44);
17500 var binary = __webpack_require__(123);
17501 var Promise = __webpack_require__(128);
17502 var PullStream = __webpack_require__(164);
17503 var NoopStream = __webpack_require__(182);
17504 var BufferStream = __webpack_require__(183);
17505 var parseExtraField = __webpack_require__(184);
17506 var Buffer = __webpack_require__(165);
17507 var parseDateTime = __webpack_require__(185);
17509 // Backwards compatibility for node versions < 8
17510 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
17511 Stream = __webpack_require__(167);
17513 var endDirectorySignature = Buffer.alloc(4);
17514 endDirectorySignature.writeUInt32LE(0x06054b50, 0);
17516 function Parse(opts) {
17517 if (!(this instanceof Parse)) {
17518 return new Parse(opts);
17521 self._opts = opts || { verbose: false };
17523 PullStream.call(self, self._opts);
17524 self.on('finish',function() {
17525 self.emit('close');
17527 self._readRecord().catch(function(e) {
17528 if (!self.__emittedError || self.__emittedError !== e)
17529 self.emit('error',e);
17533 util.inherits(Parse, PullStream);
17535 Parse.prototype._readRecord = function () {
17537 return self.pull(4).then(function(data) {
17538 if (data.length === 0)
17541 var signature = data.readUInt32LE(0);
17543 if (signature === 0x34327243) {
17544 return self._readCrxHeader();
17546 if (signature === 0x04034b50) {
17547 return self._readFile();
17549 else if (signature === 0x02014b50) {
17550 self.__ended = true;
17551 return self._readCentralDirectoryFileHeader();
17553 else if (signature === 0x06054b50) {
17554 return self._readEndOfCentralDirectoryRecord();
17556 else if (self.__ended) {
17557 return self.pull(endDirectorySignature).then(function() {
17558 return self._readEndOfCentralDirectoryRecord();
17562 self.emit('error', new Error('invalid signature: 0x' + signature.toString(16)));
17566 Parse.prototype._readCrxHeader = function() {
17568 return self.pull(12).then(function(data) {
17569 self.crxHeader = binary.parse(data)
17570 .word32lu('version')
17571 .word32lu('pubKeyLength')
17572 .word32lu('signatureLength')
17574 return self.pull(self.crxHeader.pubKeyLength + self.crxHeader.signatureLength);
17575 }).then(function(data) {
17576 self.crxHeader.publicKey = data.slice(0,self.crxHeader.pubKeyLength);
17577 self.crxHeader.signature = data.slice(self.crxHeader.pubKeyLength);
17578 self.emit('crx-header',self.crxHeader);
17579 return self._readRecord();
17583 Parse.prototype._readFile = function () {
17585 return self.pull(26).then(function(data) {
17586 var vars = binary.parse(data)
17587 .word16lu('versionsNeededToExtract')
17589 .word16lu('compressionMethod')
17590 .word16lu('lastModifiedTime')
17591 .word16lu('lastModifiedDate')
17593 .word32lu('compressedSize')
17594 .word32lu('uncompressedSize')
17595 .word16lu('fileNameLength')
17596 .word16lu('extraFieldLength')
17599 vars.lastModifiedDateTime = parseDateTime(vars.lastModifiedDate, vars.lastModifiedTime);
17601 if (self.crxHeader) vars.crxHeader = self.crxHeader;
17603 return self.pull(vars.fileNameLength).then(function(fileNameBuffer) {
17604 var fileName = fileNameBuffer.toString('utf8');
17605 var entry = Stream.PassThrough();
17606 var __autodraining = false;
17608 entry.autodrain = function() {
17609 __autodraining = true;
17610 var draining = entry.pipe(NoopStream());
17611 draining.promise = function() {
17612 return new Promise(function(resolve, reject) {
17613 draining.on('finish',resolve);
17614 draining.on('error',reject);
17620 entry.buffer = function() {
17621 return BufferStream(entry);
17624 entry.path = fileName;
17626 entry.props.path = fileName;
17627 entry.props.pathBuffer = fileNameBuffer;
17628 entry.props.flags = {
17629 "isUnicode": vars.flags & 0x11
17631 entry.type = (vars.uncompressedSize === 0 && /[\/\\]$/.test(fileName)) ? 'Directory' : 'File';
17633 if (self._opts.verbose) {
17634 if (entry.type === 'Directory') {
17635 console.log(' creating:', fileName);
17636 } else if (entry.type === 'File') {
17637 if (vars.compressionMethod === 0) {
17638 console.log(' extracting:', fileName);
17640 console.log(' inflating:', fileName);
17645 return self.pull(vars.extraFieldLength).then(function(extraField) {
17646 var extra = parseExtraField(extraField, vars);
17649 entry.extra = extra;
17651 if (self._opts.forceStream) {
17654 self.emit('entry', entry);
17656 if (self._readableState.pipesCount || (self._readableState.pipes && self._readableState.pipes.length))
17660 if (self._opts.verbose)
17667 var fileSizeKnown = !(vars.flags & 0x08) || vars.compressedSize > 0,
17670 entry.__autodraining = __autodraining; // expose __autodraining for test purposes
17671 var inflater = (vars.compressionMethod && !__autodraining) ? zlib.createInflateRaw() : Stream.PassThrough();
17673 if (fileSizeKnown) {
17674 entry.size = vars.uncompressedSize;
17675 eof = vars.compressedSize;
17677 eof = Buffer.alloc(4);
17678 eof.writeUInt32LE(0x08074b50, 0);
17681 return new Promise(function(resolve, reject) {
17684 .on('error',function(err) { self.emit('error',err);})
17686 .on('finish', function() {
17687 return fileSizeKnown ?
17688 self._readRecord().then(resolve).catch(reject) :
17689 self._processDataDescriptor(entry).then(resolve).catch(reject);
17697 Parse.prototype._processDataDescriptor = function (entry) {
17699 return self.pull(16).then(function(data) {
17700 var vars = binary.parse(data)
17701 .word32lu('dataDescriptorSignature')
17703 .word32lu('compressedSize')
17704 .word32lu('uncompressedSize')
17707 entry.size = vars.uncompressedSize;
17708 return self._readRecord();
17712 Parse.prototype._readCentralDirectoryFileHeader = function () {
17714 return self.pull(42).then(function(data) {
17716 var vars = binary.parse(data)
17717 .word16lu('versionMadeBy')
17718 .word16lu('versionsNeededToExtract')
17720 .word16lu('compressionMethod')
17721 .word16lu('lastModifiedTime')
17722 .word16lu('lastModifiedDate')
17724 .word32lu('compressedSize')
17725 .word32lu('uncompressedSize')
17726 .word16lu('fileNameLength')
17727 .word16lu('extraFieldLength')
17728 .word16lu('fileCommentLength')
17729 .word16lu('diskNumber')
17730 .word16lu('internalFileAttributes')
17731 .word32lu('externalFileAttributes')
17732 .word32lu('offsetToLocalFileHeader')
17735 return self.pull(vars.fileNameLength).then(function(fileName) {
17736 vars.fileName = fileName.toString('utf8');
17737 return self.pull(vars.extraFieldLength);
17739 .then(function(extraField) {
17740 return self.pull(vars.fileCommentLength);
17742 .then(function(fileComment) {
17743 return self._readRecord();
17748 Parse.prototype._readEndOfCentralDirectoryRecord = function() {
17750 return self.pull(18).then(function(data) {
17752 var vars = binary.parse(data)
17753 .word16lu('diskNumber')
17754 .word16lu('diskStart')
17755 .word16lu('numberOfRecordsOnDisk')
17756 .word16lu('numberOfRecords')
17757 .word32lu('sizeOfCentralDirectory')
17758 .word32lu('offsetToStartOfCentralDirectory')
17759 .word16lu('commentLength')
17762 return self.pull(vars.commentLength).then(function(comment) {
17763 comment = comment.toString('utf8');
17771 Parse.prototype.promise = function() {
17773 return new Promise(function(resolve,reject) {
17774 self.on('finish',resolve);
17775 self.on('error',reject);
17779 module.exports = Parse;
17784 /***/ (function(module, exports, __webpack_require__) {
17786 var Chainsaw = __webpack_require__(124);
17787 var EventEmitter = __webpack_require__(68).EventEmitter;
17788 var Buffers = __webpack_require__(126);
17789 var Vars = __webpack_require__(127);
17790 var Stream = __webpack_require__(44).Stream;
17792 exports = module.exports = function (bufOrEm, eventName) {
17793 if (Buffer.isBuffer(bufOrEm)) {
17794 return exports.parse(bufOrEm);
17797 var s = exports.stream();
17798 if (bufOrEm && bufOrEm.pipe) {
17801 else if (bufOrEm) {
17802 bufOrEm.on(eventName || 'data', function (buf) {
17806 bufOrEm.on('end', function () {
17813 exports.stream = function (input) {
17814 if (input) return exports.apply(null, arguments);
17816 var pending = null;
17817 function getBytes (bytes, cb, skip) {
17821 cb : function (buf) {
17830 function dispatch () {
17832 if (caughtEnd) done = true;
17835 if (typeof pending === 'function') {
17839 var bytes = offset + pending.bytes;
17841 if (buffers.length >= bytes) {
17843 if (offset == null) {
17844 buf = buffers.splice(0, bytes);
17845 if (!pending.skip) {
17850 if (!pending.skip) {
17851 buf = buffers.slice(offset, bytes);
17856 if (pending.skip) {
17866 function builder (saw) {
17867 function next () { if (!done) saw.next() }
17869 var self = words(function (bytes, cb) {
17870 return function (name) {
17871 getBytes(bytes, function (buf) {
17872 vars.set(name, cb(buf));
17878 self.tap = function (cb) {
17879 saw.nest(cb, vars.store);
17882 self.into = function (key, cb) {
17883 if (!vars.get(key)) vars.set(key, {});
17885 vars = Vars(parent.get(key));
17887 saw.nest(function () {
17888 cb.apply(this, arguments);
17889 this.tap(function () {
17895 self.flush = function () {
17900 self.loop = function (cb) {
17903 saw.nest(false, function loop () {
17904 this.vars = vars.store;
17905 cb.call(this, function () {
17909 this.tap(function () {
17910 if (end) saw.next()
17911 else loop.call(this)
17916 self.buffer = function (name, bytes) {
17917 if (typeof bytes === 'string') {
17918 bytes = vars.get(bytes);
17921 getBytes(bytes, function (buf) {
17922 vars.set(name, buf);
17927 self.skip = function (bytes) {
17928 if (typeof bytes === 'string') {
17929 bytes = vars.get(bytes);
17932 getBytes(bytes, function () {
17937 self.scan = function find (name, search) {
17938 if (typeof search === 'string') {
17939 search = new Buffer(search);
17941 else if (!Buffer.isBuffer(search)) {
17942 throw new Error('search must be a Buffer or a string');
17946 pending = function () {
17947 var pos = buffers.indexOf(search, offset + taken);
17948 var i = pos-offset-taken;
17951 if (offset != null) {
17954 buffers.slice(offset, offset + taken + i)
17956 offset += taken + i + search.length;
17961 buffers.slice(0, taken + i)
17963 buffers.splice(0, taken + i + search.length);
17968 i = Math.max(buffers.length - search.length - offset - taken, 0);
17975 self.peek = function (cb) {
17977 saw.nest(function () {
17978 cb.call(this, vars.store);
17979 this.tap(function () {
17988 var stream = Chainsaw.light(builder);
17989 stream.writable = true;
17991 var buffers = Buffers();
17993 stream.write = function (buf) {
18000 var done = false, caughtEnd = false;
18001 stream.end = function () {
18005 stream.pipe = Stream.prototype.pipe;
18006 Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) {
18007 stream[name] = EventEmitter.prototype[name];
18013 exports.parse = function parse (buffer) {
18014 var self = words(function (bytes, cb) {
18015 return function (name) {
18016 if (offset + bytes <= buffer.length) {
18017 var buf = buffer.slice(offset, offset + bytes);
18019 vars.set(name, cb(buf));
18022 vars.set(name, null);
18030 self.vars = vars.store;
18032 self.tap = function (cb) {
18033 cb.call(self, vars.store);
18037 self.into = function (key, cb) {
18038 if (!vars.get(key)) {
18042 vars = Vars(parent.get(key));
18043 cb.call(self, vars.store);
18048 self.loop = function (cb) {
18050 var ender = function () { end = true };
18051 while (end === false) {
18052 cb.call(self, ender, vars.store);
18057 self.buffer = function (name, size) {
18058 if (typeof size === 'string') {
18059 size = vars.get(size);
18061 var buf = buffer.slice(offset, Math.min(buffer.length, offset + size));
18063 vars.set(name, buf);
18068 self.skip = function (bytes) {
18069 if (typeof bytes === 'string') {
18070 bytes = vars.get(bytes);
18077 self.scan = function (name, search) {
18078 if (typeof search === 'string') {
18079 search = new Buffer(search);
18081 else if (!Buffer.isBuffer(search)) {
18082 throw new Error('search must be a Buffer or a string');
18084 vars.set(name, null);
18086 // simple but slow string search
18087 for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) {
18090 j < search.length && buffer[offset+i+j] === search[j];
18093 if (j === search.length) break;
18096 vars.set(name, buffer.slice(offset, offset + i));
18097 offset += i + search.length;
18101 self.peek = function (cb) {
18103 cb.call(self, vars.store);
18108 self.flush = function () {
18113 self.eof = function () {
18114 return offset >= buffer.length;
18120 // convert byte strings to unsigned little endian numbers
18121 function decodeLEu (bytes) {
18123 for (var i = 0; i < bytes.length; i++) {
18124 acc += Math.pow(256,i) * bytes[i];
18129 // convert byte strings to unsigned big endian numbers
18130 function decodeBEu (bytes) {
18132 for (var i = 0; i < bytes.length; i++) {
18133 acc += Math.pow(256, bytes.length - i - 1) * bytes[i];
18138 // convert byte strings to signed big endian numbers
18139 function decodeBEs (bytes) {
18140 var val = decodeBEu(bytes);
18141 if ((bytes[0] & 0x80) == 0x80) {
18142 val -= Math.pow(256, bytes.length);
18147 // convert byte strings to signed little endian numbers
18148 function decodeLEs (bytes) {
18149 var val = decodeLEu(bytes);
18150 if ((bytes[bytes.length - 1] & 0x80) == 0x80) {
18151 val -= Math.pow(256, bytes.length);
18156 function words (decode) {
18159 [ 1, 2, 4, 8 ].forEach(function (bytes) {
18160 var bits = bytes * 8;
18162 self['word' + bits + 'le']
18163 = self['word' + bits + 'lu']
18164 = decode(bytes, decodeLEu);
18166 self['word' + bits + 'ls']
18167 = decode(bytes, decodeLEs);
18169 self['word' + bits + 'be']
18170 = self['word' + bits + 'bu']
18171 = decode(bytes, decodeBEu);
18173 self['word' + bits + 'bs']
18174 = decode(bytes, decodeBEs);
18177 // word8be(n) == word8le(n) for all n
18178 self.word8 = self.word8u = self.word8be;
18179 self.word8s = self.word8bs;
18187 /***/ (function(module, exports, __webpack_require__) {
18189 var Traverse = __webpack_require__(125);
18190 var EventEmitter = __webpack_require__(68).EventEmitter;
18192 module.exports = Chainsaw;
18193 function Chainsaw (builder) {
18194 var saw = Chainsaw.saw(builder, {});
18195 var r = builder.call(saw.handlers, saw);
18196 if (r !== undefined) saw.handlers = r;
18198 return saw.chain();
18201 Chainsaw.light = function ChainsawLight (builder) {
18202 var saw = Chainsaw.saw(builder, {});
18203 var r = builder.call(saw.handlers, saw);
18204 if (r !== undefined) saw.handlers = r;
18205 return saw.chain();
18208 Chainsaw.saw = function (builder, handlers) {
18209 var saw = new EventEmitter;
18210 saw.handlers = handlers;
18213 saw.chain = function () {
18214 var ch = Traverse(saw.handlers).map(function (node) {
18215 if (this.isRoot) return node;
18216 var ps = this.path;
18218 if (typeof node === 'function') {
18219 this.update(function () {
18222 args : [].slice.call(arguments)
18229 process.nextTick(function () {
18237 saw.pop = function () {
18238 return saw.actions.shift();
18241 saw.next = function () {
18242 var action = saw.pop();
18247 else if (!action.trap) {
18248 var node = saw.handlers;
18249 action.path.forEach(function (key) { node = node[key] });
18250 node.apply(saw.handlers, action.args);
18254 saw.nest = function (cb) {
18255 var args = [].slice.call(arguments, 1);
18256 var autonext = true;
18258 if (typeof cb === 'boolean') {
18263 var s = Chainsaw.saw(builder, {});
18264 var r = builder.call(s.handlers, s);
18266 if (r !== undefined) s.handlers = r;
18268 // If we are recording...
18269 if ("undefined" !== typeof saw.step) {
18270 // ... our children should, too
18274 cb.apply(s.chain(), args);
18275 if (autonext !== false) s.on('end', saw.next);
18278 saw.record = function () {
18279 upgradeChainsaw(saw);
18282 ['trap', 'down', 'jump'].forEach(function (method) {
18283 saw[method] = function () {
18284 throw new Error("To use the trap, down and jump features, please "+
18285 "call record() first to start recording actions.");
18292 function upgradeChainsaw(saw) {
18296 saw.pop = function () {
18297 return saw.actions[saw.step++];
18300 saw.trap = function (name, cb) {
18301 var ps = Array.isArray(name) ? name : [name];
18310 saw.down = function (name) {
18311 var ps = (Array.isArray(name) ? name : [name]).join('/');
18312 var i = saw.actions.slice(saw.step).map(function (x) {
18313 if (x.trap && x.step <= saw.step) return false;
18314 return x.path.join('/') == ps;
18317 if (i >= 0) saw.step += i;
18318 else saw.step = saw.actions.length;
18320 var act = saw.actions[saw.step - 1];
18321 if (act && act.trap) {
18323 saw.step = act.step;
18329 saw.jump = function (step) {
18338 /***/ (function(module, exports) {
18340 module.exports = Traverse;
18341 function Traverse (obj) {
18342 if (!(this instanceof Traverse)) return new Traverse(obj);
18346 Traverse.prototype.get = function (ps) {
18347 var node = this.value;
18348 for (var i = 0; i < ps.length; i ++) {
18350 if (!Object.hasOwnProperty.call(node, key)) {
18359 Traverse.prototype.set = function (ps, value) {
18360 var node = this.value;
18361 for (var i = 0; i < ps.length - 1; i ++) {
18363 if (!Object.hasOwnProperty.call(node, key)) node[key] = {};
18366 node[ps[i]] = value;
18370 Traverse.prototype.map = function (cb) {
18371 return walk(this.value, cb, true);
18374 Traverse.prototype.forEach = function (cb) {
18375 this.value = walk(this.value, cb, false);
18379 Traverse.prototype.reduce = function (cb, init) {
18380 var skip = arguments.length === 1;
18381 var acc = skip ? this.value : init;
18382 this.forEach(function (x) {
18383 if (!this.isRoot || !skip) {
18384 acc = cb.call(this, acc, x);
18390 Traverse.prototype.deepEqual = function (obj) {
18391 if (arguments.length !== 1) {
18393 'deepEqual requires exactly one object to compare against'
18400 this.forEach(function (y) {
18401 var notEqual = (function () {
18407 //if (node === undefined || node === null) return notEqual();
18409 if (!this.isRoot) {
18411 if (!Object.hasOwnProperty.call(node, this.key)) {
18415 if (typeof node !== 'object') return notEqual();
18416 node = node[this.key];
18421 this.post(function () {
18425 var toS = function (o) {
18426 return Object.prototype.toString.call(o);
18429 if (this.circular) {
18430 if (Traverse(obj).get(this.circular.path) !== x) notEqual();
18432 else if (typeof x !== typeof y) {
18435 else if (x === null || y === null || x === undefined || y === undefined) {
18436 if (x !== y) notEqual();
18438 else if (x.__proto__ !== y.__proto__) {
18441 else if (x === y) {
18444 else if (typeof x === 'function') {
18445 if (x instanceof RegExp) {
18446 // both regexps on account of the __proto__ check
18447 if (x.toString() != y.toString()) notEqual();
18449 else if (x !== y) notEqual();
18451 else if (typeof x === 'object') {
18452 if (toS(y) === '[object Arguments]'
18453 || toS(x) === '[object Arguments]') {
18454 if (toS(x) !== toS(y)) {
18458 else if (x instanceof Date || y instanceof Date) {
18459 if (!(x instanceof Date) || !(y instanceof Date)
18460 || x.getTime() !== y.getTime()) {
18465 var kx = Object.keys(x);
18466 var ky = Object.keys(y);
18467 if (kx.length !== ky.length) return notEqual();
18468 for (var i = 0; i < kx.length; i++) {
18470 if (!Object.hasOwnProperty.call(y, k)) {
18481 Traverse.prototype.paths = function () {
18483 this.forEach(function (x) {
18484 acc.push(this.path);
18489 Traverse.prototype.nodes = function () {
18491 this.forEach(function (x) {
18492 acc.push(this.node);
18497 Traverse.prototype.clone = function () {
18498 var parents = [], nodes = [];
18500 return (function clone (src) {
18501 for (var i = 0; i < parents.length; i++) {
18502 if (parents[i] === src) {
18507 if (typeof src === 'object' && src !== null) {
18508 var dst = copy(src);
18513 Object.keys(src).forEach(function (key) {
18514 dst[key] = clone(src[key]);
18527 function walk (root, cb, immutable) {
18532 return (function walker (node_) {
18533 var node = immutable ? copy(node_) : node_;
18534 var modifiers = {};
18539 path : [].concat(path),
18540 parent : parents.slice(-1)[0],
18541 key : path.slice(-1)[0],
18542 isRoot : path.length === 0,
18543 level : path.length,
18545 update : function (x) {
18546 if (!state.isRoot) {
18547 state.parent.node[state.key] = x;
18551 'delete' : function () {
18552 delete state.parent.node[state.key];
18554 remove : function () {
18555 if (Array.isArray(state.parent.node)) {
18556 state.parent.node.splice(state.key, 1);
18559 delete state.parent.node[state.key];
18562 before : function (f) { modifiers.before = f },
18563 after : function (f) { modifiers.after = f },
18564 pre : function (f) { modifiers.pre = f },
18565 post : function (f) { modifiers.post = f },
18566 stop : function () { alive = false }
18569 if (!alive) return state;
18571 if (typeof node === 'object' && node !== null) {
18572 state.isLeaf = Object.keys(node).length == 0;
18574 for (var i = 0; i < parents.length; i++) {
18575 if (parents[i].node_ === node_) {
18576 state.circular = parents[i];
18582 state.isLeaf = true;
18585 state.notLeaf = !state.isLeaf;
18586 state.notRoot = !state.isRoot;
18588 // use return values to update if defined
18589 var ret = cb.call(state, state.node);
18590 if (ret !== undefined && state.update) state.update(ret);
18591 if (modifiers.before) modifiers.before.call(state, state.node);
18593 if (typeof state.node == 'object'
18594 && state.node !== null && !state.circular) {
18595 parents.push(state);
18597 var keys = Object.keys(state.node);
18598 keys.forEach(function (key, i) {
18601 if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);
18603 var child = walker(state.node[key]);
18604 if (immutable && Object.hasOwnProperty.call(state.node, key)) {
18605 state.node[key] = child.node;
18608 child.isLast = i == keys.length - 1;
18609 child.isFirst = i == 0;
18611 if (modifiers.post) modifiers.post.call(state, child);
18618 if (modifiers.after) modifiers.after.call(state, state.node);
18624 Object.keys(Traverse.prototype).forEach(function (key) {
18625 Traverse[key] = function (obj) {
18626 var args = [].slice.call(arguments, 1);
18627 var t = Traverse(obj);
18628 return t[key].apply(t, args);
18632 function copy (src) {
18633 if (typeof src === 'object' && src !== null) {
18636 if (Array.isArray(src)) {
18639 else if (src instanceof Date) {
18640 dst = new Date(src);
18642 else if (src instanceof Boolean) {
18643 dst = new Boolean(src);
18645 else if (src instanceof Number) {
18646 dst = new Number(src);
18648 else if (src instanceof String) {
18649 dst = new String(src);
18652 dst = Object.create(Object.getPrototypeOf(src));
18655 Object.keys(src).forEach(function (key) {
18656 dst[key] = src[key];
18666 /***/ (function(module, exports) {
18668 module.exports = Buffers;
18670 function Buffers (bufs) {
18671 if (!(this instanceof Buffers)) return new Buffers(bufs);
18672 this.buffers = bufs || [];
18673 this.length = this.buffers.reduce(function (size, buf) {
18674 return size + buf.length
18678 Buffers.prototype.push = function () {
18679 for (var i = 0; i < arguments.length; i++) {
18680 if (!Buffer.isBuffer(arguments[i])) {
18681 throw new TypeError('Tried to push a non-buffer');
18685 for (var i = 0; i < arguments.length; i++) {
18686 var buf = arguments[i];
18687 this.buffers.push(buf);
18688 this.length += buf.length;
18690 return this.length;
18693 Buffers.prototype.unshift = function () {
18694 for (var i = 0; i < arguments.length; i++) {
18695 if (!Buffer.isBuffer(arguments[i])) {
18696 throw new TypeError('Tried to unshift a non-buffer');
18700 for (var i = 0; i < arguments.length; i++) {
18701 var buf = arguments[i];
18702 this.buffers.unshift(buf);
18703 this.length += buf.length;
18705 return this.length;
18708 Buffers.prototype.copy = function (dst, dStart, start, end) {
18709 return this.slice(start, end).copy(dst, dStart, 0, end - start);
18712 Buffers.prototype.splice = function (i, howMany) {
18713 var buffers = this.buffers;
18714 var index = i >= 0 ? i : this.length - i;
18715 var reps = [].slice.call(arguments, 2);
18717 if (howMany === undefined) {
18718 howMany = this.length - index;
18720 else if (howMany > this.length - index) {
18721 howMany = this.length - index;
18724 for (var i = 0; i < reps.length; i++) {
18725 this.length += reps[i].length;
18728 var removed = new Buffers();
18731 var startBytes = 0;
18734 ii < buffers.length && startBytes + buffers[ii].length < index;
18736 ) { startBytes += buffers[ii].length }
18738 if (index - startBytes > 0) {
18739 var start = index - startBytes;
18741 if (start + howMany < buffers[ii].length) {
18742 removed.push(buffers[ii].slice(start, start + howMany));
18744 var orig = buffers[ii];
18745 //var buf = new Buffer(orig.length - howMany);
18746 var buf0 = new Buffer(start);
18747 for (var i = 0; i < start; i++) {
18751 var buf1 = new Buffer(orig.length - start - howMany);
18752 for (var i = start + howMany; i < orig.length; i++) {
18753 buf1[ i - howMany - start ] = orig[i]
18756 if (reps.length > 0) {
18757 var reps_ = reps.slice();
18758 reps_.unshift(buf0);
18760 buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_));
18761 ii += reps_.length;
18765 buffers.splice(ii, 1, buf0, buf1);
18766 //buffers[ii] = buf;
18771 removed.push(buffers[ii].slice(start));
18772 buffers[ii] = buffers[ii].slice(0, start);
18777 if (reps.length > 0) {
18778 buffers.splice.apply(buffers, [ ii, 0 ].concat(reps));
18782 while (removed.length < howMany) {
18783 var buf = buffers[ii];
18784 var len = buf.length;
18785 var take = Math.min(len, howMany - removed.length);
18787 if (take === len) {
18789 buffers.splice(ii, 1);
18792 removed.push(buf.slice(0, take));
18793 buffers[ii] = buffers[ii].slice(take);
18797 this.length -= removed.length;
18802 Buffers.prototype.slice = function (i, j) {
18803 var buffers = this.buffers;
18804 if (j === undefined) j = this.length;
18805 if (i === undefined) i = 0;
18807 if (j > this.length) j = this.length;
18809 var startBytes = 0;
18812 si < buffers.length && startBytes + buffers[si].length <= i;
18814 ) { startBytes += buffers[si].length }
18816 var target = new Buffer(j - i);
18819 for (var ii = si; ti < j - i && ii < buffers.length; ii++) {
18820 var len = buffers[ii].length;
18822 var start = ti === 0 ? i - startBytes : 0;
18823 var end = ti + len >= j - i
18824 ? Math.min(start + (j - i) - ti, len)
18828 buffers[ii].copy(target, ti, start, end);
18835 Buffers.prototype.pos = function (i) {
18836 if (i < 0 || i >= this.length) throw new Error('oob');
18837 var l = i, bi = 0, bu = null;
18839 bu = this.buffers[bi];
18840 if (l < bu.length) {
18841 return {buf: bi, offset: l};
18849 Buffers.prototype.get = function get (i) {
18850 var pos = this.pos(i);
18852 return this.buffers[pos.buf].get(pos.offset);
18855 Buffers.prototype.set = function set (i, b) {
18856 var pos = this.pos(i);
18858 return this.buffers[pos.buf].set(pos.offset, b);
18861 Buffers.prototype.indexOf = function (needle, offset) {
18862 if ("string" === typeof needle) {
18863 needle = new Buffer(needle);
18864 } else if (needle instanceof Buffer) {
18865 // already a buffer
18867 throw new Error('Invalid type for a search string');
18870 if (!needle.length) {
18874 if (!this.length) {
18878 var i = 0, j = 0, match = 0, mstart, pos = 0;
18880 // start search from a particular point in the virtual buffer
18882 var p = this.pos(offset);
18888 // for each character in virtual buffer
18890 while (j >= this.buffers[i].length) {
18894 if (i >= this.buffers.length) {
18895 // search string not found
18900 var char = this.buffers[i][j];
18902 if (char == needle[match]) {
18903 // keep track where match started
18912 if (match == needle.length) {
18916 } else if (match != 0) {
18917 // a partial match ended, go back to match starting position
18918 // this will continue the search at the next character
18930 Buffers.prototype.toBuffer = function() {
18931 return this.slice();
18934 Buffers.prototype.toString = function(encoding, start, end) {
18935 return this.slice(start, end).toString(encoding);
18941 /***/ (function(module, exports) {
18943 module.exports = function (store) {
18944 function getset (name, value) {
18945 var node = vars.store;
18946 var keys = name.split('.');
18947 keys.slice(0,-1).forEach(function (k) {
18948 if (node[k] === undefined) node[k] = {};
18951 var key = keys[keys.length - 1];
18952 if (arguments.length == 1) {
18956 return node[key] = value;
18961 get : function (name) {
18962 return getset(name);
18964 set : function (name, value) {
18965 return getset(name, value);
18967 store : store || {},
18975 /***/ (function(module, exports, __webpack_require__) {
18980 if (typeof Promise !== "undefined") old = Promise;
18981 function noConflict() {
18982 try { if (Promise === bluebird) Promise = old; }
18986 var bluebird = __webpack_require__(129)();
18987 bluebird.noConflict = noConflict;
18988 module.exports = bluebird;
18993 /***/ (function(module, exports, __webpack_require__) {
18997 module.exports = function() {
18998 var makeSelfResolutionError = function () {
18999 return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
19001 var reflectHandler = function() {
19002 return new Promise.PromiseInspection(this._target());
19004 var apiRejection = function(msg) {
19005 return Promise.reject(new TypeError(msg));
19007 function Proxyable() {}
19008 var UNDEFINED_BINDING = {};
19009 var util = __webpack_require__(130);
19013 getDomain = function() {
19014 var ret = process.domain;
19015 if (ret === undefined) ret = null;
19019 getDomain = function() {
19023 util.notEnumerableProp(Promise, "_getDomain", getDomain);
19025 var es5 = __webpack_require__(131);
19026 var Async = __webpack_require__(132);
19027 var async = new Async();
19028 es5.defineProperty(Promise, "_async", {value: async});
19029 var errors = __webpack_require__(135);
19030 var TypeError = Promise.TypeError = errors.TypeError;
19031 Promise.RangeError = errors.RangeError;
19032 var CancellationError = Promise.CancellationError = errors.CancellationError;
19033 Promise.TimeoutError = errors.TimeoutError;
19034 Promise.OperationalError = errors.OperationalError;
19035 Promise.RejectionError = errors.OperationalError;
19036 Promise.AggregateError = errors.AggregateError;
19037 var INTERNAL = function(){};
19039 var NEXT_FILTER = {};
19040 var tryConvertToPromise = __webpack_require__(136)(Promise, INTERNAL);
19042 __webpack_require__(137)(Promise, INTERNAL,
19043 tryConvertToPromise, apiRejection, Proxyable);
19044 var Context = __webpack_require__(138)(Promise);
19045 /*jshint unused:false*/
19046 var createContext = Context.create;
19047 var debug = __webpack_require__(139)(Promise, Context);
19048 var CapturedTrace = debug.CapturedTrace;
19049 var PassThroughHandlerContext =
19050 __webpack_require__(140)(Promise, tryConvertToPromise);
19051 var catchFilter = __webpack_require__(141)(NEXT_FILTER);
19052 var nodebackForPromise = __webpack_require__(142);
19053 var errorObj = util.errorObj;
19054 var tryCatch = util.tryCatch;
19055 function check(self, executor) {
19056 if (typeof executor !== "function") {
19057 throw new TypeError("expecting a function but got " + util.classString(executor));
19059 if (self.constructor !== Promise) {
19060 throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
19064 function Promise(executor) {
19065 this._bitField = 0;
19066 this._fulfillmentHandler0 = undefined;
19067 this._rejectionHandler0 = undefined;
19068 this._promise0 = undefined;
19069 this._receiver0 = undefined;
19070 if (executor !== INTERNAL) {
19071 check(this, executor);
19072 this._resolveFromExecutor(executor);
19074 this._promiseCreated();
19075 this._fireEvent("promiseCreated", this);
19078 Promise.prototype.toString = function () {
19079 return "[object Promise]";
19082 Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
19083 var len = arguments.length;
19085 var catchInstances = new Array(len - 1),
19087 for (i = 0; i < len - 1; ++i) {
19088 var item = arguments[i];
19089 if (util.isObject(item)) {
19090 catchInstances[j++] = item;
19092 return apiRejection("expecting an object but got " +
19093 "A catch statement predicate " + util.classString(item));
19096 catchInstances.length = j;
19098 return this.then(undefined, catchFilter(catchInstances, fn, this));
19100 return this.then(undefined, fn);
19103 Promise.prototype.reflect = function () {
19104 return this._then(reflectHandler,
19105 reflectHandler, undefined, this, undefined);
19108 Promise.prototype.then = function (didFulfill, didReject) {
19109 if (debug.warnings() && arguments.length > 0 &&
19110 typeof didFulfill !== "function" &&
19111 typeof didReject !== "function") {
19112 var msg = ".then() only accepts functions but was passed: " +
19113 util.classString(didFulfill);
19114 if (arguments.length > 1) {
19115 msg += ", " + util.classString(didReject);
19119 return this._then(didFulfill, didReject, undefined, undefined, undefined);
19122 Promise.prototype.done = function (didFulfill, didReject) {
19124 this._then(didFulfill, didReject, undefined, undefined, undefined);
19125 promise._setIsFinal();
19128 Promise.prototype.spread = function (fn) {
19129 if (typeof fn !== "function") {
19130 return apiRejection("expecting a function but got " + util.classString(fn));
19132 return this.all()._then(fn, undefined, undefined, APPLY, undefined);
19135 Promise.prototype.toJSON = function () {
19137 isFulfilled: false,
19139 fulfillmentValue: undefined,
19140 rejectionReason: undefined
19142 if (this.isFulfilled()) {
19143 ret.fulfillmentValue = this.value();
19144 ret.isFulfilled = true;
19145 } else if (this.isRejected()) {
19146 ret.rejectionReason = this.reason();
19147 ret.isRejected = true;
19152 Promise.prototype.all = function () {
19153 if (arguments.length > 0) {
19154 this._warn(".all() was passed arguments but it does not take any");
19156 return new PromiseArray(this).promise();
19159 Promise.prototype.error = function (fn) {
19160 return this.caught(util.originatesFromRejection, fn);
19163 Promise.getNewLibraryCopy = module.exports;
19165 Promise.is = function (val) {
19166 return val instanceof Promise;
19169 Promise.fromNode = Promise.fromCallback = function(fn) {
19170 var ret = new Promise(INTERNAL);
19171 ret._captureStackTrace();
19172 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
19174 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
19175 if (result === errorObj) {
19176 ret._rejectCallback(result.e, true);
19178 if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
19182 Promise.all = function (promises) {
19183 return new PromiseArray(promises).promise();
19186 Promise.cast = function (obj) {
19187 var ret = tryConvertToPromise(obj);
19188 if (!(ret instanceof Promise)) {
19189 ret = new Promise(INTERNAL);
19190 ret._captureStackTrace();
19191 ret._setFulfilled();
19192 ret._rejectionHandler0 = obj;
19197 Promise.resolve = Promise.fulfilled = Promise.cast;
19199 Promise.reject = Promise.rejected = function (reason) {
19200 var ret = new Promise(INTERNAL);
19201 ret._captureStackTrace();
19202 ret._rejectCallback(reason, true);
19206 Promise.setScheduler = function(fn) {
19207 if (typeof fn !== "function") {
19208 throw new TypeError("expecting a function but got " + util.classString(fn));
19210 return async.setScheduler(fn);
19213 Promise.prototype._then = function (
19219 var haveInternalData = internalData !== undefined;
19220 var promise = haveInternalData ? internalData : new Promise(INTERNAL);
19221 var target = this._target();
19222 var bitField = target._bitField;
19224 if (!haveInternalData) {
19225 promise._propagateFrom(this, 3);
19226 promise._captureStackTrace();
19227 if (receiver === undefined &&
19228 ((this._bitField & 2097152) !== 0)) {
19229 if (!((bitField & 50397184) === 0)) {
19230 receiver = this._boundValue();
19232 receiver = target === this ? undefined : this._boundTo;
19235 this._fireEvent("promiseChained", this, promise);
19238 var domain = getDomain();
19239 if (!((bitField & 50397184) === 0)) {
19240 var handler, value, settler = target._settlePromiseCtx;
19241 if (((bitField & 33554432) !== 0)) {
19242 value = target._rejectionHandler0;
19243 handler = didFulfill;
19244 } else if (((bitField & 16777216) !== 0)) {
19245 value = target._fulfillmentHandler0;
19246 handler = didReject;
19247 target._unsetRejectionIsUnhandled();
19249 settler = target._settlePromiseLateCancellationObserver;
19250 value = new CancellationError("late cancellation observer");
19251 target._attachExtraTrace(value);
19252 handler = didReject;
19255 async.invoke(settler, target, {
19256 handler: domain === null ? handler
19257 : (typeof handler === "function" &&
19258 util.domainBind(domain, handler)),
19260 receiver: receiver,
19264 target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
19270 Promise.prototype._length = function () {
19271 return this._bitField & 65535;
19274 Promise.prototype._isFateSealed = function () {
19275 return (this._bitField & 117506048) !== 0;
19278 Promise.prototype._isFollowing = function () {
19279 return (this._bitField & 67108864) === 67108864;
19282 Promise.prototype._setLength = function (len) {
19283 this._bitField = (this._bitField & -65536) |
19287 Promise.prototype._setFulfilled = function () {
19288 this._bitField = this._bitField | 33554432;
19289 this._fireEvent("promiseFulfilled", this);
19292 Promise.prototype._setRejected = function () {
19293 this._bitField = this._bitField | 16777216;
19294 this._fireEvent("promiseRejected", this);
19297 Promise.prototype._setFollowing = function () {
19298 this._bitField = this._bitField | 67108864;
19299 this._fireEvent("promiseResolved", this);
19302 Promise.prototype._setIsFinal = function () {
19303 this._bitField = this._bitField | 4194304;
19306 Promise.prototype._isFinal = function () {
19307 return (this._bitField & 4194304) > 0;
19310 Promise.prototype._unsetCancelled = function() {
19311 this._bitField = this._bitField & (~65536);
19314 Promise.prototype._setCancelled = function() {
19315 this._bitField = this._bitField | 65536;
19316 this._fireEvent("promiseCancelled", this);
19319 Promise.prototype._setWillBeCancelled = function() {
19320 this._bitField = this._bitField | 8388608;
19323 Promise.prototype._setAsyncGuaranteed = function() {
19324 if (async.hasCustomScheduler()) return;
19325 this._bitField = this._bitField | 134217728;
19328 Promise.prototype._receiverAt = function (index) {
19329 var ret = index === 0 ? this._receiver0 : this[
19330 index * 4 - 4 + 3];
19331 if (ret === UNDEFINED_BINDING) {
19333 } else if (ret === undefined && this._isBound()) {
19334 return this._boundValue();
19339 Promise.prototype._promiseAt = function (index) {
19341 index * 4 - 4 + 2];
19344 Promise.prototype._fulfillmentHandlerAt = function (index) {
19346 index * 4 - 4 + 0];
19349 Promise.prototype._rejectionHandlerAt = function (index) {
19351 index * 4 - 4 + 1];
19354 Promise.prototype._boundValue = function() {};
19356 Promise.prototype._migrateCallback0 = function (follower) {
19357 var bitField = follower._bitField;
19358 var fulfill = follower._fulfillmentHandler0;
19359 var reject = follower._rejectionHandler0;
19360 var promise = follower._promise0;
19361 var receiver = follower._receiverAt(0);
19362 if (receiver === undefined) receiver = UNDEFINED_BINDING;
19363 this._addCallbacks(fulfill, reject, promise, receiver, null);
19366 Promise.prototype._migrateCallbackAt = function (follower, index) {
19367 var fulfill = follower._fulfillmentHandlerAt(index);
19368 var reject = follower._rejectionHandlerAt(index);
19369 var promise = follower._promiseAt(index);
19370 var receiver = follower._receiverAt(index);
19371 if (receiver === undefined) receiver = UNDEFINED_BINDING;
19372 this._addCallbacks(fulfill, reject, promise, receiver, null);
19375 Promise.prototype._addCallbacks = function (
19382 var index = this._length();
19384 if (index >= 65535 - 4) {
19386 this._setLength(0);
19390 this._promise0 = promise;
19391 this._receiver0 = receiver;
19392 if (typeof fulfill === "function") {
19393 this._fulfillmentHandler0 =
19394 domain === null ? fulfill : util.domainBind(domain, fulfill);
19396 if (typeof reject === "function") {
19397 this._rejectionHandler0 =
19398 domain === null ? reject : util.domainBind(domain, reject);
19401 var base = index * 4 - 4;
19402 this[base + 2] = promise;
19403 this[base + 3] = receiver;
19404 if (typeof fulfill === "function") {
19406 domain === null ? fulfill : util.domainBind(domain, fulfill);
19408 if (typeof reject === "function") {
19410 domain === null ? reject : util.domainBind(domain, reject);
19413 this._setLength(index + 1);
19417 Promise.prototype._proxy = function (proxyable, arg) {
19418 this._addCallbacks(undefined, undefined, arg, proxyable, null);
19421 Promise.prototype._resolveCallback = function(value, shouldBind) {
19422 if (((this._bitField & 117506048) !== 0)) return;
19423 if (value === this)
19424 return this._rejectCallback(makeSelfResolutionError(), false);
19425 var maybePromise = tryConvertToPromise(value, this);
19426 if (!(maybePromise instanceof Promise)) return this._fulfill(value);
19428 if (shouldBind) this._propagateFrom(maybePromise, 2);
19430 var promise = maybePromise._target();
19432 if (promise === this) {
19433 this._reject(makeSelfResolutionError());
19437 var bitField = promise._bitField;
19438 if (((bitField & 50397184) === 0)) {
19439 var len = this._length();
19440 if (len > 0) promise._migrateCallback0(this);
19441 for (var i = 1; i < len; ++i) {
19442 promise._migrateCallbackAt(this, i);
19444 this._setFollowing();
19445 this._setLength(0);
19446 this._setFollowee(promise);
19447 } else if (((bitField & 33554432) !== 0)) {
19448 this._fulfill(promise._value());
19449 } else if (((bitField & 16777216) !== 0)) {
19450 this._reject(promise._reason());
19452 var reason = new CancellationError("late cancellation observer");
19453 promise._attachExtraTrace(reason);
19454 this._reject(reason);
19458 Promise.prototype._rejectCallback =
19459 function(reason, synchronous, ignoreNonErrorWarnings) {
19460 var trace = util.ensureErrorObject(reason);
19461 var hasStack = trace === reason;
19462 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
19463 var message = "a promise was rejected with a non-error: " +
19464 util.classString(reason);
19465 this._warn(message, true);
19467 this._attachExtraTrace(trace, synchronous ? hasStack : false);
19468 this._reject(reason);
19471 Promise.prototype._resolveFromExecutor = function (executor) {
19472 var promise = this;
19473 this._captureStackTrace();
19474 this._pushContext();
19475 var synchronous = true;
19476 var r = this._execute(executor, function(value) {
19477 promise._resolveCallback(value);
19478 }, function (reason) {
19479 promise._rejectCallback(reason, synchronous);
19481 synchronous = false;
19482 this._popContext();
19484 if (r !== undefined) {
19485 promise._rejectCallback(r, true);
19489 Promise.prototype._settlePromiseFromHandler = function (
19490 handler, receiver, value, promise
19492 var bitField = promise._bitField;
19493 if (((bitField & 65536) !== 0)) return;
19494 promise._pushContext();
19496 if (receiver === APPLY) {
19497 if (!value || typeof value.length !== "number") {
19499 x.e = new TypeError("cannot .spread() a non-array: " +
19500 util.classString(value));
19502 x = tryCatch(handler).apply(this._boundValue(), value);
19505 x = tryCatch(handler).call(receiver, value);
19507 var promiseCreated = promise._popContext();
19508 bitField = promise._bitField;
19509 if (((bitField & 65536) !== 0)) return;
19511 if (x === NEXT_FILTER) {
19512 promise._reject(value);
19513 } else if (x === errorObj) {
19514 promise._rejectCallback(x.e, false);
19516 debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
19517 promise._resolveCallback(x);
19521 Promise.prototype._target = function() {
19523 while (ret._isFollowing()) ret = ret._followee();
19527 Promise.prototype._followee = function() {
19528 return this._rejectionHandler0;
19531 Promise.prototype._setFollowee = function(promise) {
19532 this._rejectionHandler0 = promise;
19535 Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
19536 var isPromise = promise instanceof Promise;
19537 var bitField = this._bitField;
19538 var asyncGuaranteed = ((bitField & 134217728) !== 0);
19539 if (((bitField & 65536) !== 0)) {
19540 if (isPromise) promise._invokeInternalOnCancel();
19542 if (receiver instanceof PassThroughHandlerContext &&
19543 receiver.isFinallyHandler()) {
19544 receiver.cancelPromise = promise;
19545 if (tryCatch(handler).call(receiver, value) === errorObj) {
19546 promise._reject(errorObj.e);
19548 } else if (handler === reflectHandler) {
19549 promise._fulfill(reflectHandler.call(receiver));
19550 } else if (receiver instanceof Proxyable) {
19551 receiver._promiseCancelled(promise);
19552 } else if (isPromise || promise instanceof PromiseArray) {
19557 } else if (typeof handler === "function") {
19559 handler.call(receiver, value, promise);
19561 if (asyncGuaranteed) promise._setAsyncGuaranteed();
19562 this._settlePromiseFromHandler(handler, receiver, value, promise);
19564 } else if (receiver instanceof Proxyable) {
19565 if (!receiver._isResolved()) {
19566 if (((bitField & 33554432) !== 0)) {
19567 receiver._promiseFulfilled(value, promise);
19569 receiver._promiseRejected(value, promise);
19572 } else if (isPromise) {
19573 if (asyncGuaranteed) promise._setAsyncGuaranteed();
19574 if (((bitField & 33554432) !== 0)) {
19575 promise._fulfill(value);
19577 promise._reject(value);
19582 Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
19583 var handler = ctx.handler;
19584 var promise = ctx.promise;
19585 var receiver = ctx.receiver;
19586 var value = ctx.value;
19587 if (typeof handler === "function") {
19588 if (!(promise instanceof Promise)) {
19589 handler.call(receiver, value, promise);
19591 this._settlePromiseFromHandler(handler, receiver, value, promise);
19593 } else if (promise instanceof Promise) {
19594 promise._reject(value);
19598 Promise.prototype._settlePromiseCtx = function(ctx) {
19599 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
19602 Promise.prototype._settlePromise0 = function(handler, value, bitField) {
19603 var promise = this._promise0;
19604 var receiver = this._receiverAt(0);
19605 this._promise0 = undefined;
19606 this._receiver0 = undefined;
19607 this._settlePromise(promise, handler, receiver, value);
19610 Promise.prototype._clearCallbackDataAtIndex = function(index) {
19611 var base = index * 4 - 4;
19615 this[base + 1] = undefined;
19618 Promise.prototype._fulfill = function (value) {
19619 var bitField = this._bitField;
19620 if (((bitField & 117506048) >>> 16)) return;
19621 if (value === this) {
19622 var err = makeSelfResolutionError();
19623 this._attachExtraTrace(err);
19624 return this._reject(err);
19626 this._setFulfilled();
19627 this._rejectionHandler0 = value;
19629 if ((bitField & 65535) > 0) {
19630 if (((bitField & 134217728) !== 0)) {
19631 this._settlePromises();
19633 async.settlePromises(this);
19638 Promise.prototype._reject = function (reason) {
19639 var bitField = this._bitField;
19640 if (((bitField & 117506048) >>> 16)) return;
19641 this._setRejected();
19642 this._fulfillmentHandler0 = reason;
19644 if (this._isFinal()) {
19645 return async.fatalError(reason, util.isNode);
19648 if ((bitField & 65535) > 0) {
19649 async.settlePromises(this);
19651 this._ensurePossibleRejectionHandled();
19655 Promise.prototype._fulfillPromises = function (len, value) {
19656 for (var i = 1; i < len; i++) {
19657 var handler = this._fulfillmentHandlerAt(i);
19658 var promise = this._promiseAt(i);
19659 var receiver = this._receiverAt(i);
19660 this._clearCallbackDataAtIndex(i);
19661 this._settlePromise(promise, handler, receiver, value);
19665 Promise.prototype._rejectPromises = function (len, reason) {
19666 for (var i = 1; i < len; i++) {
19667 var handler = this._rejectionHandlerAt(i);
19668 var promise = this._promiseAt(i);
19669 var receiver = this._receiverAt(i);
19670 this._clearCallbackDataAtIndex(i);
19671 this._settlePromise(promise, handler, receiver, reason);
19675 Promise.prototype._settlePromises = function () {
19676 var bitField = this._bitField;
19677 var len = (bitField & 65535);
19680 if (((bitField & 16842752) !== 0)) {
19681 var reason = this._fulfillmentHandler0;
19682 this._settlePromise0(this._rejectionHandler0, reason, bitField);
19683 this._rejectPromises(len, reason);
19685 var value = this._rejectionHandler0;
19686 this._settlePromise0(this._fulfillmentHandler0, value, bitField);
19687 this._fulfillPromises(len, value);
19689 this._setLength(0);
19691 this._clearCancellationData();
19694 Promise.prototype._settledValue = function() {
19695 var bitField = this._bitField;
19696 if (((bitField & 33554432) !== 0)) {
19697 return this._rejectionHandler0;
19698 } else if (((bitField & 16777216) !== 0)) {
19699 return this._fulfillmentHandler0;
19703 function deferResolve(v) {this.promise._resolveCallback(v);}
19704 function deferReject(v) {this.promise._rejectCallback(v, false);}
19706 Promise.defer = Promise.pending = function() {
19707 debug.deprecated("Promise.defer", "new Promise");
19708 var promise = new Promise(INTERNAL);
19711 resolve: deferResolve,
19712 reject: deferReject
19716 util.notEnumerableProp(Promise,
19717 "_makeSelfResolutionError",
19718 makeSelfResolutionError);
19720 __webpack_require__(143)(Promise, INTERNAL, tryConvertToPromise, apiRejection,
19722 __webpack_require__(144)(Promise, INTERNAL, tryConvertToPromise, debug);
19723 __webpack_require__(145)(Promise, PromiseArray, apiRejection, debug);
19724 __webpack_require__(146)(Promise);
19725 __webpack_require__(147)(Promise);
19726 __webpack_require__(148)(
19727 Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
19728 Promise.Promise = Promise;
19729 Promise.version = "3.4.7";
19730 __webpack_require__(149)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
19731 __webpack_require__(150)(Promise);
19732 __webpack_require__(151)(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
19733 __webpack_require__(152)(Promise, INTERNAL, debug);
19734 __webpack_require__(153)(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
19735 __webpack_require__(154)(Promise);
19736 __webpack_require__(155)(Promise, INTERNAL);
19737 __webpack_require__(156)(Promise, PromiseArray, tryConvertToPromise, apiRejection);
19738 __webpack_require__(157)(Promise, INTERNAL, tryConvertToPromise, apiRejection);
19739 __webpack_require__(158)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
19740 __webpack_require__(159)(Promise, PromiseArray, debug);
19741 __webpack_require__(160)(Promise, PromiseArray, apiRejection);
19742 __webpack_require__(161)(Promise, INTERNAL);
19743 __webpack_require__(162)(Promise, INTERNAL);
19744 __webpack_require__(163)(Promise);
19746 util.toFastProperties(Promise);
19747 util.toFastProperties(Promise.prototype);
19748 function fillTypes(value) {
19749 var p = new Promise(INTERNAL);
19750 p._fulfillmentHandler0 = value;
19751 p._rejectionHandler0 = value;
19752 p._promise0 = value;
19753 p._receiver0 = value;
19755 // Complete slack tracking, opt out of field-type tracking and
19761 fillTypes(function(){});
19762 fillTypes(undefined);
19764 fillTypes(new Promise(INTERNAL));
19765 debug.setBounds(Async.firstLineError, util.lastLineError);
19773 /***/ (function(module, exports, __webpack_require__) {
19777 var es5 = __webpack_require__(131);
19778 var canEvaluate = typeof navigator == "undefined";
19780 var errorObj = {e: {}};
19781 var tryCatchTarget;
19782 var globalObject = typeof self !== "undefined" ? self :
19783 typeof window !== "undefined" ? window :
19784 typeof global !== "undefined" ? global :
19785 this !== undefined ? this : null;
19787 function tryCatcher() {
19789 var target = tryCatchTarget;
19790 tryCatchTarget = null;
19791 return target.apply(this, arguments);
19797 function tryCatch(fn) {
19798 tryCatchTarget = fn;
19802 var inherits = function(Child, Parent) {
19803 var hasProp = {}.hasOwnProperty;
19806 this.constructor = Child;
19807 this.constructor$ = Parent;
19808 for (var propertyName in Parent.prototype) {
19809 if (hasProp.call(Parent.prototype, propertyName) &&
19810 propertyName.charAt(propertyName.length-1) !== "$"
19812 this[propertyName + "$"] = Parent.prototype[propertyName];
19816 T.prototype = Parent.prototype;
19817 Child.prototype = new T();
19818 return Child.prototype;
19822 function isPrimitive(val) {
19823 return val == null || val === true || val === false ||
19824 typeof val === "string" || typeof val === "number";
19828 function isObject(value) {
19829 return typeof value === "function" ||
19830 typeof value === "object" && value !== null;
19833 function maybeWrapAsError(maybeError) {
19834 if (!isPrimitive(maybeError)) return maybeError;
19836 return new Error(safeToString(maybeError));
19839 function withAppended(target, appendee) {
19840 var len = target.length;
19841 var ret = new Array(len + 1);
19843 for (i = 0; i < len; ++i) {
19844 ret[i] = target[i];
19850 function getDataPropertyOrDefault(obj, key, defaultValue) {
19852 var desc = Object.getOwnPropertyDescriptor(obj, key);
19854 if (desc != null) {
19855 return desc.get == null && desc.set == null
19860 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
19864 function notEnumerableProp(obj, name, value) {
19865 if (isPrimitive(obj)) return obj;
19868 configurable: true,
19872 es5.defineProperty(obj, name, descriptor);
19876 function thrower(r) {
19880 var inheritedDataKeys = (function() {
19881 var excludedPrototypes = [
19887 var isExcludedProto = function(val) {
19888 for (var i = 0; i < excludedPrototypes.length; ++i) {
19889 if (excludedPrototypes[i] === val) {
19897 var getKeys = Object.getOwnPropertyNames;
19898 return function(obj) {
19900 var visitedKeys = Object.create(null);
19901 while (obj != null && !isExcludedProto(obj)) {
19904 keys = getKeys(obj);
19908 for (var i = 0; i < keys.length; ++i) {
19910 if (visitedKeys[key]) continue;
19911 visitedKeys[key] = true;
19912 var desc = Object.getOwnPropertyDescriptor(obj, key);
19913 if (desc != null && desc.get == null && desc.set == null) {
19917 obj = es5.getPrototypeOf(obj);
19922 var hasProp = {}.hasOwnProperty;
19923 return function(obj) {
19924 if (isExcludedProto(obj)) return [];
19927 /*jshint forin:false */
19928 enumeration: for (var key in obj) {
19929 if (hasProp.call(obj, key)) {
19932 for (var i = 0; i < excludedPrototypes.length; ++i) {
19933 if (hasProp.call(excludedPrototypes[i], key)) {
19934 continue enumeration;
19946 var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
19947 function isClass(fn) {
19949 if (typeof fn === "function") {
19950 var keys = es5.names(fn.prototype);
19952 var hasMethods = es5.isES5 && keys.length > 1;
19953 var hasMethodsOtherThanConstructor = keys.length > 0 &&
19954 !(keys.length === 1 && keys[0] === "constructor");
19955 var hasThisAssignmentAndStaticMethods =
19956 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
19958 if (hasMethods || hasMethodsOtherThanConstructor ||
19959 hasThisAssignmentAndStaticMethods) {
19969 function toFastProperties(obj) {
19970 /*jshint -W027,-W055,-W031*/
19971 function FakeConstructor() {}
19972 FakeConstructor.prototype = obj;
19974 while (l--) new FakeConstructor();
19979 var rident = /^[a-z$_][a-z$_0-9]*$/i;
19980 function isIdentifier(str) {
19981 return rident.test(str);
19984 function filledRange(count, prefix, suffix) {
19985 var ret = new Array(count);
19986 for(var i = 0; i < count; ++i) {
19987 ret[i] = prefix + i + suffix;
19992 function safeToString(obj) {
19996 return "[no string representation]";
20000 function isError(obj) {
20001 return obj !== null &&
20002 typeof obj === "object" &&
20003 typeof obj.message === "string" &&
20004 typeof obj.name === "string";
20007 function markAsOriginatingFromRejection(e) {
20009 notEnumerableProp(e, "isOperational", true);
20014 function originatesFromRejection(e) {
20015 if (e == null) return false;
20016 return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
20017 e["isOperational"] === true);
20020 function canAttachTrace(obj) {
20021 return isError(obj) && es5.propertyIsWritable(obj, "stack");
20024 var ensureErrorObject = (function() {
20025 if (!("stack" in new Error())) {
20026 return function(value) {
20027 if (canAttachTrace(value)) return value;
20028 try {throw new Error(safeToString(value));}
20029 catch(err) {return err;}
20032 return function(value) {
20033 if (canAttachTrace(value)) return value;
20034 return new Error(safeToString(value));
20039 function classString(obj) {
20040 return {}.toString.call(obj);
20043 function copyDescriptors(from, to, filter) {
20044 var keys = es5.names(from);
20045 for (var i = 0; i < keys.length; ++i) {
20049 es5.defineProperty(to, key, es5.getDescriptor(from, key));
20050 } catch (ignore) {}
20055 var asArray = function(v) {
20056 if (es5.isArray(v)) {
20062 if (typeof Symbol !== "undefined" && Symbol.iterator) {
20063 var ArrayFrom = typeof Array.from === "function" ? function(v) {
20064 return Array.from(v);
20067 var it = v[Symbol.iterator]();
20069 while (!((itResult = it.next()).done)) {
20070 ret.push(itResult.value);
20075 asArray = function(v) {
20076 if (es5.isArray(v)) {
20078 } else if (v != null && typeof v[Symbol.iterator] === "function") {
20079 return ArrayFrom(v);
20085 var isNode = typeof process !== "undefined" &&
20086 classString(process).toLowerCase() === "[object process]";
20088 var hasEnvVariables = typeof process !== "undefined" &&
20089 typeof process.env !== "undefined";
20091 function env(key) {
20092 return hasEnvVariables ? process.env[key] : undefined;
20095 function getNativePromise() {
20096 if (typeof Promise === "function") {
20098 var promise = new Promise(function(){});
20099 if ({}.toString.call(promise) === "[object Promise]") {
20106 function domainBind(self, cb) {
20107 return self.bind(cb);
20112 isIdentifier: isIdentifier,
20113 inheritedDataKeys: inheritedDataKeys,
20114 getDataPropertyOrDefault: getDataPropertyOrDefault,
20116 isArray: es5.isArray,
20118 notEnumerableProp: notEnumerableProp,
20119 isPrimitive: isPrimitive,
20120 isObject: isObject,
20122 canEvaluate: canEvaluate,
20123 errorObj: errorObj,
20124 tryCatch: tryCatch,
20125 inherits: inherits,
20126 withAppended: withAppended,
20127 maybeWrapAsError: maybeWrapAsError,
20128 toFastProperties: toFastProperties,
20129 filledRange: filledRange,
20130 toString: safeToString,
20131 canAttachTrace: canAttachTrace,
20132 ensureErrorObject: ensureErrorObject,
20133 originatesFromRejection: originatesFromRejection,
20134 markAsOriginatingFromRejection: markAsOriginatingFromRejection,
20135 classString: classString,
20136 copyDescriptors: copyDescriptors,
20137 hasDevTools: typeof chrome !== "undefined" && chrome &&
20138 typeof chrome.loadTimes === "function",
20140 hasEnvVariables: hasEnvVariables,
20142 global: globalObject,
20143 getNativePromise: getNativePromise,
20144 domainBind: domainBind
20146 ret.isRecentNode = ret.isNode && (function() {
20147 var version = process.versions.node.split(".").map(Number);
20148 return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
20151 if (ret.isNode) ret.toFastProperties(process);
20153 try {throw new Error(); } catch (e) {ret.lastLineError = e;}
20154 module.exports = ret;
20159 /***/ (function(module, exports) {
20161 var isES5 = (function(){
20163 return this === undefined;
20168 freeze: Object.freeze,
20169 defineProperty: Object.defineProperty,
20170 getDescriptor: Object.getOwnPropertyDescriptor,
20172 names: Object.getOwnPropertyNames,
20173 getPrototypeOf: Object.getPrototypeOf,
20174 isArray: Array.isArray,
20176 propertyIsWritable: function(obj, prop) {
20177 var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
20178 return !!(!descriptor || descriptor.writable || descriptor.set);
20182 var has = {}.hasOwnProperty;
20183 var str = {}.toString;
20184 var proto = {}.constructor.prototype;
20186 var ObjectKeys = function (o) {
20188 for (var key in o) {
20189 if (has.call(o, key)) {
20196 var ObjectGetDescriptor = function(o, key) {
20197 return {value: o[key]};
20200 var ObjectDefineProperty = function (o, key, desc) {
20201 o[key] = desc.value;
20205 var ObjectFreeze = function (obj) {
20209 var ObjectGetPrototypeOf = function (obj) {
20211 return Object(obj).constructor.prototype;
20218 var ArrayIsArray = function (obj) {
20220 return str.call(obj) === "[object Array]";
20228 isArray: ArrayIsArray,
20231 defineProperty: ObjectDefineProperty,
20232 getDescriptor: ObjectGetDescriptor,
20233 freeze: ObjectFreeze,
20234 getPrototypeOf: ObjectGetPrototypeOf,
20236 propertyIsWritable: function() {
20245 /***/ (function(module, exports, __webpack_require__) {
20249 var firstLineError;
20250 try {throw new Error(); } catch (e) {firstLineError = e;}
20251 var schedule = __webpack_require__(133);
20252 var Queue = __webpack_require__(134);
20253 var util = __webpack_require__(130);
20256 this._customScheduler = false;
20257 this._isTickUsed = false;
20258 this._lateQueue = new Queue(16);
20259 this._normalQueue = new Queue(16);
20260 this._haveDrainedQueues = false;
20261 this._trampolineEnabled = true;
20263 this.drainQueues = function () {
20264 self._drainQueues();
20266 this._schedule = schedule;
20269 Async.prototype.setScheduler = function(fn) {
20270 var prev = this._schedule;
20271 this._schedule = fn;
20272 this._customScheduler = true;
20276 Async.prototype.hasCustomScheduler = function() {
20277 return this._customScheduler;
20280 Async.prototype.enableTrampoline = function() {
20281 this._trampolineEnabled = true;
20284 Async.prototype.disableTrampolineIfNecessary = function() {
20285 if (util.hasDevTools) {
20286 this._trampolineEnabled = false;
20290 Async.prototype.haveItemsQueued = function () {
20291 return this._isTickUsed || this._haveDrainedQueues;
20295 Async.prototype.fatalError = function(e, isNode) {
20297 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
20301 this.throwLater(e);
20305 Async.prototype.throwLater = function(fn, arg) {
20306 if (arguments.length === 1) {
20308 fn = function () { throw arg; };
20310 if (typeof setTimeout !== "undefined") {
20311 setTimeout(function() {
20315 this._schedule(function() {
20319 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
20323 function AsyncInvokeLater(fn, receiver, arg) {
20324 this._lateQueue.push(fn, receiver, arg);
20328 function AsyncInvoke(fn, receiver, arg) {
20329 this._normalQueue.push(fn, receiver, arg);
20333 function AsyncSettlePromises(promise) {
20334 this._normalQueue._pushOne(promise);
20338 if (!util.hasDevTools) {
20339 Async.prototype.invokeLater = AsyncInvokeLater;
20340 Async.prototype.invoke = AsyncInvoke;
20341 Async.prototype.settlePromises = AsyncSettlePromises;
20343 Async.prototype.invokeLater = function (fn, receiver, arg) {
20344 if (this._trampolineEnabled) {
20345 AsyncInvokeLater.call(this, fn, receiver, arg);
20347 this._schedule(function() {
20348 setTimeout(function() {
20349 fn.call(receiver, arg);
20355 Async.prototype.invoke = function (fn, receiver, arg) {
20356 if (this._trampolineEnabled) {
20357 AsyncInvoke.call(this, fn, receiver, arg);
20359 this._schedule(function() {
20360 fn.call(receiver, arg);
20365 Async.prototype.settlePromises = function(promise) {
20366 if (this._trampolineEnabled) {
20367 AsyncSettlePromises.call(this, promise);
20369 this._schedule(function() {
20370 promise._settlePromises();
20376 Async.prototype._drainQueue = function(queue) {
20377 while (queue.length() > 0) {
20378 var fn = queue.shift();
20379 if (typeof fn !== "function") {
20380 fn._settlePromises();
20383 var receiver = queue.shift();
20384 var arg = queue.shift();
20385 fn.call(receiver, arg);
20389 Async.prototype._drainQueues = function () {
20390 this._drainQueue(this._normalQueue);
20392 this._haveDrainedQueues = true;
20393 this._drainQueue(this._lateQueue);
20396 Async.prototype._queueTick = function () {
20397 if (!this._isTickUsed) {
20398 this._isTickUsed = true;
20399 this._schedule(this.drainQueues);
20403 Async.prototype._reset = function () {
20404 this._isTickUsed = false;
20407 module.exports = Async;
20408 module.exports.firstLineError = firstLineError;
20413 /***/ (function(module, exports, __webpack_require__) {
20417 var util = __webpack_require__(130);
20419 var noAsyncScheduler = function() {
20420 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
20422 var NativePromise = util.getNativePromise();
20423 if (util.isNode && typeof MutationObserver === "undefined") {
20424 var GlobalSetImmediate = global.setImmediate;
20425 var ProcessNextTick = process.nextTick;
20426 schedule = util.isRecentNode
20427 ? function(fn) { GlobalSetImmediate.call(global, fn); }
20428 : function(fn) { ProcessNextTick.call(process, fn); };
20429 } else if (typeof NativePromise === "function" &&
20430 typeof NativePromise.resolve === "function") {
20431 var nativePromise = NativePromise.resolve();
20432 schedule = function(fn) {
20433 nativePromise.then(fn);
20435 } else if ((typeof MutationObserver !== "undefined") &&
20436 !(typeof window !== "undefined" &&
20437 window.navigator &&
20438 (window.navigator.standalone || window.cordova))) {
20439 schedule = (function() {
20440 var div = document.createElement("div");
20441 var opts = {attributes: true};
20442 var toggleScheduled = false;
20443 var div2 = document.createElement("div");
20444 var o2 = new MutationObserver(function() {
20445 div.classList.toggle("foo");
20446 toggleScheduled = false;
20448 o2.observe(div2, opts);
20450 var scheduleToggle = function() {
20451 if (toggleScheduled) return;
20452 toggleScheduled = true;
20453 div2.classList.toggle("foo");
20456 return function schedule(fn) {
20457 var o = new MutationObserver(function() {
20461 o.observe(div, opts);
20465 } else if (typeof setImmediate !== "undefined") {
20466 schedule = function (fn) {
20469 } else if (typeof setTimeout !== "undefined") {
20470 schedule = function (fn) {
20474 schedule = noAsyncScheduler;
20476 module.exports = schedule;
20481 /***/ (function(module, exports, __webpack_require__) {
20485 function arrayMove(src, srcIndex, dst, dstIndex, len) {
20486 for (var j = 0; j < len; ++j) {
20487 dst[j + dstIndex] = src[j + srcIndex];
20488 src[j + srcIndex] = void 0;
20492 function Queue(capacity) {
20493 this._capacity = capacity;
20498 Queue.prototype._willBeOverCapacity = function (size) {
20499 return this._capacity < size;
20502 Queue.prototype._pushOne = function (arg) {
20503 var length = this.length();
20504 this._checkCapacity(length + 1);
20505 var i = (this._front + length) & (this._capacity - 1);
20507 this._length = length + 1;
20510 Queue.prototype.push = function (fn, receiver, arg) {
20511 var length = this.length() + 3;
20512 if (this._willBeOverCapacity(length)) {
20514 this._pushOne(receiver);
20515 this._pushOne(arg);
20518 var j = this._front + length - 3;
20519 this._checkCapacity(length);
20520 var wrapMask = this._capacity - 1;
20521 this[(j + 0) & wrapMask] = fn;
20522 this[(j + 1) & wrapMask] = receiver;
20523 this[(j + 2) & wrapMask] = arg;
20524 this._length = length;
20527 Queue.prototype.shift = function () {
20528 var front = this._front,
20531 this[front] = undefined;
20532 this._front = (front + 1) & (this._capacity - 1);
20537 Queue.prototype.length = function () {
20538 return this._length;
20541 Queue.prototype._checkCapacity = function (size) {
20542 if (this._capacity < size) {
20543 this._resizeTo(this._capacity << 1);
20547 Queue.prototype._resizeTo = function (capacity) {
20548 var oldCapacity = this._capacity;
20549 this._capacity = capacity;
20550 var front = this._front;
20551 var length = this._length;
20552 var moveItemsCount = (front + length) & (oldCapacity - 1);
20553 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
20556 module.exports = Queue;
20561 /***/ (function(module, exports, __webpack_require__) {
20565 var es5 = __webpack_require__(131);
20566 var Objectfreeze = es5.freeze;
20567 var util = __webpack_require__(130);
20568 var inherits = util.inherits;
20569 var notEnumerableProp = util.notEnumerableProp;
20571 function subError(nameProperty, defaultMessage) {
20572 function SubError(message) {
20573 if (!(this instanceof SubError)) return new SubError(message);
20574 notEnumerableProp(this, "message",
20575 typeof message === "string" ? message : defaultMessage);
20576 notEnumerableProp(this, "name", nameProperty);
20577 if (Error.captureStackTrace) {
20578 Error.captureStackTrace(this, this.constructor);
20583 inherits(SubError, Error);
20587 var _TypeError, _RangeError;
20588 var Warning = subError("Warning", "warning");
20589 var CancellationError = subError("CancellationError", "cancellation error");
20590 var TimeoutError = subError("TimeoutError", "timeout error");
20591 var AggregateError = subError("AggregateError", "aggregate error");
20593 _TypeError = TypeError;
20594 _RangeError = RangeError;
20596 _TypeError = subError("TypeError", "type error");
20597 _RangeError = subError("RangeError", "range error");
20600 var methods = ("join pop push shift unshift slice filter forEach some " +
20601 "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
20603 for (var i = 0; i < methods.length; ++i) {
20604 if (typeof Array.prototype[methods[i]] === "function") {
20605 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
20609 es5.defineProperty(AggregateError.prototype, "length", {
20611 configurable: false,
20615 AggregateError.prototype["isOperational"] = true;
20617 AggregateError.prototype.toString = function() {
20618 var indent = Array(level * 4 + 1).join(" ");
20619 var ret = "\n" + indent + "AggregateError of:" + "\n";
20621 indent = Array(level * 4 + 1).join(" ");
20622 for (var i = 0; i < this.length; ++i) {
20623 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
20624 var lines = str.split("\n");
20625 for (var j = 0; j < lines.length; ++j) {
20626 lines[j] = indent + lines[j];
20628 str = lines.join("\n");
20635 function OperationalError(message) {
20636 if (!(this instanceof OperationalError))
20637 return new OperationalError(message);
20638 notEnumerableProp(this, "name", "OperationalError");
20639 notEnumerableProp(this, "message", message);
20640 this.cause = message;
20641 this["isOperational"] = true;
20643 if (message instanceof Error) {
20644 notEnumerableProp(this, "message", message.message);
20645 notEnumerableProp(this, "stack", message.stack);
20646 } else if (Error.captureStackTrace) {
20647 Error.captureStackTrace(this, this.constructor);
20651 inherits(OperationalError, Error);
20653 var errorTypes = Error["__BluebirdErrorTypes__"];
20655 errorTypes = Objectfreeze({
20656 CancellationError: CancellationError,
20657 TimeoutError: TimeoutError,
20658 OperationalError: OperationalError,
20659 RejectionError: OperationalError,
20660 AggregateError: AggregateError
20662 es5.defineProperty(Error, "__BluebirdErrorTypes__", {
20666 configurable: false
20672 TypeError: _TypeError,
20673 RangeError: _RangeError,
20674 CancellationError: errorTypes.CancellationError,
20675 OperationalError: errorTypes.OperationalError,
20676 TimeoutError: errorTypes.TimeoutError,
20677 AggregateError: errorTypes.AggregateError,
20684 /***/ (function(module, exports, __webpack_require__) {
20688 module.exports = function(Promise, INTERNAL) {
20689 var util = __webpack_require__(130);
20690 var errorObj = util.errorObj;
20691 var isObject = util.isObject;
20693 function tryConvertToPromise(obj, context) {
20694 if (isObject(obj)) {
20695 if (obj instanceof Promise) return obj;
20696 var then = getThen(obj);
20697 if (then === errorObj) {
20698 if (context) context._pushContext();
20699 var ret = Promise.reject(then.e);
20700 if (context) context._popContext();
20702 } else if (typeof then === "function") {
20703 if (isAnyBluebirdPromise(obj)) {
20704 var ret = new Promise(INTERNAL);
20714 return doThenable(obj, then, context);
20720 function doGetThen(obj) {
20724 function getThen(obj) {
20726 return doGetThen(obj);
20733 var hasProp = {}.hasOwnProperty;
20734 function isAnyBluebirdPromise(obj) {
20736 return hasProp.call(obj, "_promise0");
20742 function doThenable(x, then, context) {
20743 var promise = new Promise(INTERNAL);
20745 if (context) context._pushContext();
20746 promise._captureStackTrace();
20747 if (context) context._popContext();
20748 var synchronous = true;
20749 var result = util.tryCatch(then).call(x, resolve, reject);
20750 synchronous = false;
20752 if (promise && result === errorObj) {
20753 promise._rejectCallback(result.e, true, true);
20757 function resolve(value) {
20758 if (!promise) return;
20759 promise._resolveCallback(value);
20763 function reject(reason) {
20764 if (!promise) return;
20765 promise._rejectCallback(reason, synchronous, true);
20771 return tryConvertToPromise;
20777 /***/ (function(module, exports, __webpack_require__) {
20781 module.exports = function(Promise, INTERNAL, tryConvertToPromise,
20782 apiRejection, Proxyable) {
20783 var util = __webpack_require__(130);
20784 var isArray = util.isArray;
20786 function toResolutionValue(val) {
20788 case -2: return [];
20789 case -3: return {};
20793 function PromiseArray(values) {
20794 var promise = this._promise = new Promise(INTERNAL);
20795 if (values instanceof Promise) {
20796 promise._propagateFrom(values, 3);
20798 promise._setOnCancel(this);
20799 this._values = values;
20801 this._totalResolved = 0;
20802 this._init(undefined, -2);
20804 util.inherits(PromiseArray, Proxyable);
20806 PromiseArray.prototype.length = function () {
20807 return this._length;
20810 PromiseArray.prototype.promise = function () {
20811 return this._promise;
20814 PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
20815 var values = tryConvertToPromise(this._values, this._promise);
20816 if (values instanceof Promise) {
20817 values = values._target();
20818 var bitField = values._bitField;
20820 this._values = values;
20822 if (((bitField & 50397184) === 0)) {
20823 this._promise._setAsyncGuaranteed();
20824 return values._then(
20829 resolveValueIfEmpty
20831 } else if (((bitField & 33554432) !== 0)) {
20832 values = values._value();
20833 } else if (((bitField & 16777216) !== 0)) {
20834 return this._reject(values._reason());
20836 return this._cancel();
20839 values = util.asArray(values);
20840 if (values === null) {
20841 var err = apiRejection(
20842 "expecting an array or an iterable object but got " + util.classString(values)).reason();
20843 this._promise._rejectCallback(err, false);
20847 if (values.length === 0) {
20848 if (resolveValueIfEmpty === -5) {
20849 this._resolveEmptyArray();
20852 this._resolve(toResolutionValue(resolveValueIfEmpty));
20856 this._iterate(values);
20859 PromiseArray.prototype._iterate = function(values) {
20860 var len = this.getActualLength(values.length);
20861 this._length = len;
20862 this._values = this.shouldCopyValues() ? new Array(len) : this._values;
20863 var result = this._promise;
20864 var isResolved = false;
20865 var bitField = null;
20866 for (var i = 0; i < len; ++i) {
20867 var maybePromise = tryConvertToPromise(values[i], result);
20869 if (maybePromise instanceof Promise) {
20870 maybePromise = maybePromise._target();
20871 bitField = maybePromise._bitField;
20877 if (bitField !== null) {
20878 maybePromise.suppressUnhandledRejections();
20880 } else if (bitField !== null) {
20881 if (((bitField & 50397184) === 0)) {
20882 maybePromise._proxy(this, i);
20883 this._values[i] = maybePromise;
20884 } else if (((bitField & 33554432) !== 0)) {
20885 isResolved = this._promiseFulfilled(maybePromise._value(), i);
20886 } else if (((bitField & 16777216) !== 0)) {
20887 isResolved = this._promiseRejected(maybePromise._reason(), i);
20889 isResolved = this._promiseCancelled(i);
20892 isResolved = this._promiseFulfilled(maybePromise, i);
20895 if (!isResolved) result._setAsyncGuaranteed();
20898 PromiseArray.prototype._isResolved = function () {
20899 return this._values === null;
20902 PromiseArray.prototype._resolve = function (value) {
20903 this._values = null;
20904 this._promise._fulfill(value);
20907 PromiseArray.prototype._cancel = function() {
20908 if (this._isResolved() || !this._promise._isCancellable()) return;
20909 this._values = null;
20910 this._promise._cancel();
20913 PromiseArray.prototype._reject = function (reason) {
20914 this._values = null;
20915 this._promise._rejectCallback(reason, false);
20918 PromiseArray.prototype._promiseFulfilled = function (value, index) {
20919 this._values[index] = value;
20920 var totalResolved = ++this._totalResolved;
20921 if (totalResolved >= this._length) {
20922 this._resolve(this._values);
20928 PromiseArray.prototype._promiseCancelled = function() {
20933 PromiseArray.prototype._promiseRejected = function (reason) {
20934 this._totalResolved++;
20935 this._reject(reason);
20939 PromiseArray.prototype._resultCancelled = function() {
20940 if (this._isResolved()) return;
20941 var values = this._values;
20943 if (values instanceof Promise) {
20946 for (var i = 0; i < values.length; ++i) {
20947 if (values[i] instanceof Promise) {
20948 values[i].cancel();
20954 PromiseArray.prototype.shouldCopyValues = function () {
20958 PromiseArray.prototype.getActualLength = function (len) {
20962 return PromiseArray;
20968 /***/ (function(module, exports, __webpack_require__) {
20972 module.exports = function(Promise) {
20973 var longStackTraces = false;
20974 var contextStack = [];
20976 Promise.prototype._promiseCreated = function() {};
20977 Promise.prototype._pushContext = function() {};
20978 Promise.prototype._popContext = function() {return null;};
20979 Promise._peekContext = Promise.prototype._peekContext = function() {};
20981 function Context() {
20982 this._trace = new Context.CapturedTrace(peekContext());
20984 Context.prototype._pushContext = function () {
20985 if (this._trace !== undefined) {
20986 this._trace._promiseCreated = null;
20987 contextStack.push(this._trace);
20991 Context.prototype._popContext = function () {
20992 if (this._trace !== undefined) {
20993 var trace = contextStack.pop();
20994 var ret = trace._promiseCreated;
20995 trace._promiseCreated = null;
21001 function createContext() {
21002 if (longStackTraces) return new Context();
21005 function peekContext() {
21006 var lastIndex = contextStack.length - 1;
21007 if (lastIndex >= 0) {
21008 return contextStack[lastIndex];
21012 Context.CapturedTrace = null;
21013 Context.create = createContext;
21014 Context.deactivateLongStackTraces = function() {};
21015 Context.activateLongStackTraces = function() {
21016 var Promise_pushContext = Promise.prototype._pushContext;
21017 var Promise_popContext = Promise.prototype._popContext;
21018 var Promise_PeekContext = Promise._peekContext;
21019 var Promise_peekContext = Promise.prototype._peekContext;
21020 var Promise_promiseCreated = Promise.prototype._promiseCreated;
21021 Context.deactivateLongStackTraces = function() {
21022 Promise.prototype._pushContext = Promise_pushContext;
21023 Promise.prototype._popContext = Promise_popContext;
21024 Promise._peekContext = Promise_PeekContext;
21025 Promise.prototype._peekContext = Promise_peekContext;
21026 Promise.prototype._promiseCreated = Promise_promiseCreated;
21027 longStackTraces = false;
21029 longStackTraces = true;
21030 Promise.prototype._pushContext = Context.prototype._pushContext;
21031 Promise.prototype._popContext = Context.prototype._popContext;
21032 Promise._peekContext = Promise.prototype._peekContext = peekContext;
21033 Promise.prototype._promiseCreated = function() {
21034 var ctx = this._peekContext();
21035 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
21044 /***/ (function(module, exports, __webpack_require__) {
21048 module.exports = function(Promise, Context) {
21049 var getDomain = Promise._getDomain;
21050 var async = Promise._async;
21051 var Warning = __webpack_require__(135).Warning;
21052 var util = __webpack_require__(130);
21053 var canAttachTrace = util.canAttachTrace;
21054 var unhandledRejectionHandled;
21055 var possiblyUnhandledRejection;
21056 var bluebirdFramePattern =
21057 /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
21058 var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
21059 var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
21060 var stackFramePattern = null;
21061 var formatStack = null;
21062 var indentStackFrames = false;
21064 var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
21066 util.env("BLUEBIRD_DEBUG") ||
21067 util.env("NODE_ENV") === "development"));
21069 var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
21070 (debugging || util.env("BLUEBIRD_WARNINGS")));
21072 var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
21073 (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
21075 var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
21076 (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
21078 Promise.prototype.suppressUnhandledRejections = function() {
21079 var target = this._target();
21080 target._bitField = ((target._bitField & (~1048576)) |
21084 Promise.prototype._ensurePossibleRejectionHandled = function () {
21085 if ((this._bitField & 524288) !== 0) return;
21086 this._setRejectionIsUnhandled();
21087 async.invokeLater(this._notifyUnhandledRejection, this, undefined);
21090 Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
21091 fireRejectionEvent("rejectionHandled",
21092 unhandledRejectionHandled, undefined, this);
21095 Promise.prototype._setReturnedNonUndefined = function() {
21096 this._bitField = this._bitField | 268435456;
21099 Promise.prototype._returnedNonUndefined = function() {
21100 return (this._bitField & 268435456) !== 0;
21103 Promise.prototype._notifyUnhandledRejection = function () {
21104 if (this._isRejectionUnhandled()) {
21105 var reason = this._settledValue();
21106 this._setUnhandledRejectionIsNotified();
21107 fireRejectionEvent("unhandledRejection",
21108 possiblyUnhandledRejection, reason, this);
21112 Promise.prototype._setUnhandledRejectionIsNotified = function () {
21113 this._bitField = this._bitField | 262144;
21116 Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
21117 this._bitField = this._bitField & (~262144);
21120 Promise.prototype._isUnhandledRejectionNotified = function () {
21121 return (this._bitField & 262144) > 0;
21124 Promise.prototype._setRejectionIsUnhandled = function () {
21125 this._bitField = this._bitField | 1048576;
21128 Promise.prototype._unsetRejectionIsUnhandled = function () {
21129 this._bitField = this._bitField & (~1048576);
21130 if (this._isUnhandledRejectionNotified()) {
21131 this._unsetUnhandledRejectionIsNotified();
21132 this._notifyUnhandledRejectionIsHandled();
21136 Promise.prototype._isRejectionUnhandled = function () {
21137 return (this._bitField & 1048576) > 0;
21140 Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
21141 return warn(message, shouldUseOwnTrace, promise || this);
21144 Promise.onPossiblyUnhandledRejection = function (fn) {
21145 var domain = getDomain();
21146 possiblyUnhandledRejection =
21147 typeof fn === "function" ? (domain === null ?
21148 fn : util.domainBind(domain, fn))
21152 Promise.onUnhandledRejectionHandled = function (fn) {
21153 var domain = getDomain();
21154 unhandledRejectionHandled =
21155 typeof fn === "function" ? (domain === null ?
21156 fn : util.domainBind(domain, fn))
21160 var disableLongStackTraces = function() {};
21161 Promise.longStackTraces = function () {
21162 if (async.haveItemsQueued() && !config.longStackTraces) {
21163 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
21165 if (!config.longStackTraces && longStackTracesIsSupported()) {
21166 var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
21167 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
21168 config.longStackTraces = true;
21169 disableLongStackTraces = function() {
21170 if (async.haveItemsQueued() && !config.longStackTraces) {
21171 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
21173 Promise.prototype._captureStackTrace = Promise_captureStackTrace;
21174 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
21175 Context.deactivateLongStackTraces();
21176 async.enableTrampoline();
21177 config.longStackTraces = false;
21179 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
21180 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
21181 Context.activateLongStackTraces();
21182 async.disableTrampolineIfNecessary();
21186 Promise.hasLongStackTraces = function () {
21187 return config.longStackTraces && longStackTracesIsSupported();
21190 var fireDomEvent = (function() {
21192 if (typeof CustomEvent === "function") {
21193 var event = new CustomEvent("CustomEvent");
21194 util.global.dispatchEvent(event);
21195 return function(name, event) {
21196 var domEvent = new CustomEvent(name.toLowerCase(), {
21200 return !util.global.dispatchEvent(domEvent);
21202 } else if (typeof Event === "function") {
21203 var event = new Event("CustomEvent");
21204 util.global.dispatchEvent(event);
21205 return function(name, event) {
21206 var domEvent = new Event(name.toLowerCase(), {
21209 domEvent.detail = event;
21210 return !util.global.dispatchEvent(domEvent);
21213 var event = document.createEvent("CustomEvent");
21214 event.initCustomEvent("testingtheevent", false, true, {});
21215 util.global.dispatchEvent(event);
21216 return function(name, event) {
21217 var domEvent = document.createEvent("CustomEvent");
21218 domEvent.initCustomEvent(name.toLowerCase(), false, true,
21220 return !util.global.dispatchEvent(domEvent);
21224 return function() {
21229 var fireGlobalEvent = (function() {
21231 return function() {
21232 return process.emit.apply(process, arguments);
21235 if (!util.global) {
21236 return function() {
21240 return function(name) {
21241 var methodName = "on" + name.toLowerCase();
21242 var method = util.global[methodName];
21243 if (!method) return false;
21244 method.apply(util.global, [].slice.call(arguments, 1));
21250 function generatePromiseLifecycleEventObject(name, promise) {
21251 return {promise: promise};
21254 var eventToObjectGenerator = {
21255 promiseCreated: generatePromiseLifecycleEventObject,
21256 promiseFulfilled: generatePromiseLifecycleEventObject,
21257 promiseRejected: generatePromiseLifecycleEventObject,
21258 promiseResolved: generatePromiseLifecycleEventObject,
21259 promiseCancelled: generatePromiseLifecycleEventObject,
21260 promiseChained: function(name, promise, child) {
21261 return {promise: promise, child: child};
21263 warning: function(name, warning) {
21264 return {warning: warning};
21266 unhandledRejection: function (name, reason, promise) {
21267 return {reason: reason, promise: promise};
21269 rejectionHandled: generatePromiseLifecycleEventObject
21272 var activeFireEvent = function (name) {
21273 var globalEventFired = false;
21275 globalEventFired = fireGlobalEvent.apply(null, arguments);
21277 async.throwLater(e);
21278 globalEventFired = true;
21281 var domEventFired = false;
21283 domEventFired = fireDomEvent(name,
21284 eventToObjectGenerator[name].apply(null, arguments));
21286 async.throwLater(e);
21287 domEventFired = true;
21290 return domEventFired || globalEventFired;
21293 Promise.config = function(opts) {
21294 opts = Object(opts);
21295 if ("longStackTraces" in opts) {
21296 if (opts.longStackTraces) {
21297 Promise.longStackTraces();
21298 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
21299 disableLongStackTraces();
21302 if ("warnings" in opts) {
21303 var warningsOption = opts.warnings;
21304 config.warnings = !!warningsOption;
21305 wForgottenReturn = config.warnings;
21307 if (util.isObject(warningsOption)) {
21308 if ("wForgottenReturn" in warningsOption) {
21309 wForgottenReturn = !!warningsOption.wForgottenReturn;
21313 if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
21314 if (async.haveItemsQueued()) {
21316 "cannot enable cancellation after promises are in use");
21318 Promise.prototype._clearCancellationData =
21319 cancellationClearCancellationData;
21320 Promise.prototype._propagateFrom = cancellationPropagateFrom;
21321 Promise.prototype._onCancel = cancellationOnCancel;
21322 Promise.prototype._setOnCancel = cancellationSetOnCancel;
21323 Promise.prototype._attachCancellationCallback =
21324 cancellationAttachCancellationCallback;
21325 Promise.prototype._execute = cancellationExecute;
21326 propagateFromFunction = cancellationPropagateFrom;
21327 config.cancellation = true;
21329 if ("monitoring" in opts) {
21330 if (opts.monitoring && !config.monitoring) {
21331 config.monitoring = true;
21332 Promise.prototype._fireEvent = activeFireEvent;
21333 } else if (!opts.monitoring && config.monitoring) {
21334 config.monitoring = false;
21335 Promise.prototype._fireEvent = defaultFireEvent;
21341 function defaultFireEvent() { return false; }
21343 Promise.prototype._fireEvent = defaultFireEvent;
21344 Promise.prototype._execute = function(executor, resolve, reject) {
21346 executor(resolve, reject);
21351 Promise.prototype._onCancel = function () {};
21352 Promise.prototype._setOnCancel = function (handler) { ; };
21353 Promise.prototype._attachCancellationCallback = function(onCancel) {
21356 Promise.prototype._captureStackTrace = function () {};
21357 Promise.prototype._attachExtraTrace = function () {};
21358 Promise.prototype._clearCancellationData = function() {};
21359 Promise.prototype._propagateFrom = function (parent, flags) {
21364 function cancellationExecute(executor, resolve, reject) {
21365 var promise = this;
21367 executor(resolve, reject, function(onCancel) {
21368 if (typeof onCancel !== "function") {
21369 throw new TypeError("onCancel must be a function, got: " +
21370 util.toString(onCancel));
21372 promise._attachCancellationCallback(onCancel);
21379 function cancellationAttachCancellationCallback(onCancel) {
21380 if (!this._isCancellable()) return this;
21382 var previousOnCancel = this._onCancel();
21383 if (previousOnCancel !== undefined) {
21384 if (util.isArray(previousOnCancel)) {
21385 previousOnCancel.push(onCancel);
21387 this._setOnCancel([previousOnCancel, onCancel]);
21390 this._setOnCancel(onCancel);
21394 function cancellationOnCancel() {
21395 return this._onCancelField;
21398 function cancellationSetOnCancel(onCancel) {
21399 this._onCancelField = onCancel;
21402 function cancellationClearCancellationData() {
21403 this._cancellationParent = undefined;
21404 this._onCancelField = undefined;
21407 function cancellationPropagateFrom(parent, flags) {
21408 if ((flags & 1) !== 0) {
21409 this._cancellationParent = parent;
21410 var branchesRemainingToCancel = parent._branchesRemainingToCancel;
21411 if (branchesRemainingToCancel === undefined) {
21412 branchesRemainingToCancel = 0;
21414 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
21416 if ((flags & 2) !== 0 && parent._isBound()) {
21417 this._setBoundTo(parent._boundTo);
21421 function bindingPropagateFrom(parent, flags) {
21422 if ((flags & 2) !== 0 && parent._isBound()) {
21423 this._setBoundTo(parent._boundTo);
21426 var propagateFromFunction = bindingPropagateFrom;
21428 function boundValueFunction() {
21429 var ret = this._boundTo;
21430 if (ret !== undefined) {
21431 if (ret instanceof Promise) {
21432 if (ret.isFulfilled()) {
21433 return ret.value();
21442 function longStackTracesCaptureStackTrace() {
21443 this._trace = new CapturedTrace(this._peekContext());
21446 function longStackTracesAttachExtraTrace(error, ignoreSelf) {
21447 if (canAttachTrace(error)) {
21448 var trace = this._trace;
21449 if (trace !== undefined) {
21450 if (ignoreSelf) trace = trace._parent;
21452 if (trace !== undefined) {
21453 trace.attachExtraTrace(error);
21454 } else if (!error.__stackCleaned__) {
21455 var parsed = parseStackAndMessage(error);
21456 util.notEnumerableProp(error, "stack",
21457 parsed.message + "\n" + parsed.stack.join("\n"));
21458 util.notEnumerableProp(error, "__stackCleaned__", true);
21463 function checkForgottenReturns(returnValue, promiseCreated, name, promise,
21465 if (returnValue === undefined && promiseCreated !== null &&
21466 wForgottenReturn) {
21467 if (parent !== undefined && parent._returnedNonUndefined()) return;
21468 if ((promise._bitField & 65535) === 0) return;
21470 if (name) name = name + " ";
21471 var handlerLine = "";
21472 var creatorLine = "";
21473 if (promiseCreated._trace) {
21474 var traceLines = promiseCreated._trace.stack.split("\n");
21475 var stack = cleanStack(traceLines);
21476 for (var i = stack.length - 1; i >= 0; --i) {
21477 var line = stack[i];
21478 if (!nodeFramePattern.test(line)) {
21479 var lineMatches = line.match(parseLinePattern);
21481 handlerLine = "at " + lineMatches[1] +
21482 ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
21488 if (stack.length > 0) {
21489 var firstUserLine = stack[0];
21490 for (var i = 0; i < traceLines.length; ++i) {
21492 if (traceLines[i] === firstUserLine) {
21494 creatorLine = "\n" + traceLines[i - 1];
21502 var msg = "a promise was created in a " + name +
21503 "handler " + handlerLine + "but was not returned from it, " +
21504 "see http://goo.gl/rRqMUw" +
21506 promise._warn(msg, true, promiseCreated);
21510 function deprecated(name, replacement) {
21511 var message = name +
21512 " is deprecated and will be removed in a future version.";
21513 if (replacement) message += " Use " + replacement + " instead.";
21514 return warn(message);
21517 function warn(message, shouldUseOwnTrace, promise) {
21518 if (!config.warnings) return;
21519 var warning = new Warning(message);
21521 if (shouldUseOwnTrace) {
21522 promise._attachExtraTrace(warning);
21523 } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
21524 ctx.attachExtraTrace(warning);
21526 var parsed = parseStackAndMessage(warning);
21527 warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
21530 if (!activeFireEvent("warning", warning)) {
21531 formatAndLogError(warning, "", true);
21535 function reconstructStack(message, stacks) {
21536 for (var i = 0; i < stacks.length - 1; ++i) {
21537 stacks[i].push("From previous event:");
21538 stacks[i] = stacks[i].join("\n");
21540 if (i < stacks.length) {
21541 stacks[i] = stacks[i].join("\n");
21543 return message + "\n" + stacks.join("\n");
21546 function removeDuplicateOrEmptyJumps(stacks) {
21547 for (var i = 0; i < stacks.length; ++i) {
21548 if (stacks[i].length === 0 ||
21549 ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
21550 stacks.splice(i, 1);
21556 function removeCommonRoots(stacks) {
21557 var current = stacks[0];
21558 for (var i = 1; i < stacks.length; ++i) {
21559 var prev = stacks[i];
21560 var currentLastIndex = current.length - 1;
21561 var currentLastLine = current[currentLastIndex];
21562 var commonRootMeetPoint = -1;
21564 for (var j = prev.length - 1; j >= 0; --j) {
21565 if (prev[j] === currentLastLine) {
21566 commonRootMeetPoint = j;
21571 for (var j = commonRootMeetPoint; j >= 0; --j) {
21572 var line = prev[j];
21573 if (current[currentLastIndex] === line) {
21575 currentLastIndex--;
21584 function cleanStack(stack) {
21586 for (var i = 0; i < stack.length; ++i) {
21587 var line = stack[i];
21588 var isTraceLine = " (No stack trace)" === line ||
21589 stackFramePattern.test(line);
21590 var isInternalFrame = isTraceLine && shouldIgnore(line);
21591 if (isTraceLine && !isInternalFrame) {
21592 if (indentStackFrames && line.charAt(0) !== " ") {
21601 function stackFramesAsArray(error) {
21602 var stack = error.stack.replace(/\s+$/g, "").split("\n");
21603 for (var i = 0; i < stack.length; ++i) {
21604 var line = stack[i];
21605 if (" (No stack trace)" === line || stackFramePattern.test(line)) {
21609 if (i > 0 && error.name != "SyntaxError") {
21610 stack = stack.slice(i);
21615 function parseStackAndMessage(error) {
21616 var stack = error.stack;
21617 var message = error.toString();
21618 stack = typeof stack === "string" && stack.length > 0
21619 ? stackFramesAsArray(error) : [" (No stack trace)"];
21622 stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
21626 function formatAndLogError(error, title, isSoft) {
21627 if (typeof console !== "undefined") {
21629 if (util.isObject(error)) {
21630 var stack = error.stack;
21631 message = title + formatStack(stack, error);
21633 message = title + String(error);
21635 if (typeof printWarning === "function") {
21636 printWarning(message, isSoft);
21637 } else if (typeof console.log === "function" ||
21638 typeof console.log === "object") {
21639 console.log(message);
21644 function fireRejectionEvent(name, localHandler, reason, promise) {
21645 var localEventFired = false;
21647 if (typeof localHandler === "function") {
21648 localEventFired = true;
21649 if (name === "rejectionHandled") {
21650 localHandler(promise);
21652 localHandler(reason, promise);
21656 async.throwLater(e);
21659 if (name === "unhandledRejection") {
21660 if (!activeFireEvent(name, reason, promise) && !localEventFired) {
21661 formatAndLogError(reason, "Unhandled rejection ");
21664 activeFireEvent(name, promise);
21668 function formatNonError(obj) {
21670 if (typeof obj === "function") {
21671 str = "[function " +
21672 (obj.name || "anonymous") +
21675 str = obj && typeof obj.toString === "function"
21676 ? obj.toString() : util.toString(obj);
21677 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
21678 if (ruselessToString.test(str)) {
21680 var newStr = JSON.stringify(obj);
21687 if (str.length === 0) {
21688 str = "(empty array)";
21691 return ("(<" + snip(str) + ">, no stack trace)");
21694 function snip(str) {
21696 if (str.length < maxChars) {
21699 return str.substr(0, maxChars - 3) + "...";
21702 function longStackTracesIsSupported() {
21703 return typeof captureStackTrace === "function";
21706 var shouldIgnore = function() { return false; };
21707 var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
21708 function parseLineInfo(line) {
21709 var matches = line.match(parseLineInfoRegex);
21712 fileName: matches[1],
21713 line: parseInt(matches[2], 10)
21718 function setBounds(firstLineError, lastLineError) {
21719 if (!longStackTracesIsSupported()) return;
21720 var firstStackLines = firstLineError.stack.split("\n");
21721 var lastStackLines = lastLineError.stack.split("\n");
21722 var firstIndex = -1;
21723 var lastIndex = -1;
21726 for (var i = 0; i < firstStackLines.length; ++i) {
21727 var result = parseLineInfo(firstStackLines[i]);
21729 firstFileName = result.fileName;
21730 firstIndex = result.line;
21734 for (var i = 0; i < lastStackLines.length; ++i) {
21735 var result = parseLineInfo(lastStackLines[i]);
21737 lastFileName = result.fileName;
21738 lastIndex = result.line;
21742 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
21743 firstFileName !== lastFileName || firstIndex >= lastIndex) {
21747 shouldIgnore = function(line) {
21748 if (bluebirdFramePattern.test(line)) return true;
21749 var info = parseLineInfo(line);
21751 if (info.fileName === firstFileName &&
21752 (firstIndex <= info.line && info.line <= lastIndex)) {
21760 function CapturedTrace(parent) {
21761 this._parent = parent;
21762 this._promisesCreated = 0;
21763 var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
21764 captureStackTrace(this, CapturedTrace);
21765 if (length > 32) this.uncycle();
21767 util.inherits(CapturedTrace, Error);
21768 Context.CapturedTrace = CapturedTrace;
21770 CapturedTrace.prototype.uncycle = function() {
21771 var length = this._length;
21772 if (length < 2) return;
21774 var stackToIndex = {};
21776 for (var i = 0, node = this; node !== undefined; ++i) {
21778 node = node._parent;
21780 length = this._length = i;
21781 for (var i = length - 1; i >= 0; --i) {
21782 var stack = nodes[i].stack;
21783 if (stackToIndex[stack] === undefined) {
21784 stackToIndex[stack] = i;
21787 for (var i = 0; i < length; ++i) {
21788 var currentStack = nodes[i].stack;
21789 var index = stackToIndex[currentStack];
21790 if (index !== undefined && index !== i) {
21792 nodes[index - 1]._parent = undefined;
21793 nodes[index - 1]._length = 1;
21795 nodes[i]._parent = undefined;
21796 nodes[i]._length = 1;
21797 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
21799 if (index < length - 1) {
21800 cycleEdgeNode._parent = nodes[index + 1];
21801 cycleEdgeNode._parent.uncycle();
21802 cycleEdgeNode._length =
21803 cycleEdgeNode._parent._length + 1;
21805 cycleEdgeNode._parent = undefined;
21806 cycleEdgeNode._length = 1;
21808 var currentChildLength = cycleEdgeNode._length + 1;
21809 for (var j = i - 2; j >= 0; --j) {
21810 nodes[j]._length = currentChildLength;
21811 currentChildLength++;
21818 CapturedTrace.prototype.attachExtraTrace = function(error) {
21819 if (error.__stackCleaned__) return;
21821 var parsed = parseStackAndMessage(error);
21822 var message = parsed.message;
21823 var stacks = [parsed.stack];
21826 while (trace !== undefined) {
21827 stacks.push(cleanStack(trace.stack.split("\n")));
21828 trace = trace._parent;
21830 removeCommonRoots(stacks);
21831 removeDuplicateOrEmptyJumps(stacks);
21832 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
21833 util.notEnumerableProp(error, "__stackCleaned__", true);
21836 var captureStackTrace = (function stackDetection() {
21837 var v8stackFramePattern = /^\s*at\s*/;
21838 var v8stackFormatter = function(stack, error) {
21839 if (typeof stack === "string") return stack;
21841 if (error.name !== undefined &&
21842 error.message !== undefined) {
21843 return error.toString();
21845 return formatNonError(error);
21848 if (typeof Error.stackTraceLimit === "number" &&
21849 typeof Error.captureStackTrace === "function") {
21850 Error.stackTraceLimit += 6;
21851 stackFramePattern = v8stackFramePattern;
21852 formatStack = v8stackFormatter;
21853 var captureStackTrace = Error.captureStackTrace;
21855 shouldIgnore = function(line) {
21856 return bluebirdFramePattern.test(line);
21858 return function(receiver, ignoreUntil) {
21859 Error.stackTraceLimit += 6;
21860 captureStackTrace(receiver, ignoreUntil);
21861 Error.stackTraceLimit -= 6;
21864 var err = new Error();
21866 if (typeof err.stack === "string" &&
21867 err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
21868 stackFramePattern = /@/;
21869 formatStack = v8stackFormatter;
21870 indentStackFrames = true;
21871 return function captureStackTrace(o) {
21872 o.stack = new Error().stack;
21876 var hasStackAfterThrow;
21877 try { throw new Error(); }
21879 hasStackAfterThrow = ("stack" in e);
21881 if (!("stack" in err) && hasStackAfterThrow &&
21882 typeof Error.stackTraceLimit === "number") {
21883 stackFramePattern = v8stackFramePattern;
21884 formatStack = v8stackFormatter;
21885 return function captureStackTrace(o) {
21886 Error.stackTraceLimit += 6;
21887 try { throw new Error(); }
21888 catch(e) { o.stack = e.stack; }
21889 Error.stackTraceLimit -= 6;
21893 formatStack = function(stack, error) {
21894 if (typeof stack === "string") return stack;
21896 if ((typeof error === "object" ||
21897 typeof error === "function") &&
21898 error.name !== undefined &&
21899 error.message !== undefined) {
21900 return error.toString();
21902 return formatNonError(error);
21909 if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
21910 printWarning = function (message) {
21911 console.warn(message);
21913 if (util.isNode && process.stderr.isTTY) {
21914 printWarning = function(message, isSoft) {
21915 var color = isSoft ? "\u001b[33m" : "\u001b[31m";
21916 console.warn(color + message + "\u001b[0m\n");
21918 } else if (!util.isNode && typeof (new Error().stack) === "string") {
21919 printWarning = function(message, isSoft) {
21920 console.warn("%c" + message,
21921 isSoft ? "color: darkorange" : "color: red");
21927 warnings: warnings,
21928 longStackTraces: false,
21929 cancellation: false,
21933 if (longStackTraces) Promise.longStackTraces();
21936 longStackTraces: function() {
21937 return config.longStackTraces;
21939 warnings: function() {
21940 return config.warnings;
21942 cancellation: function() {
21943 return config.cancellation;
21945 monitoring: function() {
21946 return config.monitoring;
21948 propagateFromFunction: function() {
21949 return propagateFromFunction;
21951 boundValueFunction: function() {
21952 return boundValueFunction;
21954 checkForgottenReturns: checkForgottenReturns,
21955 setBounds: setBounds,
21957 deprecated: deprecated,
21958 CapturedTrace: CapturedTrace,
21959 fireDomEvent: fireDomEvent,
21960 fireGlobalEvent: fireGlobalEvent
21967 /***/ (function(module, exports, __webpack_require__) {
21971 module.exports = function(Promise, tryConvertToPromise) {
21972 var util = __webpack_require__(130);
21973 var CancellationError = Promise.CancellationError;
21974 var errorObj = util.errorObj;
21976 function PassThroughHandlerContext(promise, type, handler) {
21977 this.promise = promise;
21979 this.handler = handler;
21980 this.called = false;
21981 this.cancelPromise = null;
21984 PassThroughHandlerContext.prototype.isFinallyHandler = function() {
21985 return this.type === 0;
21988 function FinallyHandlerCancelReaction(finallyHandler) {
21989 this.finallyHandler = finallyHandler;
21992 FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
21993 checkCancel(this.finallyHandler);
21996 function checkCancel(ctx, reason) {
21997 if (ctx.cancelPromise != null) {
21998 if (arguments.length > 1) {
21999 ctx.cancelPromise._reject(reason);
22001 ctx.cancelPromise._cancel();
22003 ctx.cancelPromise = null;
22009 function succeed() {
22010 return finallyHandler.call(this, this.promise._target()._settledValue());
22012 function fail(reason) {
22013 if (checkCancel(this, reason)) return;
22014 errorObj.e = reason;
22017 function finallyHandler(reasonOrValue) {
22018 var promise = this.promise;
22019 var handler = this.handler;
22021 if (!this.called) {
22022 this.called = true;
22023 var ret = this.isFinallyHandler()
22024 ? handler.call(promise._boundValue())
22025 : handler.call(promise._boundValue(), reasonOrValue);
22026 if (ret !== undefined) {
22027 promise._setReturnedNonUndefined();
22028 var maybePromise = tryConvertToPromise(ret, promise);
22029 if (maybePromise instanceof Promise) {
22030 if (this.cancelPromise != null) {
22031 if (maybePromise._isCancelled()) {
22033 new CancellationError("late cancellation observer");
22034 promise._attachExtraTrace(reason);
22035 errorObj.e = reason;
22037 } else if (maybePromise.isPending()) {
22038 maybePromise._attachCancellationCallback(
22039 new FinallyHandlerCancelReaction(this));
22042 return maybePromise._then(
22043 succeed, fail, undefined, this, undefined);
22048 if (promise.isRejected()) {
22050 errorObj.e = reasonOrValue;
22054 return reasonOrValue;
22058 Promise.prototype._passThrough = function(handler, type, success, fail) {
22059 if (typeof handler !== "function") return this.then();
22060 return this._then(success,
22063 new PassThroughHandlerContext(this, type, handler),
22067 Promise.prototype.lastly =
22068 Promise.prototype["finally"] = function (handler) {
22069 return this._passThrough(handler,
22075 Promise.prototype.tap = function (handler) {
22076 return this._passThrough(handler, 1, finallyHandler);
22079 return PassThroughHandlerContext;
22085 /***/ (function(module, exports, __webpack_require__) {
22089 module.exports = function(NEXT_FILTER) {
22090 var util = __webpack_require__(130);
22091 var getKeys = __webpack_require__(131).keys;
22092 var tryCatch = util.tryCatch;
22093 var errorObj = util.errorObj;
22095 function catchFilter(instances, cb, promise) {
22096 return function(e) {
22097 var boundTo = promise._boundValue();
22098 predicateLoop: for (var i = 0; i < instances.length; ++i) {
22099 var item = instances[i];
22101 if (item === Error ||
22102 (item != null && item.prototype instanceof Error)) {
22103 if (e instanceof item) {
22104 return tryCatch(cb).call(boundTo, e);
22106 } else if (typeof item === "function") {
22107 var matchesPredicate = tryCatch(item).call(boundTo, e);
22108 if (matchesPredicate === errorObj) {
22109 return matchesPredicate;
22110 } else if (matchesPredicate) {
22111 return tryCatch(cb).call(boundTo, e);
22113 } else if (util.isObject(e)) {
22114 var keys = getKeys(item);
22115 for (var j = 0; j < keys.length; ++j) {
22117 if (item[key] != e[key]) {
22118 continue predicateLoop;
22121 return tryCatch(cb).call(boundTo, e);
22124 return NEXT_FILTER;
22128 return catchFilter;
22134 /***/ (function(module, exports, __webpack_require__) {
22138 var util = __webpack_require__(130);
22139 var maybeWrapAsError = util.maybeWrapAsError;
22140 var errors = __webpack_require__(135);
22141 var OperationalError = errors.OperationalError;
22142 var es5 = __webpack_require__(131);
22144 function isUntypedError(obj) {
22145 return obj instanceof Error &&
22146 es5.getPrototypeOf(obj) === Error.prototype;
22149 var rErrorKey = /^(?:name|message|stack|cause)$/;
22150 function wrapAsOperationalError(obj) {
22152 if (isUntypedError(obj)) {
22153 ret = new OperationalError(obj);
22154 ret.name = obj.name;
22155 ret.message = obj.message;
22156 ret.stack = obj.stack;
22157 var keys = es5.keys(obj);
22158 for (var i = 0; i < keys.length; ++i) {
22160 if (!rErrorKey.test(key)) {
22161 ret[key] = obj[key];
22166 util.markAsOriginatingFromRejection(obj);
22170 function nodebackForPromise(promise, multiArgs) {
22171 return function(err, value) {
22172 if (promise === null) return;
22174 var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
22175 promise._attachExtraTrace(wrapped);
22176 promise._reject(wrapped);
22177 } else if (!multiArgs) {
22178 promise._fulfill(value);
22180 var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
22181 promise._fulfill(args);
22187 module.exports = nodebackForPromise;
22192 /***/ (function(module, exports, __webpack_require__) {
22197 function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
22198 var util = __webpack_require__(130);
22199 var tryCatch = util.tryCatch;
22201 Promise.method = function (fn) {
22202 if (typeof fn !== "function") {
22203 throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
22205 return function () {
22206 var ret = new Promise(INTERNAL);
22207 ret._captureStackTrace();
22208 ret._pushContext();
22209 var value = tryCatch(fn).apply(this, arguments);
22210 var promiseCreated = ret._popContext();
22211 debug.checkForgottenReturns(
22212 value, promiseCreated, "Promise.method", ret);
22213 ret._resolveFromSyncValue(value);
22218 Promise.attempt = Promise["try"] = function (fn) {
22219 if (typeof fn !== "function") {
22220 return apiRejection("expecting a function but got " + util.classString(fn));
22222 var ret = new Promise(INTERNAL);
22223 ret._captureStackTrace();
22224 ret._pushContext();
22226 if (arguments.length > 1) {
22227 debug.deprecated("calling Promise.try with more than 1 argument");
22228 var arg = arguments[1];
22229 var ctx = arguments[2];
22230 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
22231 : tryCatch(fn).call(ctx, arg);
22233 value = tryCatch(fn)();
22235 var promiseCreated = ret._popContext();
22236 debug.checkForgottenReturns(
22237 value, promiseCreated, "Promise.try", ret);
22238 ret._resolveFromSyncValue(value);
22242 Promise.prototype._resolveFromSyncValue = function (value) {
22243 if (value === util.errorObj) {
22244 this._rejectCallback(value.e, false);
22246 this._resolveCallback(value, true);
22254 /***/ (function(module, exports, __webpack_require__) {
22258 module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
22259 var calledBind = false;
22260 var rejectThis = function(_, e) {
22264 var targetRejected = function(e, context) {
22265 context.promiseRejectionQueued = true;
22266 context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
22269 var bindingResolved = function(thisArg, context) {
22270 if (((this._bitField & 50397184) === 0)) {
22271 this._resolveCallback(context.target);
22275 var bindingRejected = function(e, context) {
22276 if (!context.promiseRejectionQueued) this._reject(e);
22279 Promise.prototype.bind = function (thisArg) {
22282 Promise.prototype._propagateFrom = debug.propagateFromFunction();
22283 Promise.prototype._boundValue = debug.boundValueFunction();
22285 var maybePromise = tryConvertToPromise(thisArg);
22286 var ret = new Promise(INTERNAL);
22287 ret._propagateFrom(this, 1);
22288 var target = this._target();
22289 ret._setBoundTo(maybePromise);
22290 if (maybePromise instanceof Promise) {
22292 promiseRejectionQueued: false,
22295 bindingPromise: maybePromise
22297 target._then(INTERNAL, targetRejected, undefined, ret, context);
22298 maybePromise._then(
22299 bindingResolved, bindingRejected, undefined, ret, context);
22300 ret._setOnCancel(maybePromise);
22302 ret._resolveCallback(target);
22307 Promise.prototype._setBoundTo = function (obj) {
22308 if (obj !== undefined) {
22309 this._bitField = this._bitField | 2097152;
22310 this._boundTo = obj;
22312 this._bitField = this._bitField & (~2097152);
22316 Promise.prototype._isBound = function () {
22317 return (this._bitField & 2097152) === 2097152;
22320 Promise.bind = function (thisArg, value) {
22321 return Promise.resolve(value).bind(thisArg);
22328 /***/ (function(module, exports, __webpack_require__) {
22332 module.exports = function(Promise, PromiseArray, apiRejection, debug) {
22333 var util = __webpack_require__(130);
22334 var tryCatch = util.tryCatch;
22335 var errorObj = util.errorObj;
22336 var async = Promise._async;
22338 Promise.prototype["break"] = Promise.prototype.cancel = function() {
22339 if (!debug.cancellation()) return this._warn("cancellation is disabled");
22341 var promise = this;
22342 var child = promise;
22343 while (promise._isCancellable()) {
22344 if (!promise._cancelBy(child)) {
22345 if (child._isFollowing()) {
22346 child._followee().cancel();
22348 child._cancelBranched();
22353 var parent = promise._cancellationParent;
22354 if (parent == null || !parent._isCancellable()) {
22355 if (promise._isFollowing()) {
22356 promise._followee().cancel();
22358 promise._cancelBranched();
22362 if (promise._isFollowing()) promise._followee().cancel();
22363 promise._setWillBeCancelled();
22370 Promise.prototype._branchHasCancelled = function() {
22371 this._branchesRemainingToCancel--;
22374 Promise.prototype._enoughBranchesHaveCancelled = function() {
22375 return this._branchesRemainingToCancel === undefined ||
22376 this._branchesRemainingToCancel <= 0;
22379 Promise.prototype._cancelBy = function(canceller) {
22380 if (canceller === this) {
22381 this._branchesRemainingToCancel = 0;
22382 this._invokeOnCancel();
22385 this._branchHasCancelled();
22386 if (this._enoughBranchesHaveCancelled()) {
22387 this._invokeOnCancel();
22394 Promise.prototype._cancelBranched = function() {
22395 if (this._enoughBranchesHaveCancelled()) {
22400 Promise.prototype._cancel = function() {
22401 if (!this._isCancellable()) return;
22402 this._setCancelled();
22403 async.invoke(this._cancelPromises, this, undefined);
22406 Promise.prototype._cancelPromises = function() {
22407 if (this._length() > 0) this._settlePromises();
22410 Promise.prototype._unsetOnCancel = function() {
22411 this._onCancelField = undefined;
22414 Promise.prototype._isCancellable = function() {
22415 return this.isPending() && !this._isCancelled();
22418 Promise.prototype.isCancellable = function() {
22419 return this.isPending() && !this.isCancelled();
22422 Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
22423 if (util.isArray(onCancelCallback)) {
22424 for (var i = 0; i < onCancelCallback.length; ++i) {
22425 this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
22427 } else if (onCancelCallback !== undefined) {
22428 if (typeof onCancelCallback === "function") {
22429 if (!internalOnly) {
22430 var e = tryCatch(onCancelCallback).call(this._boundValue());
22431 if (e === errorObj) {
22432 this._attachExtraTrace(e.e);
22433 async.throwLater(e.e);
22437 onCancelCallback._resultCancelled(this);
22442 Promise.prototype._invokeOnCancel = function() {
22443 var onCancelCallback = this._onCancel();
22444 this._unsetOnCancel();
22445 async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
22448 Promise.prototype._invokeInternalOnCancel = function() {
22449 if (this._isCancellable()) {
22450 this._doInvokeOnCancel(this._onCancel(), true);
22451 this._unsetOnCancel();
22455 Promise.prototype._resultCancelled = function() {
22464 /***/ (function(module, exports, __webpack_require__) {
22468 module.exports = function(Promise) {
22469 function returner() {
22472 function thrower() {
22476 Promise.prototype["return"] =
22477 Promise.prototype.thenReturn = function (value) {
22478 if (value instanceof Promise) value.suppressUnhandledRejections();
22480 returner, undefined, undefined, {value: value}, undefined);
22483 Promise.prototype["throw"] =
22484 Promise.prototype.thenThrow = function (reason) {
22486 thrower, undefined, undefined, {reason: reason}, undefined);
22489 Promise.prototype.catchThrow = function (reason) {
22490 if (arguments.length <= 1) {
22492 undefined, thrower, undefined, {reason: reason}, undefined);
22494 var _reason = arguments[1];
22495 var handler = function() {throw _reason;};
22496 return this.caught(reason, handler);
22500 Promise.prototype.catchReturn = function (value) {
22501 if (arguments.length <= 1) {
22502 if (value instanceof Promise) value.suppressUnhandledRejections();
22504 undefined, returner, undefined, {value: value}, undefined);
22506 var _value = arguments[1];
22507 if (_value instanceof Promise) _value.suppressUnhandledRejections();
22508 var handler = function() {return _value;};
22509 return this.caught(value, handler);
22517 /***/ (function(module, exports, __webpack_require__) {
22521 module.exports = function(Promise) {
22522 function PromiseInspection(promise) {
22523 if (promise !== undefined) {
22524 promise = promise._target();
22525 this._bitField = promise._bitField;
22526 this._settledValueField = promise._isFateSealed()
22527 ? promise._settledValue() : undefined;
22530 this._bitField = 0;
22531 this._settledValueField = undefined;
22535 PromiseInspection.prototype._settledValue = function() {
22536 return this._settledValueField;
22539 var value = PromiseInspection.prototype.value = function () {
22540 if (!this.isFulfilled()) {
22541 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
22543 return this._settledValue();
22546 var reason = PromiseInspection.prototype.error =
22547 PromiseInspection.prototype.reason = function () {
22548 if (!this.isRejected()) {
22549 throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
22551 return this._settledValue();
22554 var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
22555 return (this._bitField & 33554432) !== 0;
22558 var isRejected = PromiseInspection.prototype.isRejected = function () {
22559 return (this._bitField & 16777216) !== 0;
22562 var isPending = PromiseInspection.prototype.isPending = function () {
22563 return (this._bitField & 50397184) === 0;
22566 var isResolved = PromiseInspection.prototype.isResolved = function () {
22567 return (this._bitField & 50331648) !== 0;
22570 PromiseInspection.prototype.isCancelled = function() {
22571 return (this._bitField & 8454144) !== 0;
22574 Promise.prototype.__isCancelled = function() {
22575 return (this._bitField & 65536) === 65536;
22578 Promise.prototype._isCancelled = function() {
22579 return this._target().__isCancelled();
22582 Promise.prototype.isCancelled = function() {
22583 return (this._target()._bitField & 8454144) !== 0;
22586 Promise.prototype.isPending = function() {
22587 return isPending.call(this._target());
22590 Promise.prototype.isRejected = function() {
22591 return isRejected.call(this._target());
22594 Promise.prototype.isFulfilled = function() {
22595 return isFulfilled.call(this._target());
22598 Promise.prototype.isResolved = function() {
22599 return isResolved.call(this._target());
22602 Promise.prototype.value = function() {
22603 return value.call(this._target());
22606 Promise.prototype.reason = function() {
22607 var target = this._target();
22608 target._unsetRejectionIsUnhandled();
22609 return reason.call(target);
22612 Promise.prototype._value = function() {
22613 return this._settledValue();
22616 Promise.prototype._reason = function() {
22617 this._unsetRejectionIsUnhandled();
22618 return this._settledValue();
22621 Promise.PromiseInspection = PromiseInspection;
22627 /***/ (function(module, exports, __webpack_require__) {
22632 function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
22634 var util = __webpack_require__(130);
22635 var canEvaluate = util.canEvaluate;
22636 var tryCatch = util.tryCatch;
22637 var errorObj = util.errorObj;
22642 var thenCallback = function(i) {
22643 return new Function("value", "holder", " \n\
22645 holder.pIndex = value; \n\
22646 holder.checkFulfillment(this); \n\
22647 ".replace(/Index/g, i));
22650 var promiseSetter = function(i) {
22651 return new Function("promise", "holder", " \n\
22653 holder.pIndex = promise; \n\
22654 ".replace(/Index/g, i));
22657 var generateHolderClass = function(total) {
22658 var props = new Array(total);
22659 for (var i = 0; i < props.length; ++i) {
22660 props[i] = "this.p" + (i+1);
22662 var assignment = props.join(" = ") + " = null;";
22663 var cancellationCode= "var promise;\n" + props.map(function(prop) {
22665 promise = " + prop + "; \n\
22666 if (promise instanceof Promise) { \n\
22667 promise.cancel(); \n\
22671 var passedArguments = props.join(", ");
22672 var name = "Holder$" + total;
22675 var code = "return function(tryCatch, errorObj, Promise, async) { \n\
22677 function [TheName](fn) { \n\
22678 [TheProperties] \n\
22680 this.asyncNeeded = true; \n\
22684 [TheName].prototype._callFunction = function(promise) { \n\
22685 promise._pushContext(); \n\
22686 var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
22687 promise._popContext(); \n\
22688 if (ret === errorObj) { \n\
22689 promise._rejectCallback(ret.e, false); \n\
22691 promise._resolveCallback(ret); \n\
22695 [TheName].prototype.checkFulfillment = function(promise) { \n\
22696 var now = ++this.now; \n\
22697 if (now === [TheTotal]) { \n\
22698 if (this.asyncNeeded) { \n\
22699 async.invoke(this._callFunction, this, promise); \n\
22701 this._callFunction(promise); \n\
22707 [TheName].prototype._resultCancelled = function() { \n\
22708 [CancellationCode] \n\
22711 return [TheName]; \n\
22712 }(tryCatch, errorObj, Promise, async); \n\
22715 code = code.replace(/\[TheName\]/g, name)
22716 .replace(/\[TheTotal\]/g, total)
22717 .replace(/\[ThePassedArguments\]/g, passedArguments)
22718 .replace(/\[TheProperties\]/g, assignment)
22719 .replace(/\[CancellationCode\]/g, cancellationCode);
22721 return new Function("tryCatch", "errorObj", "Promise", "async", code)
22722 (tryCatch, errorObj, Promise, async);
22725 var holderClasses = [];
22726 var thenCallbacks = [];
22727 var promiseSetters = [];
22729 for (var i = 0; i < 8; ++i) {
22730 holderClasses.push(generateHolderClass(i + 1));
22731 thenCallbacks.push(thenCallback(i + 1));
22732 promiseSetters.push(promiseSetter(i + 1));
22735 reject = function (reason) {
22736 this._reject(reason);
22740 Promise.join = function () {
22741 var last = arguments.length - 1;
22743 if (last > 0 && typeof arguments[last] === "function") {
22744 fn = arguments[last];
22746 if (last <= 8 && canEvaluate) {
22747 var ret = new Promise(INTERNAL);
22748 ret._captureStackTrace();
22749 var HolderClass = holderClasses[last - 1];
22750 var holder = new HolderClass(fn);
22751 var callbacks = thenCallbacks;
22753 for (var i = 0; i < last; ++i) {
22754 var maybePromise = tryConvertToPromise(arguments[i], ret);
22755 if (maybePromise instanceof Promise) {
22756 maybePromise = maybePromise._target();
22757 var bitField = maybePromise._bitField;
22759 if (((bitField & 50397184) === 0)) {
22760 maybePromise._then(callbacks[i], reject,
22761 undefined, ret, holder);
22762 promiseSetters[i](maybePromise, holder);
22763 holder.asyncNeeded = false;
22764 } else if (((bitField & 33554432) !== 0)) {
22765 callbacks[i].call(ret,
22766 maybePromise._value(), holder);
22767 } else if (((bitField & 16777216) !== 0)) {
22768 ret._reject(maybePromise._reason());
22773 callbacks[i].call(ret, maybePromise, holder);
22777 if (!ret._isFateSealed()) {
22778 if (holder.asyncNeeded) {
22779 var domain = getDomain();
22780 if (domain !== null) {
22781 holder.fn = util.domainBind(domain, holder.fn);
22784 ret._setAsyncGuaranteed();
22785 ret._setOnCancel(holder);
22791 var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
22792 if (fn) args.pop();
22793 var ret = new PromiseArray(args).promise();
22794 return fn !== undefined ? ret.spread(fn) : ret;
22802 /***/ (function(module, exports, __webpack_require__) {
22806 module.exports = function(Promise,
22809 tryConvertToPromise,
22812 var getDomain = Promise._getDomain;
22813 var util = __webpack_require__(130);
22814 var tryCatch = util.tryCatch;
22815 var errorObj = util.errorObj;
22816 var async = Promise._async;
22818 function MappingPromiseArray(promises, fn, limit, _filter) {
22819 this.constructor$(promises);
22820 this._promise._captureStackTrace();
22821 var domain = getDomain();
22822 this._callback = domain === null ? fn : util.domainBind(domain, fn);
22823 this._preservedValues = _filter === INTERNAL
22824 ? new Array(this.length())
22826 this._limit = limit;
22827 this._inFlight = 0;
22829 async.invoke(this._asyncInit, this, undefined);
22831 util.inherits(MappingPromiseArray, PromiseArray);
22833 MappingPromiseArray.prototype._asyncInit = function() {
22834 this._init$(undefined, -2);
22837 MappingPromiseArray.prototype._init = function () {};
22839 MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
22840 var values = this._values;
22841 var length = this.length();
22842 var preservedValues = this._preservedValues;
22843 var limit = this._limit;
22846 index = (index * -1) - 1;
22847 values[index] = value;
22850 this._drainQueue();
22851 if (this._isResolved()) return true;
22854 if (limit >= 1 && this._inFlight >= limit) {
22855 values[index] = value;
22856 this._queue.push(index);
22859 if (preservedValues !== null) preservedValues[index] = value;
22861 var promise = this._promise;
22862 var callback = this._callback;
22863 var receiver = promise._boundValue();
22864 promise._pushContext();
22865 var ret = tryCatch(callback).call(receiver, value, index, length);
22866 var promiseCreated = promise._popContext();
22867 debug.checkForgottenReturns(
22870 preservedValues !== null ? "Promise.filter" : "Promise.map",
22873 if (ret === errorObj) {
22874 this._reject(ret.e);
22878 var maybePromise = tryConvertToPromise(ret, this._promise);
22879 if (maybePromise instanceof Promise) {
22880 maybePromise = maybePromise._target();
22881 var bitField = maybePromise._bitField;
22883 if (((bitField & 50397184) === 0)) {
22884 if (limit >= 1) this._inFlight++;
22885 values[index] = maybePromise;
22886 maybePromise._proxy(this, (index + 1) * -1);
22888 } else if (((bitField & 33554432) !== 0)) {
22889 ret = maybePromise._value();
22890 } else if (((bitField & 16777216) !== 0)) {
22891 this._reject(maybePromise._reason());
22898 values[index] = ret;
22900 var totalResolved = ++this._totalResolved;
22901 if (totalResolved >= length) {
22902 if (preservedValues !== null) {
22903 this._filter(values, preservedValues);
22905 this._resolve(values);
22912 MappingPromiseArray.prototype._drainQueue = function () {
22913 var queue = this._queue;
22914 var limit = this._limit;
22915 var values = this._values;
22916 while (queue.length > 0 && this._inFlight < limit) {
22917 if (this._isResolved()) return;
22918 var index = queue.pop();
22919 this._promiseFulfilled(values[index], index);
22923 MappingPromiseArray.prototype._filter = function (booleans, values) {
22924 var len = values.length;
22925 var ret = new Array(len);
22927 for (var i = 0; i < len; ++i) {
22928 if (booleans[i]) ret[j++] = values[i];
22931 this._resolve(ret);
22934 MappingPromiseArray.prototype.preservedValues = function () {
22935 return this._preservedValues;
22938 function map(promises, fn, options, _filter) {
22939 if (typeof fn !== "function") {
22940 return apiRejection("expecting a function but got " + util.classString(fn));
22944 if (options !== undefined) {
22945 if (typeof options === "object" && options !== null) {
22946 if (typeof options.concurrency !== "number") {
22947 return Promise.reject(
22948 new TypeError("'concurrency' must be a number but it is " +
22949 util.classString(options.concurrency)));
22951 limit = options.concurrency;
22953 return Promise.reject(new TypeError(
22954 "options argument must be an object but it is " +
22955 util.classString(options)));
22958 limit = typeof limit === "number" &&
22959 isFinite(limit) && limit >= 1 ? limit : 0;
22960 return new MappingPromiseArray(promises, fn, limit, _filter).promise();
22963 Promise.prototype.map = function (fn, options) {
22964 return map(this, fn, options, null);
22967 Promise.map = function (promises, fn, options, _filter) {
22968 return map(promises, fn, options, _filter);
22977 /***/ (function(module, exports, __webpack_require__) {
22981 var cr = Object.create;
22983 var callerCache = cr(null);
22984 var getterCache = cr(null);
22985 callerCache[" size"] = getterCache[" size"] = 0;
22988 module.exports = function(Promise) {
22989 var util = __webpack_require__(130);
22990 var canEvaluate = util.canEvaluate;
22991 var isIdentifier = util.isIdentifier;
22993 var getMethodCaller;
22996 var makeMethodCaller = function (methodName) {
22997 return new Function("ensureMethod", " \n\
22998 return function(obj) { \n\
23000 var len = this.length; \n\
23001 ensureMethod(obj, 'methodName'); \n\
23003 case 1: return obj.methodName(this[0]); \n\
23004 case 2: return obj.methodName(this[0], this[1]); \n\
23005 case 3: return obj.methodName(this[0], this[1], this[2]); \n\
23006 case 0: return obj.methodName(); \n\
23008 return obj.methodName.apply(obj, this); \n\
23011 ".replace(/methodName/g, methodName))(ensureMethod);
23014 var makeGetter = function (propertyName) {
23015 return new Function("obj", " \n\
23017 return obj.propertyName; \n\
23018 ".replace("propertyName", propertyName));
23021 var getCompiled = function(name, compiler, cache) {
23022 var ret = cache[name];
23023 if (typeof ret !== "function") {
23024 if (!isIdentifier(name)) {
23027 ret = compiler(name);
23030 if (cache[" size"] > 512) {
23031 var keys = Object.keys(cache);
23032 for (var i = 0; i < 256; ++i) delete cache[keys[i]];
23033 cache[" size"] = keys.length - 256;
23039 getMethodCaller = function(name) {
23040 return getCompiled(name, makeMethodCaller, callerCache);
23043 getGetter = function(name) {
23044 return getCompiled(name, makeGetter, getterCache);
23048 function ensureMethod(obj, methodName) {
23050 if (obj != null) fn = obj[methodName];
23051 if (typeof fn !== "function") {
23052 var message = "Object " + util.classString(obj) + " has no method '" +
23053 util.toString(methodName) + "'";
23054 throw new Promise.TypeError(message);
23059 function caller(obj) {
23060 var methodName = this.pop();
23061 var fn = ensureMethod(obj, methodName);
23062 return fn.apply(obj, this);
23064 Promise.prototype.call = function (methodName) {
23065 var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
23068 var maybeCaller = getMethodCaller(methodName);
23069 if (maybeCaller !== null) {
23071 maybeCaller, undefined, undefined, args, undefined);
23075 args.push(methodName);
23076 return this._then(caller, undefined, undefined, args, undefined);
23079 function namedGetter(obj) {
23082 function indexedGetter(obj) {
23084 if (index < 0) index = Math.max(0, index + obj.length);
23087 Promise.prototype.get = function (propertyName) {
23088 var isIndex = (typeof propertyName === "number");
23092 var maybeGetter = getGetter(propertyName);
23093 getter = maybeGetter !== null ? maybeGetter : namedGetter;
23095 getter = namedGetter;
23098 getter = indexedGetter;
23100 return this._then(getter, undefined, undefined, propertyName, undefined);
23107 /***/ (function(module, exports, __webpack_require__) {
23111 module.exports = function (Promise, apiRejection, tryConvertToPromise,
23112 createContext, INTERNAL, debug) {
23113 var util = __webpack_require__(130);
23114 var TypeError = __webpack_require__(135).TypeError;
23115 var inherits = __webpack_require__(130).inherits;
23116 var errorObj = util.errorObj;
23117 var tryCatch = util.tryCatch;
23120 function thrower(e) {
23121 setTimeout(function(){throw e;}, 0);
23124 function castPreservingDisposable(thenable) {
23125 var maybePromise = tryConvertToPromise(thenable);
23126 if (maybePromise !== thenable &&
23127 typeof thenable._isDisposable === "function" &&
23128 typeof thenable._getDisposer === "function" &&
23129 thenable._isDisposable()) {
23130 maybePromise._setDisposable(thenable._getDisposer());
23132 return maybePromise;
23134 function dispose(resources, inspection) {
23136 var len = resources.length;
23137 var ret = new Promise(INTERNAL);
23138 function iterator() {
23139 if (i >= len) return ret._fulfill();
23140 var maybePromise = castPreservingDisposable(resources[i++]);
23141 if (maybePromise instanceof Promise &&
23142 maybePromise._isDisposable()) {
23144 maybePromise = tryConvertToPromise(
23145 maybePromise._getDisposer().tryDispose(inspection),
23146 resources.promise);
23150 if (maybePromise instanceof Promise) {
23151 return maybePromise._then(iterator, thrower,
23161 function Disposer(data, promise, context) {
23163 this._promise = promise;
23164 this._context = context;
23167 Disposer.prototype.data = function () {
23171 Disposer.prototype.promise = function () {
23172 return this._promise;
23175 Disposer.prototype.resource = function () {
23176 if (this.promise().isFulfilled()) {
23177 return this.promise().value();
23182 Disposer.prototype.tryDispose = function(inspection) {
23183 var resource = this.resource();
23184 var context = this._context;
23185 if (context !== undefined) context._pushContext();
23186 var ret = resource !== NULL
23187 ? this.doDispose(resource, inspection) : null;
23188 if (context !== undefined) context._popContext();
23189 this._promise._unsetDisposable();
23194 Disposer.isDisposer = function (d) {
23195 return (d != null &&
23196 typeof d.resource === "function" &&
23197 typeof d.tryDispose === "function");
23200 function FunctionDisposer(fn, promise, context) {
23201 this.constructor$(fn, promise, context);
23203 inherits(FunctionDisposer, Disposer);
23205 FunctionDisposer.prototype.doDispose = function (resource, inspection) {
23206 var fn = this.data();
23207 return fn.call(resource, resource, inspection);
23210 function maybeUnwrapDisposer(value) {
23211 if (Disposer.isDisposer(value)) {
23212 this.resources[this.index]._setDisposable(value);
23213 return value.promise();
23218 function ResourceList(length) {
23219 this.length = length;
23220 this.promise = null;
23221 this[length-1] = null;
23224 ResourceList.prototype._resultCancelled = function() {
23225 var len = this.length;
23226 for (var i = 0; i < len; ++i) {
23227 var item = this[i];
23228 if (item instanceof Promise) {
23234 Promise.using = function () {
23235 var len = arguments.length;
23236 if (len < 2) return apiRejection(
23237 "you must pass at least 2 arguments to Promise.using");
23238 var fn = arguments[len - 1];
23239 if (typeof fn !== "function") {
23240 return apiRejection("expecting a function but got " + util.classString(fn));
23243 var spreadArgs = true;
23244 if (len === 2 && Array.isArray(arguments[0])) {
23245 input = arguments[0];
23246 len = input.length;
23247 spreadArgs = false;
23252 var resources = new ResourceList(len);
23253 for (var i = 0; i < len; ++i) {
23254 var resource = input[i];
23255 if (Disposer.isDisposer(resource)) {
23256 var disposer = resource;
23257 resource = resource.promise();
23258 resource._setDisposable(disposer);
23260 var maybePromise = tryConvertToPromise(resource);
23261 if (maybePromise instanceof Promise) {
23263 maybePromise._then(maybeUnwrapDisposer, null, null, {
23264 resources: resources,
23269 resources[i] = resource;
23272 var reflectedResources = new Array(resources.length);
23273 for (var i = 0; i < reflectedResources.length; ++i) {
23274 reflectedResources[i] = Promise.resolve(resources[i]).reflect();
23277 var resultPromise = Promise.all(reflectedResources)
23278 .then(function(inspections) {
23279 for (var i = 0; i < inspections.length; ++i) {
23280 var inspection = inspections[i];
23281 if (inspection.isRejected()) {
23282 errorObj.e = inspection.error();
23284 } else if (!inspection.isFulfilled()) {
23285 resultPromise.cancel();
23288 inspections[i] = inspection.value();
23290 promise._pushContext();
23293 var ret = spreadArgs
23294 ? fn.apply(undefined, inspections) : fn(inspections);
23295 var promiseCreated = promise._popContext();
23296 debug.checkForgottenReturns(
23297 ret, promiseCreated, "Promise.using", promise);
23301 var promise = resultPromise.lastly(function() {
23302 var inspection = new Promise.PromiseInspection(resultPromise);
23303 return dispose(resources, inspection);
23305 resources.promise = promise;
23306 promise._setOnCancel(resources);
23310 Promise.prototype._setDisposable = function (disposer) {
23311 this._bitField = this._bitField | 131072;
23312 this._disposer = disposer;
23315 Promise.prototype._isDisposable = function () {
23316 return (this._bitField & 131072) > 0;
23319 Promise.prototype._getDisposer = function () {
23320 return this._disposer;
23323 Promise.prototype._unsetDisposable = function () {
23324 this._bitField = this._bitField & (~131072);
23325 this._disposer = undefined;
23328 Promise.prototype.disposer = function (fn) {
23329 if (typeof fn === "function") {
23330 return new FunctionDisposer(fn, this, createContext());
23332 throw new TypeError();
23340 /***/ (function(module, exports, __webpack_require__) {
23344 module.exports = function(Promise, INTERNAL, debug) {
23345 var util = __webpack_require__(130);
23346 var TimeoutError = Promise.TimeoutError;
23348 function HandleWrapper(handle) {
23349 this.handle = handle;
23352 HandleWrapper.prototype._resultCancelled = function() {
23353 clearTimeout(this.handle);
23356 var afterValue = function(value) { return delay(+this).thenReturn(value); };
23357 var delay = Promise.delay = function (ms, value) {
23360 if (value !== undefined) {
23361 ret = Promise.resolve(value)
23362 ._then(afterValue, null, null, ms, undefined);
23363 if (debug.cancellation() && value instanceof Promise) {
23364 ret._setOnCancel(value);
23367 ret = new Promise(INTERNAL);
23368 handle = setTimeout(function() { ret._fulfill(); }, +ms);
23369 if (debug.cancellation()) {
23370 ret._setOnCancel(new HandleWrapper(handle));
23372 ret._captureStackTrace();
23374 ret._setAsyncGuaranteed();
23378 Promise.prototype.delay = function (ms) {
23379 return delay(ms, this);
23382 var afterTimeout = function (promise, message, parent) {
23384 if (typeof message !== "string") {
23385 if (message instanceof Error) {
23388 err = new TimeoutError("operation timed out");
23391 err = new TimeoutError(message);
23393 util.markAsOriginatingFromRejection(err);
23394 promise._attachExtraTrace(err);
23395 promise._reject(err);
23397 if (parent != null) {
23402 function successClear(value) {
23403 clearTimeout(this.handle);
23407 function failureClear(reason) {
23408 clearTimeout(this.handle);
23412 Promise.prototype.timeout = function (ms, message) {
23416 var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
23417 if (ret.isPending()) {
23418 afterTimeout(ret, message, parent);
23422 if (debug.cancellation()) {
23423 parent = this.then();
23424 ret = parent._then(successClear, failureClear,
23425 undefined, handleWrapper, undefined);
23426 ret._setOnCancel(handleWrapper);
23428 ret = this._then(successClear, failureClear,
23429 undefined, handleWrapper, undefined);
23440 /***/ (function(module, exports, __webpack_require__) {
23444 module.exports = function(Promise,
23447 tryConvertToPromise,
23450 var errors = __webpack_require__(135);
23451 var TypeError = errors.TypeError;
23452 var util = __webpack_require__(130);
23453 var errorObj = util.errorObj;
23454 var tryCatch = util.tryCatch;
23455 var yieldHandlers = [];
23457 function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
23458 for (var i = 0; i < yieldHandlers.length; ++i) {
23459 traceParent._pushContext();
23460 var result = tryCatch(yieldHandlers[i])(value);
23461 traceParent._popContext();
23462 if (result === errorObj) {
23463 traceParent._pushContext();
23464 var ret = Promise.reject(errorObj.e);
23465 traceParent._popContext();
23468 var maybePromise = tryConvertToPromise(result, traceParent);
23469 if (maybePromise instanceof Promise) return maybePromise;
23474 function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
23475 if (debug.cancellation()) {
23476 var internal = new Promise(INTERNAL);
23477 var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
23478 this._promise = internal.lastly(function() {
23479 return _finallyPromise;
23481 internal._captureStackTrace();
23482 internal._setOnCancel(this);
23484 var promise = this._promise = new Promise(INTERNAL);
23485 promise._captureStackTrace();
23487 this._stack = stack;
23488 this._generatorFunction = generatorFunction;
23489 this._receiver = receiver;
23490 this._generator = undefined;
23491 this._yieldHandlers = typeof yieldHandler === "function"
23492 ? [yieldHandler].concat(yieldHandlers)
23494 this._yieldedPromise = null;
23495 this._cancellationPhase = false;
23497 util.inherits(PromiseSpawn, Proxyable);
23499 PromiseSpawn.prototype._isResolved = function() {
23500 return this._promise === null;
23503 PromiseSpawn.prototype._cleanup = function() {
23504 this._promise = this._generator = null;
23505 if (debug.cancellation() && this._finallyPromise !== null) {
23506 this._finallyPromise._fulfill();
23507 this._finallyPromise = null;
23511 PromiseSpawn.prototype._promiseCancelled = function() {
23512 if (this._isResolved()) return;
23513 var implementsReturn = typeof this._generator["return"] !== "undefined";
23516 if (!implementsReturn) {
23517 var reason = new Promise.CancellationError(
23518 "generator .return() sentinel");
23519 Promise.coroutine.returnSentinel = reason;
23520 this._promise._attachExtraTrace(reason);
23521 this._promise._pushContext();
23522 result = tryCatch(this._generator["throw"]).call(this._generator,
23524 this._promise._popContext();
23526 this._promise._pushContext();
23527 result = tryCatch(this._generator["return"]).call(this._generator,
23529 this._promise._popContext();
23531 this._cancellationPhase = true;
23532 this._yieldedPromise = null;
23533 this._continue(result);
23536 PromiseSpawn.prototype._promiseFulfilled = function(value) {
23537 this._yieldedPromise = null;
23538 this._promise._pushContext();
23539 var result = tryCatch(this._generator.next).call(this._generator, value);
23540 this._promise._popContext();
23541 this._continue(result);
23544 PromiseSpawn.prototype._promiseRejected = function(reason) {
23545 this._yieldedPromise = null;
23546 this._promise._attachExtraTrace(reason);
23547 this._promise._pushContext();
23548 var result = tryCatch(this._generator["throw"])
23549 .call(this._generator, reason);
23550 this._promise._popContext();
23551 this._continue(result);
23554 PromiseSpawn.prototype._resultCancelled = function() {
23555 if (this._yieldedPromise instanceof Promise) {
23556 var promise = this._yieldedPromise;
23557 this._yieldedPromise = null;
23562 PromiseSpawn.prototype.promise = function () {
23563 return this._promise;
23566 PromiseSpawn.prototype._run = function () {
23567 this._generator = this._generatorFunction.call(this._receiver);
23569 this._generatorFunction = undefined;
23570 this._promiseFulfilled(undefined);
23573 PromiseSpawn.prototype._continue = function (result) {
23574 var promise = this._promise;
23575 if (result === errorObj) {
23577 if (this._cancellationPhase) {
23578 return promise.cancel();
23580 return promise._rejectCallback(result.e, false);
23584 var value = result.value;
23585 if (result.done === true) {
23587 if (this._cancellationPhase) {
23588 return promise.cancel();
23590 return promise._resolveCallback(value);
23593 var maybePromise = tryConvertToPromise(value, this._promise);
23594 if (!(maybePromise instanceof Promise)) {
23596 promiseFromYieldHandler(maybePromise,
23597 this._yieldHandlers,
23599 if (maybePromise === null) {
23600 this._promiseRejected(
23602 "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
23603 "From coroutine:\u000a" +
23604 this._stack.split("\n").slice(1, -7).join("\n")
23610 maybePromise = maybePromise._target();
23611 var bitField = maybePromise._bitField;
23613 if (((bitField & 50397184) === 0)) {
23614 this._yieldedPromise = maybePromise;
23615 maybePromise._proxy(this, null);
23616 } else if (((bitField & 33554432) !== 0)) {
23617 Promise._async.invoke(
23618 this._promiseFulfilled, this, maybePromise._value()
23620 } else if (((bitField & 16777216) !== 0)) {
23621 Promise._async.invoke(
23622 this._promiseRejected, this, maybePromise._reason()
23625 this._promiseCancelled();
23630 Promise.coroutine = function (generatorFunction, options) {
23631 if (typeof generatorFunction !== "function") {
23632 throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
23634 var yieldHandler = Object(options).yieldHandler;
23635 var PromiseSpawn$ = PromiseSpawn;
23636 var stack = new Error().stack;
23637 return function () {
23638 var generator = generatorFunction.apply(this, arguments);
23639 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
23641 var ret = spawn.promise();
23642 spawn._generator = generator;
23643 spawn._promiseFulfilled(undefined);
23648 Promise.coroutine.addYieldHandler = function(fn) {
23649 if (typeof fn !== "function") {
23650 throw new TypeError("expecting a function but got " + util.classString(fn));
23652 yieldHandlers.push(fn);
23655 Promise.spawn = function (generatorFunction) {
23656 debug.deprecated("Promise.spawn()", "Promise.coroutine()");
23657 if (typeof generatorFunction !== "function") {
23658 return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
23660 var spawn = new PromiseSpawn(generatorFunction, this);
23661 var ret = spawn.promise();
23662 spawn._run(Promise.spawn);
23670 /***/ (function(module, exports, __webpack_require__) {
23674 module.exports = function(Promise) {
23675 var util = __webpack_require__(130);
23676 var async = Promise._async;
23677 var tryCatch = util.tryCatch;
23678 var errorObj = util.errorObj;
23680 function spreadAdapter(val, nodeback) {
23681 var promise = this;
23682 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
23684 tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
23685 if (ret === errorObj) {
23686 async.throwLater(ret.e);
23690 function successAdapter(val, nodeback) {
23691 var promise = this;
23692 var receiver = promise._boundValue();
23693 var ret = val === undefined
23694 ? tryCatch(nodeback).call(receiver, null)
23695 : tryCatch(nodeback).call(receiver, null, val);
23696 if (ret === errorObj) {
23697 async.throwLater(ret.e);
23700 function errorAdapter(reason, nodeback) {
23701 var promise = this;
23703 var newReason = new Error(reason + "");
23704 newReason.cause = reason;
23705 reason = newReason;
23707 var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
23708 if (ret === errorObj) {
23709 async.throwLater(ret.e);
23713 Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
23715 if (typeof nodeback == "function") {
23716 var adapter = successAdapter;
23717 if (options !== undefined && Object(options).spread) {
23718 adapter = spreadAdapter;
23735 /***/ (function(module, exports, __webpack_require__) {
23739 module.exports = function(Promise, INTERNAL) {
23741 var util = __webpack_require__(130);
23742 var nodebackForPromise = __webpack_require__(142);
23743 var withAppended = util.withAppended;
23744 var maybeWrapAsError = util.maybeWrapAsError;
23745 var canEvaluate = util.canEvaluate;
23746 var TypeError = __webpack_require__(135).TypeError;
23747 var defaultSuffix = "Async";
23748 var defaultPromisified = {__isPromisified__: true};
23749 var noCopyProps = [
23756 "__isPromisified__"
23758 var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
23760 var defaultFilter = function(name) {
23761 return util.isIdentifier(name) &&
23762 name.charAt(0) !== "_" &&
23763 name !== "constructor";
23766 function propsFilter(key) {
23767 return !noCopyPropsPattern.test(key);
23770 function isPromisified(fn) {
23772 return fn.__isPromisified__ === true;
23779 function hasPromisified(obj, key, suffix) {
23780 var val = util.getDataPropertyOrDefault(obj, key + suffix,
23781 defaultPromisified);
23782 return val ? isPromisified(val) : false;
23784 function checkValid(ret, suffix, suffixRegexp) {
23785 for (var i = 0; i < ret.length; i += 2) {
23787 if (suffixRegexp.test(key)) {
23788 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
23789 for (var j = 0; j < ret.length; j += 2) {
23790 if (ret[j] === keyWithoutAsyncSuffix) {
23791 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
23792 .replace("%s", suffix));
23799 function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
23800 var keys = util.inheritedDataKeys(obj);
23802 for (var i = 0; i < keys.length; ++i) {
23804 var value = obj[key];
23805 var passesDefaultFilter = filter === defaultFilter
23806 ? true : defaultFilter(key, value, obj);
23807 if (typeof value === "function" &&
23808 !isPromisified(value) &&
23809 !hasPromisified(obj, key, suffix) &&
23810 filter(key, value, obj, passesDefaultFilter)) {
23811 ret.push(key, value);
23814 checkValid(ret, suffix, suffixRegexp);
23818 var escapeIdentRegex = function(str) {
23819 return str.replace(/([$])/, "\\$");
23822 var makeNodePromisifiedEval;
23824 var switchCaseArgumentOrder = function(likelyArgumentCount) {
23825 var ret = [likelyArgumentCount];
23826 var min = Math.max(0, likelyArgumentCount - 1 - 3);
23827 for(var i = likelyArgumentCount - 1; i >= min; --i) {
23830 for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
23836 var argumentSequence = function(argumentCount) {
23837 return util.filledRange(argumentCount, "_arg", "");
23840 var parameterDeclaration = function(parameterCount) {
23841 return util.filledRange(
23842 Math.max(parameterCount, 3), "_arg", "");
23845 var parameterCount = function(fn) {
23846 if (typeof fn.length === "number") {
23847 return Math.max(Math.min(fn.length, 1023 + 1), 0);
23852 makeNodePromisifiedEval =
23853 function(callback, receiver, originalName, fn, _, multiArgs) {
23854 var newParameterCount = Math.max(0, parameterCount(fn) - 1);
23855 var argumentOrder = switchCaseArgumentOrder(newParameterCount);
23856 var shouldProxyThis = typeof callback === "string" || receiver === THIS;
23858 function generateCallForArgumentCount(count) {
23859 var args = argumentSequence(count).join(", ");
23860 var comma = count > 0 ? ", " : "";
23862 if (shouldProxyThis) {
23863 ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
23865 ret = receiver === undefined
23866 ? "ret = callback({{args}}, nodeback); break;\n"
23867 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
23869 return ret.replace("{{args}}", args).replace(", ", comma);
23872 function generateArgumentSwitchCase() {
23874 for (var i = 0; i < argumentOrder.length; ++i) {
23875 ret += "case " + argumentOrder[i] +":" +
23876 generateCallForArgumentCount(argumentOrder[i]);
23881 var args = new Array(len + 1); \n\
23883 for (var i = 0; i < len; ++i) { \n\
23884 args[i] = arguments[i]; \n\
23886 args[i] = nodeback; \n\
23889 ".replace("[CodeForCall]", (shouldProxyThis
23890 ? "ret = callback.apply(this, args);\n"
23891 : "ret = callback.apply(receiver, args);\n"));
23895 var getFunctionCode = typeof callback === "string"
23896 ? ("this != null ? this['"+callback+"'] : fn")
23898 var body = "'use strict'; \n\
23899 var ret = function (Parameters) { \n\
23901 var len = arguments.length; \n\
23902 var promise = new Promise(INTERNAL); \n\
23903 promise._captureStackTrace(); \n\
23904 var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
23906 var callback = tryCatch([GetFunctionCode]); \n\
23908 [CodeForSwitchCase] \n\
23910 if (ret === errorObj) { \n\
23911 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
23913 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
23914 return promise; \n\
23916 notEnumerableProp(ret, '__isPromisified__', true); \n\
23918 ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
23919 .replace("[GetFunctionCode]", getFunctionCode);
23920 body = body.replace("Parameters", parameterDeclaration(newParameterCount));
23921 return new Function("Promise",
23925 "maybeWrapAsError",
23926 "nodebackForPromise",
23929 "notEnumerableProp",
23937 nodebackForPromise,
23940 util.notEnumerableProp,
23945 function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
23946 var defaultThis = (function() {return this;})();
23947 var method = callback;
23948 if (typeof method === "string") {
23951 function promisified() {
23952 var _receiver = receiver;
23953 if (receiver === THIS) _receiver = this;
23954 var promise = new Promise(INTERNAL);
23955 promise._captureStackTrace();
23956 var cb = typeof method === "string" && this !== defaultThis
23957 ? this[method] : callback;
23958 var fn = nodebackForPromise(promise, multiArgs);
23960 cb.apply(_receiver, withAppended(arguments, fn));
23962 promise._rejectCallback(maybeWrapAsError(e), true, true);
23964 if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
23967 util.notEnumerableProp(promisified, "__isPromisified__", true);
23968 return promisified;
23971 var makeNodePromisified = canEvaluate
23972 ? makeNodePromisifiedEval
23973 : makeNodePromisifiedClosure;
23975 function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
23976 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
23978 promisifiableMethods(obj, suffix, suffixRegexp, filter);
23980 for (var i = 0, len = methods.length; i < len; i+= 2) {
23981 var key = methods[i];
23982 var fn = methods[i+1];
23983 var promisifiedKey = key + suffix;
23984 if (promisifier === makeNodePromisified) {
23985 obj[promisifiedKey] =
23986 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
23988 var promisified = promisifier(fn, function() {
23989 return makeNodePromisified(key, THIS, key,
23990 fn, suffix, multiArgs);
23992 util.notEnumerableProp(promisified, "__isPromisified__", true);
23993 obj[promisifiedKey] = promisified;
23996 util.toFastProperties(obj);
24000 function promisify(callback, receiver, multiArgs) {
24001 return makeNodePromisified(callback, receiver, undefined,
24002 callback, null, multiArgs);
24005 Promise.promisify = function (fn, options) {
24006 if (typeof fn !== "function") {
24007 throw new TypeError("expecting a function but got " + util.classString(fn));
24009 if (isPromisified(fn)) {
24012 options = Object(options);
24013 var receiver = options.context === undefined ? THIS : options.context;
24014 var multiArgs = !!options.multiArgs;
24015 var ret = promisify(fn, receiver, multiArgs);
24016 util.copyDescriptors(fn, ret, propsFilter);
24020 Promise.promisifyAll = function (target, options) {
24021 if (typeof target !== "function" && typeof target !== "object") {
24022 throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
24024 options = Object(options);
24025 var multiArgs = !!options.multiArgs;
24026 var suffix = options.suffix;
24027 if (typeof suffix !== "string") suffix = defaultSuffix;
24028 var filter = options.filter;
24029 if (typeof filter !== "function") filter = defaultFilter;
24030 var promisifier = options.promisifier;
24031 if (typeof promisifier !== "function") promisifier = makeNodePromisified;
24033 if (!util.isIdentifier(suffix)) {
24034 throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
24037 var keys = util.inheritedDataKeys(target);
24038 for (var i = 0; i < keys.length; ++i) {
24039 var value = target[keys[i]];
24040 if (keys[i] !== "constructor" &&
24041 util.isClass(value)) {
24042 promisifyAll(value.prototype, suffix, filter, promisifier,
24044 promisifyAll(value, suffix, filter, promisifier, multiArgs);
24048 return promisifyAll(target, suffix, filter, promisifier, multiArgs);
24056 /***/ (function(module, exports, __webpack_require__) {
24060 module.exports = function(
24061 Promise, PromiseArray, tryConvertToPromise, apiRejection) {
24062 var util = __webpack_require__(130);
24063 var isObject = util.isObject;
24064 var es5 = __webpack_require__(131);
24066 if (typeof Map === "function") Es6Map = Map;
24068 var mapToEntries = (function() {
24072 function extractEntry(value, key) {
24073 this[index] = value;
24074 this[index + size] = key;
24078 return function mapToEntries(map) {
24081 var ret = new Array(map.size * 2);
24082 map.forEach(extractEntry, ret);
24087 var entriesToMap = function(entries) {
24088 var ret = new Es6Map();
24089 var length = entries.length / 2 | 0;
24090 for (var i = 0; i < length; ++i) {
24091 var key = entries[length + i];
24092 var value = entries[i];
24093 ret.set(key, value);
24098 function PropertiesPromiseArray(obj) {
24101 if (Es6Map !== undefined && obj instanceof Es6Map) {
24102 entries = mapToEntries(obj);
24105 var keys = es5.keys(obj);
24106 var len = keys.length;
24107 entries = new Array(len * 2);
24108 for (var i = 0; i < len; ++i) {
24110 entries[i] = obj[key];
24111 entries[i + len] = key;
24114 this.constructor$(entries);
24115 this._isMap = isMap;
24116 this._init$(undefined, -3);
24118 util.inherits(PropertiesPromiseArray, PromiseArray);
24120 PropertiesPromiseArray.prototype._init = function () {};
24122 PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
24123 this._values[index] = value;
24124 var totalResolved = ++this._totalResolved;
24125 if (totalResolved >= this._length) {
24128 val = entriesToMap(this._values);
24131 var keyOffset = this.length();
24132 for (var i = 0, len = this.length(); i < len; ++i) {
24133 val[this._values[i + keyOffset]] = this._values[i];
24136 this._resolve(val);
24142 PropertiesPromiseArray.prototype.shouldCopyValues = function () {
24146 PropertiesPromiseArray.prototype.getActualLength = function (len) {
24150 function props(promises) {
24152 var castValue = tryConvertToPromise(promises);
24154 if (!isObject(castValue)) {
24155 return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
24156 } else if (castValue instanceof Promise) {
24157 ret = castValue._then(
24158 Promise.props, undefined, undefined, undefined, undefined);
24160 ret = new PropertiesPromiseArray(castValue).promise();
24163 if (castValue instanceof Promise) {
24164 ret._propagateFrom(castValue, 2);
24169 Promise.prototype.props = function () {
24170 return props(this);
24173 Promise.props = function (promises) {
24174 return props(promises);
24181 /***/ (function(module, exports, __webpack_require__) {
24185 module.exports = function(
24186 Promise, INTERNAL, tryConvertToPromise, apiRejection) {
24187 var util = __webpack_require__(130);
24189 var raceLater = function (promise) {
24190 return promise.then(function(array) {
24191 return race(array, promise);
24195 function race(promises, parent) {
24196 var maybePromise = tryConvertToPromise(promises);
24198 if (maybePromise instanceof Promise) {
24199 return raceLater(maybePromise);
24201 promises = util.asArray(promises);
24202 if (promises === null)
24203 return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
24206 var ret = new Promise(INTERNAL);
24207 if (parent !== undefined) {
24208 ret._propagateFrom(parent, 3);
24210 var fulfill = ret._fulfill;
24211 var reject = ret._reject;
24212 for (var i = 0, len = promises.length; i < len; ++i) {
24213 var val = promises[i];
24215 if (val === undefined && !(i in promises)) {
24219 Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
24224 Promise.race = function (promises) {
24225 return race(promises, undefined);
24228 Promise.prototype.race = function () {
24229 return race(this, undefined);
24237 /***/ (function(module, exports, __webpack_require__) {
24241 module.exports = function(Promise,
24244 tryConvertToPromise,
24247 var getDomain = Promise._getDomain;
24248 var util = __webpack_require__(130);
24249 var tryCatch = util.tryCatch;
24251 function ReductionPromiseArray(promises, fn, initialValue, _each) {
24252 this.constructor$(promises);
24253 var domain = getDomain();
24254 this._fn = domain === null ? fn : util.domainBind(domain, fn);
24255 if (initialValue !== undefined) {
24256 initialValue = Promise.resolve(initialValue);
24257 initialValue._attachCancellationCallback(this);
24259 this._initialValue = initialValue;
24260 this._currentCancellable = null;
24261 if(_each === INTERNAL) {
24262 this._eachValues = Array(this._length);
24263 } else if (_each === 0) {
24264 this._eachValues = null;
24266 this._eachValues = undefined;
24268 this._promise._captureStackTrace();
24269 this._init$(undefined, -5);
24271 util.inherits(ReductionPromiseArray, PromiseArray);
24273 ReductionPromiseArray.prototype._gotAccum = function(accum) {
24274 if (this._eachValues !== undefined &&
24275 this._eachValues !== null &&
24276 accum !== INTERNAL) {
24277 this._eachValues.push(accum);
24281 ReductionPromiseArray.prototype._eachComplete = function(value) {
24282 if (this._eachValues !== null) {
24283 this._eachValues.push(value);
24285 return this._eachValues;
24288 ReductionPromiseArray.prototype._init = function() {};
24290 ReductionPromiseArray.prototype._resolveEmptyArray = function() {
24291 this._resolve(this._eachValues !== undefined ? this._eachValues
24292 : this._initialValue);
24295 ReductionPromiseArray.prototype.shouldCopyValues = function () {
24299 ReductionPromiseArray.prototype._resolve = function(value) {
24300 this._promise._resolveCallback(value);
24301 this._values = null;
24304 ReductionPromiseArray.prototype._resultCancelled = function(sender) {
24305 if (sender === this._initialValue) return this._cancel();
24306 if (this._isResolved()) return;
24307 this._resultCancelled$();
24308 if (this._currentCancellable instanceof Promise) {
24309 this._currentCancellable.cancel();
24311 if (this._initialValue instanceof Promise) {
24312 this._initialValue.cancel();
24316 ReductionPromiseArray.prototype._iterate = function (values) {
24317 this._values = values;
24320 var length = values.length;
24321 if (this._initialValue !== undefined) {
24322 value = this._initialValue;
24325 value = Promise.resolve(values[0]);
24329 this._currentCancellable = value;
24331 if (!value.isRejected()) {
24332 for (; i < length; ++i) {
24340 value = value._then(gotAccum, undefined, undefined, ctx, undefined);
24344 if (this._eachValues !== undefined) {
24346 ._then(this._eachComplete, undefined, undefined, this, undefined);
24348 value._then(completed, completed, undefined, value, this);
24351 Promise.prototype.reduce = function (fn, initialValue) {
24352 return reduce(this, fn, initialValue, null);
24355 Promise.reduce = function (promises, fn, initialValue, _each) {
24356 return reduce(promises, fn, initialValue, _each);
24359 function completed(valueOrReason, array) {
24360 if (this.isFulfilled()) {
24361 array._resolve(valueOrReason);
24363 array._reject(valueOrReason);
24367 function reduce(promises, fn, initialValue, _each) {
24368 if (typeof fn !== "function") {
24369 return apiRejection("expecting a function but got " + util.classString(fn));
24371 var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
24372 return array.promise();
24375 function gotAccum(accum) {
24376 this.accum = accum;
24377 this.array._gotAccum(accum);
24378 var value = tryConvertToPromise(this.value, this.array._promise);
24379 if (value instanceof Promise) {
24380 this.array._currentCancellable = value;
24381 return value._then(gotValue, undefined, undefined, this, undefined);
24383 return gotValue.call(this, value);
24387 function gotValue(value) {
24388 var array = this.array;
24389 var promise = array._promise;
24390 var fn = tryCatch(array._fn);
24391 promise._pushContext();
24393 if (array._eachValues !== undefined) {
24394 ret = fn.call(promise._boundValue(), value, this.index, this.length);
24396 ret = fn.call(promise._boundValue(),
24397 this.accum, value, this.index, this.length);
24399 if (ret instanceof Promise) {
24400 array._currentCancellable = ret;
24402 var promiseCreated = promise._popContext();
24403 debug.checkForgottenReturns(
24406 array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
24416 /***/ (function(module, exports, __webpack_require__) {
24421 function(Promise, PromiseArray, debug) {
24422 var PromiseInspection = Promise.PromiseInspection;
24423 var util = __webpack_require__(130);
24425 function SettledPromiseArray(values) {
24426 this.constructor$(values);
24428 util.inherits(SettledPromiseArray, PromiseArray);
24430 SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
24431 this._values[index] = inspection;
24432 var totalResolved = ++this._totalResolved;
24433 if (totalResolved >= this._length) {
24434 this._resolve(this._values);
24440 SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
24441 var ret = new PromiseInspection();
24442 ret._bitField = 33554432;
24443 ret._settledValueField = value;
24444 return this._promiseResolved(index, ret);
24446 SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
24447 var ret = new PromiseInspection();
24448 ret._bitField = 16777216;
24449 ret._settledValueField = reason;
24450 return this._promiseResolved(index, ret);
24453 Promise.settle = function (promises) {
24454 debug.deprecated(".settle()", ".reflect()");
24455 return new SettledPromiseArray(promises).promise();
24458 Promise.prototype.settle = function () {
24459 return Promise.settle(this);
24466 /***/ (function(module, exports, __webpack_require__) {
24471 function(Promise, PromiseArray, apiRejection) {
24472 var util = __webpack_require__(130);
24473 var RangeError = __webpack_require__(135).RangeError;
24474 var AggregateError = __webpack_require__(135).AggregateError;
24475 var isArray = util.isArray;
24476 var CANCELLATION = {};
24479 function SomePromiseArray(values) {
24480 this.constructor$(values);
24482 this._unwrap = false;
24483 this._initialized = false;
24485 util.inherits(SomePromiseArray, PromiseArray);
24487 SomePromiseArray.prototype._init = function () {
24488 if (!this._initialized) {
24491 if (this._howMany === 0) {
24495 this._init$(undefined, -5);
24496 var isArrayResolved = isArray(this._values);
24497 if (!this._isResolved() &&
24499 this._howMany > this._canPossiblyFulfill()) {
24500 this._reject(this._getRangeError(this.length()));
24504 SomePromiseArray.prototype.init = function () {
24505 this._initialized = true;
24509 SomePromiseArray.prototype.setUnwrap = function () {
24510 this._unwrap = true;
24513 SomePromiseArray.prototype.howMany = function () {
24514 return this._howMany;
24517 SomePromiseArray.prototype.setHowMany = function (count) {
24518 this._howMany = count;
24521 SomePromiseArray.prototype._promiseFulfilled = function (value) {
24522 this._addFulfilled(value);
24523 if (this._fulfilled() === this.howMany()) {
24524 this._values.length = this.howMany();
24525 if (this.howMany() === 1 && this._unwrap) {
24526 this._resolve(this._values[0]);
24528 this._resolve(this._values);
24535 SomePromiseArray.prototype._promiseRejected = function (reason) {
24536 this._addRejected(reason);
24537 return this._checkOutcome();
24540 SomePromiseArray.prototype._promiseCancelled = function () {
24541 if (this._values instanceof Promise || this._values == null) {
24542 return this._cancel();
24544 this._addRejected(CANCELLATION);
24545 return this._checkOutcome();
24548 SomePromiseArray.prototype._checkOutcome = function() {
24549 if (this.howMany() > this._canPossiblyFulfill()) {
24550 var e = new AggregateError();
24551 for (var i = this.length(); i < this._values.length; ++i) {
24552 if (this._values[i] !== CANCELLATION) {
24553 e.push(this._values[i]);
24556 if (e.length > 0) {
24566 SomePromiseArray.prototype._fulfilled = function () {
24567 return this._totalResolved;
24570 SomePromiseArray.prototype._rejected = function () {
24571 return this._values.length - this.length();
24574 SomePromiseArray.prototype._addRejected = function (reason) {
24575 this._values.push(reason);
24578 SomePromiseArray.prototype._addFulfilled = function (value) {
24579 this._values[this._totalResolved++] = value;
24582 SomePromiseArray.prototype._canPossiblyFulfill = function () {
24583 return this.length() - this._rejected();
24586 SomePromiseArray.prototype._getRangeError = function (count) {
24587 var message = "Input array must contain at least " +
24588 this._howMany + " items but contains only " + count + " items";
24589 return new RangeError(message);
24592 SomePromiseArray.prototype._resolveEmptyArray = function () {
24593 this._reject(this._getRangeError(0));
24596 function some(promises, howMany) {
24597 if ((howMany | 0) !== howMany || howMany < 0) {
24598 return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
24600 var ret = new SomePromiseArray(promises);
24601 var promise = ret.promise();
24602 ret.setHowMany(howMany);
24607 Promise.some = function (promises, howMany) {
24608 return some(promises, howMany);
24611 Promise.prototype.some = function (howMany) {
24612 return some(this, howMany);
24615 Promise._SomePromiseArray = SomePromiseArray;
24621 /***/ (function(module, exports, __webpack_require__) {
24625 module.exports = function(Promise, INTERNAL) {
24626 var PromiseMap = Promise.map;
24628 Promise.prototype.filter = function (fn, options) {
24629 return PromiseMap(this, fn, options, INTERNAL);
24632 Promise.filter = function (promises, fn, options) {
24633 return PromiseMap(promises, fn, options, INTERNAL);
24640 /***/ (function(module, exports, __webpack_require__) {
24644 module.exports = function(Promise, INTERNAL) {
24645 var PromiseReduce = Promise.reduce;
24646 var PromiseAll = Promise.all;
24648 function promiseAllThis() {
24649 return PromiseAll(this);
24652 function PromiseMapSeries(promises, fn) {
24653 return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
24656 Promise.prototype.each = function (fn) {
24657 return PromiseReduce(this, fn, INTERNAL, 0)
24658 ._then(promiseAllThis, undefined, undefined, this, undefined);
24661 Promise.prototype.mapSeries = function (fn) {
24662 return PromiseReduce(this, fn, INTERNAL, INTERNAL);
24665 Promise.each = function (promises, fn) {
24666 return PromiseReduce(promises, fn, INTERNAL, 0)
24667 ._then(promiseAllThis, undefined, undefined, promises, undefined);
24670 Promise.mapSeries = PromiseMapSeries;
24677 /***/ (function(module, exports, __webpack_require__) {
24681 module.exports = function(Promise) {
24682 var SomePromiseArray = Promise._SomePromiseArray;
24683 function any(promises) {
24684 var ret = new SomePromiseArray(promises);
24685 var promise = ret.promise();
24692 Promise.any = function (promises) {
24693 return any(promises);
24696 Promise.prototype.any = function () {
24705 /***/ (function(module, exports, __webpack_require__) {
24707 var Stream = __webpack_require__(44);
24708 var Promise = __webpack_require__(128);
24709 var util = __webpack_require__(50);
24710 var Buffer = __webpack_require__(165);
24711 var strFunction = 'function';
24713 // Backwards compatibility for node versions < 8
24714 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
24715 Stream = __webpack_require__(167);
24717 function PullStream() {
24718 if (!(this instanceof PullStream))
24719 return new PullStream();
24721 Stream.Duplex.call(this,{decodeStrings:false, objectMode:true});
24722 this.buffer = Buffer.from('');
24724 self.on('finish',function() {
24725 self.finished = true;
24726 self.emit('chunk',false);
24730 util.inherits(PullStream,Stream.Duplex);
24732 PullStream.prototype._write = function(chunk,e,cb) {
24733 this.buffer = Buffer.concat([this.buffer,chunk]);
24735 this.emit('chunk');
24739 // The `eof` parameter is interpreted as `file_length` if the type is number
24740 // otherwise (i.e. buffer) it is interpreted as a pattern signaling end of stream
24741 PullStream.prototype.stream = function(eof,includeEof) {
24742 var p = Stream.PassThrough();
24743 var done,self= this;
24746 if (typeof self.cb === strFunction) {
24747 var callback = self.cb;
24748 self.cb = undefined;
24755 if (self.buffer && self.buffer.length) {
24756 if (typeof eof === 'number') {
24757 packet = self.buffer.slice(0,eof);
24758 self.buffer = self.buffer.slice(eof);
24759 eof -= packet.length;
24762 var match = self.buffer.indexOf(eof);
24763 if (match !== -1) {
24764 // store signature match byte offset to allow us to reference
24765 // this for zip64 offset
24767 if (includeEof) match = match + eof.length;
24768 packet = self.buffer.slice(0,match);
24769 self.buffer = self.buffer.slice(match);
24772 var len = self.buffer.length - eof.length;
24776 packet = self.buffer.slice(0,len);
24777 self.buffer = self.buffer.slice(len);
24781 if (packet) p.write(packet,function() {
24782 if (self.buffer.length === 0 || (eof.length && self.buffer.length <= eof.length)) cb();
24787 if (self.finished && !this.__ended) {
24788 self.removeListener('chunk',pull);
24789 self.emit('error', new Error('FILE_ENDED'));
24790 this.__ended = true;
24795 self.removeListener('chunk',pull);
24800 self.on('chunk',pull);
24805 PullStream.prototype.pull = function(eof,includeEof) {
24806 if (eof === 0) return Promise.resolve('');
24808 // If we already have the required data in buffer
24809 // we can resolve the request immediately
24810 if (!isNaN(eof) && this.buffer.length > eof) {
24811 var data = this.buffer.slice(0,eof);
24812 this.buffer = this.buffer.slice(eof);
24813 return Promise.resolve(data);
24816 // Otherwise we stream until we have it
24817 var buffer = Buffer.from(''),
24820 var concatStream = Stream.Transform();
24821 concatStream._transform = function(d,e,cb) {
24822 buffer = Buffer.concat([buffer,d]);
24827 var pullStreamRejectHandler;
24828 return new Promise(function(resolve,reject) {
24829 rejectHandler = reject;
24830 pullStreamRejectHandler = function(e) {
24831 self.__emittedError = e;
24835 return reject(new Error('FILE_ENDED'));
24836 self.once('error',pullStreamRejectHandler); // reject any errors from pullstream itself
24837 self.stream(eof,includeEof)
24838 .on('error',reject)
24839 .pipe(concatStream)
24840 .on('finish',function() {resolve(buffer);})
24841 .on('error',reject);
24843 .finally(function() {
24844 self.removeListener('error',rejectHandler);
24845 self.removeListener('error',pullStreamRejectHandler);
24849 PullStream.prototype._read = function(){};
24851 module.exports = PullStream;
24856 /***/ (function(module, exports, __webpack_require__) {
24858 var Buffer = __webpack_require__(166).Buffer;
24860 // Backwards compatibility for node versions < 8
24861 if (Buffer.from === undefined) {
24862 Buffer.from = function (a, b, c) {
24863 return new Buffer(a, b, c)
24866 Buffer.alloc = Buffer.from;
24869 module.exports = Buffer;
24873 /***/ (function(module, exports) {
24875 module.exports = require("buffer");
24879 /***/ (function(module, exports, __webpack_require__) {
24881 var Stream = __webpack_require__(44);
24882 if (process.env.READABLE_STREAM === 'disable' && Stream) {
24883 module.exports = Stream;
24884 exports = module.exports = Stream.Readable;
24885 exports.Readable = Stream.Readable;
24886 exports.Writable = Stream.Writable;
24887 exports.Duplex = Stream.Duplex;
24888 exports.Transform = Stream.Transform;
24889 exports.PassThrough = Stream.PassThrough;
24890 exports.Stream = Stream;
24892 exports = module.exports = __webpack_require__(168);
24893 exports.Stream = Stream || exports;
24894 exports.Readable = exports;
24895 exports.Writable = __webpack_require__(177);
24896 exports.Duplex = __webpack_require__(176);
24897 exports.Transform = __webpack_require__(180);
24898 exports.PassThrough = __webpack_require__(181);
24904 /***/ (function(module, exports, __webpack_require__) {
24907 // Copyright Joyent, Inc. and other Node contributors.
24909 // Permission is hereby granted, free of charge, to any person obtaining a
24910 // copy of this software and associated documentation files (the
24911 // "Software"), to deal in the Software without restriction, including
24912 // without limitation the rights to use, copy, modify, merge, publish,
24913 // distribute, sublicense, and/or sell copies of the Software, and to permit
24914 // persons to whom the Software is furnished to do so, subject to the
24915 // following conditions:
24917 // The above copyright notice and this permission notice shall be included
24918 // in all copies or substantial portions of the Software.
24920 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24921 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24922 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
24923 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
24924 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24925 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24926 // USE OR OTHER DEALINGS IN THE SOFTWARE.
24932 var pna = __webpack_require__(169);
24935 module.exports = Readable;
24938 var isArray = __webpack_require__(170);
24945 Readable.ReadableState = ReadableState;
24948 var EE = __webpack_require__(68).EventEmitter;
24950 var EElistenerCount = function (emitter, type) {
24951 return emitter.listeners(type).length;
24956 var Stream = __webpack_require__(171);
24961 var Buffer = __webpack_require__(172).Buffer;
24962 var OurUint8Array = global.Uint8Array || function () {};
24963 function _uint8ArrayToBuffer(chunk) {
24964 return Buffer.from(chunk);
24966 function _isUint8Array(obj) {
24967 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
24973 var util = Object.create(__webpack_require__(173));
24974 util.inherits = __webpack_require__(66);
24978 var debugUtil = __webpack_require__(50);
24979 var debug = void 0;
24980 if (debugUtil && debugUtil.debuglog) {
24981 debug = debugUtil.debuglog('stream');
24983 debug = function () {};
24987 var BufferList = __webpack_require__(174);
24988 var destroyImpl = __webpack_require__(175);
24991 util.inherits(Readable, Stream);
24993 var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
24995 function prependListener(emitter, event, fn) {
24996 // Sadly this is not cacheable as some libraries bundle their own
24997 // event emitter implementation with them.
24998 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
25000 // This is a hack to make sure that our error handler is attached before any
25001 // userland ones. NEVER DO THIS. This is here only because this code needs
25002 // to continue to work with older versions of Node.js that do not include
25003 // the prependListener() method. The goal is to eventually remove this hack.
25004 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
25007 function ReadableState(options, stream) {
25008 Duplex = Duplex || __webpack_require__(176);
25010 options = options || {};
25012 // Duplex streams are both readable and writable, but share
25013 // the same options object.
25014 // However, some cases require setting options to different
25015 // values for the readable and the writable sides of the duplex stream.
25016 // These options can be provided separately as readableXXX and writableXXX.
25017 var isDuplex = stream instanceof Duplex;
25019 // object stream flag. Used to make read(n) ignore n and to
25020 // make all the buffer merging and length checks go away
25021 this.objectMode = !!options.objectMode;
25023 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
25025 // the point at which it stops calling _read() to fill the buffer
25026 // Note: 0 is a valid value, means "don't call _read preemptively ever"
25027 var hwm = options.highWaterMark;
25028 var readableHwm = options.readableHighWaterMark;
25029 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
25031 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
25034 this.highWaterMark = Math.floor(this.highWaterMark);
25036 // A linked list is used to store data chunks instead of an array because the
25037 // linked list can remove elements from the beginning faster than
25039 this.buffer = new BufferList();
25042 this.pipesCount = 0;
25043 this.flowing = null;
25044 this.ended = false;
25045 this.endEmitted = false;
25046 this.reading = false;
25048 // a flag to be able to tell if the event 'readable'/'data' is emitted
25049 // immediately, or on a later tick. We set this to true at first, because
25050 // any actions that shouldn't happen until "later" should generally also
25051 // not happen before the first read call.
25054 // whenever we return null, then we set a flag to say
25055 // that we're awaiting a 'readable' event emission.
25056 this.needReadable = false;
25057 this.emittedReadable = false;
25058 this.readableListening = false;
25059 this.resumeScheduled = false;
25061 // has it been destroyed
25062 this.destroyed = false;
25064 // Crypto is kind of old and crusty. Historically, its default string
25065 // encoding is 'binary' so we have to make this configurable.
25066 // Everything else in the universe uses 'utf8', though.
25067 this.defaultEncoding = options.defaultEncoding || 'utf8';
25069 // the number of writers that are awaiting a drain event in .pipe()s
25070 this.awaitDrain = 0;
25072 // if true, a maybeReadMore has been scheduled
25073 this.readingMore = false;
25075 this.decoder = null;
25076 this.encoding = null;
25077 if (options.encoding) {
25078 if (!StringDecoder) StringDecoder = __webpack_require__(179).StringDecoder;
25079 this.decoder = new StringDecoder(options.encoding);
25080 this.encoding = options.encoding;
25084 function Readable(options) {
25085 Duplex = Duplex || __webpack_require__(176);
25087 if (!(this instanceof Readable)) return new Readable(options);
25089 this._readableState = new ReadableState(options, this);
25092 this.readable = true;
25095 if (typeof options.read === 'function') this._read = options.read;
25097 if (typeof options.destroy === 'function') this._destroy = options.destroy;
25103 Object.defineProperty(Readable.prototype, 'destroyed', {
25105 if (this._readableState === undefined) {
25108 return this._readableState.destroyed;
25110 set: function (value) {
25111 // we ignore the value if the stream
25112 // has not been initialized yet
25113 if (!this._readableState) {
25117 // backward compatibility, the user is explicitly
25118 // managing destroyed
25119 this._readableState.destroyed = value;
25123 Readable.prototype.destroy = destroyImpl.destroy;
25124 Readable.prototype._undestroy = destroyImpl.undestroy;
25125 Readable.prototype._destroy = function (err, cb) {
25130 // Manually shove something into the read() buffer.
25131 // This returns true if the highWaterMark has not been hit yet,
25132 // similar to how Writable.write() returns true if you should
25133 // write() some more.
25134 Readable.prototype.push = function (chunk, encoding) {
25135 var state = this._readableState;
25136 var skipChunkCheck;
25138 if (!state.objectMode) {
25139 if (typeof chunk === 'string') {
25140 encoding = encoding || state.defaultEncoding;
25141 if (encoding !== state.encoding) {
25142 chunk = Buffer.from(chunk, encoding);
25145 skipChunkCheck = true;
25148 skipChunkCheck = true;
25151 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
25154 // Unshift should *always* be something directly out of read()
25155 Readable.prototype.unshift = function (chunk) {
25156 return readableAddChunk(this, chunk, null, true, false);
25159 function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
25160 var state = stream._readableState;
25161 if (chunk === null) {
25162 state.reading = false;
25163 onEofChunk(stream, state);
25166 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
25168 stream.emit('error', er);
25169 } else if (state.objectMode || chunk && chunk.length > 0) {
25170 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
25171 chunk = _uint8ArrayToBuffer(chunk);
25175 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
25176 } else if (state.ended) {
25177 stream.emit('error', new Error('stream.push() after EOF'));
25179 state.reading = false;
25180 if (state.decoder && !encoding) {
25181 chunk = state.decoder.write(chunk);
25182 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
25184 addChunk(stream, state, chunk, false);
25187 } else if (!addToFront) {
25188 state.reading = false;
25192 return needMoreData(state);
25195 function addChunk(stream, state, chunk, addToFront) {
25196 if (state.flowing && state.length === 0 && !state.sync) {
25197 stream.emit('data', chunk);
25200 // update the buffer info.
25201 state.length += state.objectMode ? 1 : chunk.length;
25202 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
25204 if (state.needReadable) emitReadable(stream);
25206 maybeReadMore(stream, state);
25209 function chunkInvalid(state, chunk) {
25211 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
25212 er = new TypeError('Invalid non-string/buffer chunk');
25217 // if it's past the high water mark, we can push in some more.
25218 // Also, if we have no data yet, we can stand some
25219 // more bytes. This is to work around cases where hwm=0,
25220 // such as the repl. Also, if the push() triggered a
25221 // readable event, and the user called read(largeNumber) such that
25222 // needReadable was set, then we ought to push more, so that another
25223 // 'readable' event will be triggered.
25224 function needMoreData(state) {
25225 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
25228 Readable.prototype.isPaused = function () {
25229 return this._readableState.flowing === false;
25232 // backwards compatibility.
25233 Readable.prototype.setEncoding = function (enc) {
25234 if (!StringDecoder) StringDecoder = __webpack_require__(179).StringDecoder;
25235 this._readableState.decoder = new StringDecoder(enc);
25236 this._readableState.encoding = enc;
25240 // Don't raise the hwm > 8MB
25241 var MAX_HWM = 0x800000;
25242 function computeNewHighWaterMark(n) {
25243 if (n >= MAX_HWM) {
25246 // Get the next highest power of 2 to prevent increasing hwm excessively in
25259 // This function is designed to be inlinable, so please take care when making
25260 // changes to the function body.
25261 function howMuchToRead(n, state) {
25262 if (n <= 0 || state.length === 0 && state.ended) return 0;
25263 if (state.objectMode) return 1;
25265 // Only flow one buffer at a time
25266 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
25268 // If we're asking for more than the current hwm, then raise the hwm.
25269 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
25270 if (n <= state.length) return n;
25271 // Don't have enough
25272 if (!state.ended) {
25273 state.needReadable = true;
25276 return state.length;
25279 // you can override either this method, or the async _read(n) below.
25280 Readable.prototype.read = function (n) {
25282 n = parseInt(n, 10);
25283 var state = this._readableState;
25286 if (n !== 0) state.emittedReadable = false;
25288 // if we're doing read(0) to trigger a readable event, but we
25289 // already have a bunch of data in the buffer, then just trigger
25290 // the 'readable' event and move on.
25291 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
25292 debug('read: emitReadable', state.length, state.ended);
25293 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
25297 n = howMuchToRead(n, state);
25299 // if we've ended, and we're now clear, then finish it up.
25300 if (n === 0 && state.ended) {
25301 if (state.length === 0) endReadable(this);
25305 // All the actual chunk generation logic needs to be
25306 // *below* the call to _read. The reason is that in certain
25307 // synthetic stream cases, such as passthrough streams, _read
25308 // may be a completely synchronous operation which may change
25309 // the state of the read buffer, providing enough data when
25310 // before there was *not* enough.
25312 // So, the steps are:
25313 // 1. Figure out what the state of things will be after we do
25314 // a read from the buffer.
25316 // 2. If that resulting state will trigger a _read, then call _read.
25317 // Note that this may be asynchronous, or synchronous. Yes, it is
25318 // deeply ugly to write APIs this way, but that still doesn't mean
25319 // that the Readable class should behave improperly, as streams are
25320 // designed to be sync/async agnostic.
25321 // Take note if the _read call is sync or async (ie, if the read call
25322 // has returned yet), so that we know whether or not it's safe to emit
25325 // 3. Actually pull the requested chunks out of the buffer and return.
25327 // if we need a readable event, then we need to do some reading.
25328 var doRead = state.needReadable;
25329 debug('need readable', doRead);
25331 // if we currently have less than the highWaterMark, then also read some
25332 if (state.length === 0 || state.length - n < state.highWaterMark) {
25334 debug('length less than watermark', doRead);
25337 // however, if we've ended, then there's no point, and if we're already
25338 // reading, then it's unnecessary.
25339 if (state.ended || state.reading) {
25341 debug('reading or ended', doRead);
25342 } else if (doRead) {
25344 state.reading = true;
25346 // if the length is currently zero, then we *need* a readable event.
25347 if (state.length === 0) state.needReadable = true;
25348 // call internal read method
25349 this._read(state.highWaterMark);
25350 state.sync = false;
25351 // If _read pushed data synchronously, then `reading` will be false,
25352 // and we need to re-evaluate how much data we can return to the user.
25353 if (!state.reading) n = howMuchToRead(nOrig, state);
25357 if (n > 0) ret = fromList(n, state);else ret = null;
25359 if (ret === null) {
25360 state.needReadable = true;
25366 if (state.length === 0) {
25367 // If we have nothing in the buffer, then we want to know
25368 // as soon as we *do* get something into the buffer.
25369 if (!state.ended) state.needReadable = true;
25371 // If we tried to read() past the EOF, then emit end on the next tick.
25372 if (nOrig !== n && state.ended) endReadable(this);
25375 if (ret !== null) this.emit('data', ret);
25380 function onEofChunk(stream, state) {
25381 if (state.ended) return;
25382 if (state.decoder) {
25383 var chunk = state.decoder.end();
25384 if (chunk && chunk.length) {
25385 state.buffer.push(chunk);
25386 state.length += state.objectMode ? 1 : chunk.length;
25389 state.ended = true;
25391 // emit 'readable' now to make sure it gets picked up.
25392 emitReadable(stream);
25395 // Don't emit readable right away in sync mode, because this can trigger
25396 // another read() call => stack overflow. This way, it might trigger
25397 // a nextTick recursion warning, but that's not so bad.
25398 function emitReadable(stream) {
25399 var state = stream._readableState;
25400 state.needReadable = false;
25401 if (!state.emittedReadable) {
25402 debug('emitReadable', state.flowing);
25403 state.emittedReadable = true;
25404 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
25408 function emitReadable_(stream) {
25409 debug('emit readable');
25410 stream.emit('readable');
25414 // at this point, the user has presumably seen the 'readable' event,
25415 // and called read() to consume some data. that may have triggered
25416 // in turn another _read(n) call, in which case reading = true if
25417 // it's in progress.
25418 // However, if we're not ended, or reading, and the length < hwm,
25419 // then go ahead and try to read some more preemptively.
25420 function maybeReadMore(stream, state) {
25421 if (!state.readingMore) {
25422 state.readingMore = true;
25423 pna.nextTick(maybeReadMore_, stream, state);
25427 function maybeReadMore_(stream, state) {
25428 var len = state.length;
25429 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
25430 debug('maybeReadMore read 0');
25432 if (len === state.length)
25433 // didn't get any data, stop spinning.
25434 break;else len = state.length;
25436 state.readingMore = false;
25439 // abstract method. to be overridden in specific implementation classes.
25440 // call cb(er, data) where data is <= n in length.
25441 // for virtual (non-string, non-buffer) streams, "length" is somewhat
25442 // arbitrary, and perhaps not very meaningful.
25443 Readable.prototype._read = function (n) {
25444 this.emit('error', new Error('_read() is not implemented'));
25447 Readable.prototype.pipe = function (dest, pipeOpts) {
25449 var state = this._readableState;
25451 switch (state.pipesCount) {
25453 state.pipes = dest;
25456 state.pipes = [state.pipes, dest];
25459 state.pipes.push(dest);
25462 state.pipesCount += 1;
25463 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
25465 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
25467 var endFn = doEnd ? onend : unpipe;
25468 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
25470 dest.on('unpipe', onunpipe);
25471 function onunpipe(readable, unpipeInfo) {
25473 if (readable === src) {
25474 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
25475 unpipeInfo.hasUnpiped = true;
25486 // when the dest drains, it reduces the awaitDrain counter
25487 // on the source. This would be more elegant with a .once()
25488 // handler in flow(), but adding and removing repeatedly is
25490 var ondrain = pipeOnDrain(src);
25491 dest.on('drain', ondrain);
25493 var cleanedUp = false;
25494 function cleanup() {
25496 // cleanup event handlers once the pipe is broken
25497 dest.removeListener('close', onclose);
25498 dest.removeListener('finish', onfinish);
25499 dest.removeListener('drain', ondrain);
25500 dest.removeListener('error', onerror);
25501 dest.removeListener('unpipe', onunpipe);
25502 src.removeListener('end', onend);
25503 src.removeListener('end', unpipe);
25504 src.removeListener('data', ondata);
25508 // if the reader is waiting for a drain event from this
25509 // specific writer, then it would cause it to never start
25511 // So, if this is awaiting a drain, then we just call it now.
25512 // If we don't know, then assume that we are waiting for one.
25513 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
25516 // If the user pushes more data while we're writing to dest then we'll end up
25517 // in ondata again. However, we only want to increase awaitDrain once because
25518 // dest will only emit one 'drain' event for the multiple writes.
25519 // => Introduce a guard on increasing awaitDrain.
25520 var increasedAwaitDrain = false;
25521 src.on('data', ondata);
25522 function ondata(chunk) {
25524 increasedAwaitDrain = false;
25525 var ret = dest.write(chunk);
25526 if (false === ret && !increasedAwaitDrain) {
25527 // If the user unpiped during `dest.write()`, it is possible
25528 // to get stuck in a permanently paused state if that write
25529 // also returned false.
25530 // => Check whether `dest` is still a piping destination.
25531 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
25532 debug('false write response, pause', src._readableState.awaitDrain);
25533 src._readableState.awaitDrain++;
25534 increasedAwaitDrain = true;
25540 // if the dest has an error, then stop piping into it.
25541 // however, don't suppress the throwing behavior for this.
25542 function onerror(er) {
25543 debug('onerror', er);
25545 dest.removeListener('error', onerror);
25546 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
25549 // Make sure our error handler is attached before userland ones.
25550 prependListener(dest, 'error', onerror);
25552 // Both close and finish should trigger unpipe, but only once.
25553 function onclose() {
25554 dest.removeListener('finish', onfinish);
25557 dest.once('close', onclose);
25558 function onfinish() {
25560 dest.removeListener('close', onclose);
25563 dest.once('finish', onfinish);
25565 function unpipe() {
25570 // tell the dest that it's being piped to
25571 dest.emit('pipe', src);
25573 // start the flow if it hasn't been started already.
25574 if (!state.flowing) {
25575 debug('pipe resume');
25582 function pipeOnDrain(src) {
25583 return function () {
25584 var state = src._readableState;
25585 debug('pipeOnDrain', state.awaitDrain);
25586 if (state.awaitDrain) state.awaitDrain--;
25587 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
25588 state.flowing = true;
25594 Readable.prototype.unpipe = function (dest) {
25595 var state = this._readableState;
25596 var unpipeInfo = { hasUnpiped: false };
25598 // if we're not piping anywhere, then do nothing.
25599 if (state.pipesCount === 0) return this;
25601 // just one destination. most common case.
25602 if (state.pipesCount === 1) {
25603 // passed in one, but it's not the right one.
25604 if (dest && dest !== state.pipes) return this;
25606 if (!dest) dest = state.pipes;
25609 state.pipes = null;
25610 state.pipesCount = 0;
25611 state.flowing = false;
25612 if (dest) dest.emit('unpipe', this, unpipeInfo);
25616 // slow case. multiple pipe destinations.
25620 var dests = state.pipes;
25621 var len = state.pipesCount;
25622 state.pipes = null;
25623 state.pipesCount = 0;
25624 state.flowing = false;
25626 for (var i = 0; i < len; i++) {
25627 dests[i].emit('unpipe', this, unpipeInfo);
25631 // try to find the right one.
25632 var index = indexOf(state.pipes, dest);
25633 if (index === -1) return this;
25635 state.pipes.splice(index, 1);
25636 state.pipesCount -= 1;
25637 if (state.pipesCount === 1) state.pipes = state.pipes[0];
25639 dest.emit('unpipe', this, unpipeInfo);
25644 // set up data events if they are asked for
25645 // Ensure readable listeners eventually get something
25646 Readable.prototype.on = function (ev, fn) {
25647 var res = Stream.prototype.on.call(this, ev, fn);
25649 if (ev === 'data') {
25650 // Start flowing on next tick if stream isn't explicitly paused
25651 if (this._readableState.flowing !== false) this.resume();
25652 } else if (ev === 'readable') {
25653 var state = this._readableState;
25654 if (!state.endEmitted && !state.readableListening) {
25655 state.readableListening = state.needReadable = true;
25656 state.emittedReadable = false;
25657 if (!state.reading) {
25658 pna.nextTick(nReadingNextTick, this);
25659 } else if (state.length) {
25660 emitReadable(this);
25667 Readable.prototype.addListener = Readable.prototype.on;
25669 function nReadingNextTick(self) {
25670 debug('readable nexttick read 0');
25674 // pause() and resume() are remnants of the legacy readable stream API
25675 // If the user uses them, then switch into old mode.
25676 Readable.prototype.resume = function () {
25677 var state = this._readableState;
25678 if (!state.flowing) {
25680 state.flowing = true;
25681 resume(this, state);
25686 function resume(stream, state) {
25687 if (!state.resumeScheduled) {
25688 state.resumeScheduled = true;
25689 pna.nextTick(resume_, stream, state);
25693 function resume_(stream, state) {
25694 if (!state.reading) {
25695 debug('resume read 0');
25699 state.resumeScheduled = false;
25700 state.awaitDrain = 0;
25701 stream.emit('resume');
25703 if (state.flowing && !state.reading) stream.read(0);
25706 Readable.prototype.pause = function () {
25707 debug('call pause flowing=%j', this._readableState.flowing);
25708 if (false !== this._readableState.flowing) {
25710 this._readableState.flowing = false;
25711 this.emit('pause');
25716 function flow(stream) {
25717 var state = stream._readableState;
25718 debug('flow', state.flowing);
25719 while (state.flowing && stream.read() !== null) {}
25722 // wrap an old-style stream as the async data source.
25723 // This is *not* part of the readable stream interface.
25724 // It is an ugly unfortunate mess of history.
25725 Readable.prototype.wrap = function (stream) {
25728 var state = this._readableState;
25729 var paused = false;
25731 stream.on('end', function () {
25732 debug('wrapped end');
25733 if (state.decoder && !state.ended) {
25734 var chunk = state.decoder.end();
25735 if (chunk && chunk.length) _this.push(chunk);
25741 stream.on('data', function (chunk) {
25742 debug('wrapped data');
25743 if (state.decoder) chunk = state.decoder.write(chunk);
25745 // don't skip over falsy values in objectMode
25746 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
25748 var ret = _this.push(chunk);
25755 // proxy all the other methods.
25756 // important when wrapping filters and duplexes.
25757 for (var i in stream) {
25758 if (this[i] === undefined && typeof stream[i] === 'function') {
25759 this[i] = function (method) {
25760 return function () {
25761 return stream[method].apply(stream, arguments);
25767 // proxy certain important events.
25768 for (var n = 0; n < kProxyEvents.length; n++) {
25769 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
25772 // when we try to consume some more bytes, simply unpause the
25773 // underlying stream.
25774 this._read = function (n) {
25775 debug('wrapped _read', n);
25785 Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
25786 // making it explicit this property is not enumerable
25787 // because otherwise some prototype manipulation in
25788 // userland will fail
25791 return this._readableState.highWaterMark;
25795 // exposed for testing purposes only.
25796 Readable._fromList = fromList;
25798 // Pluck off n bytes from an array of buffers.
25799 // Length is the combined lengths of all the buffers in the list.
25800 // This function is designed to be inlinable, so please take care when making
25801 // changes to the function body.
25802 function fromList(n, state) {
25803 // nothing buffered
25804 if (state.length === 0) return null;
25807 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
25808 // read it all, truncate the list
25809 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
25810 state.buffer.clear();
25812 // read part of list
25813 ret = fromListPartial(n, state.buffer, state.decoder);
25819 // Extracts only enough buffered data to satisfy the amount requested.
25820 // This function is designed to be inlinable, so please take care when making
25821 // changes to the function body.
25822 function fromListPartial(n, list, hasStrings) {
25824 if (n < list.head.data.length) {
25825 // slice is the same for buffers and strings
25826 ret = list.head.data.slice(0, n);
25827 list.head.data = list.head.data.slice(n);
25828 } else if (n === list.head.data.length) {
25829 // first chunk is a perfect match
25830 ret = list.shift();
25832 // result spans more than one buffer
25833 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
25838 // Copies a specified amount of characters from the list of buffered data
25840 // This function is designed to be inlinable, so please take care when making
25841 // changes to the function body.
25842 function copyFromBufferString(n, list) {
25847 while (p = p.next) {
25849 var nb = n > str.length ? str.length : n;
25850 if (nb === str.length) ret += str;else ret += str.slice(0, n);
25853 if (nb === str.length) {
25855 if (p.next) list.head = p.next;else list.head = list.tail = null;
25858 p.data = str.slice(nb);
25868 // Copies a specified amount of bytes from the list of buffered data chunks.
25869 // This function is designed to be inlinable, so please take care when making
25870 // changes to the function body.
25871 function copyFromBuffer(n, list) {
25872 var ret = Buffer.allocUnsafe(n);
25876 n -= p.data.length;
25877 while (p = p.next) {
25879 var nb = n > buf.length ? buf.length : n;
25880 buf.copy(ret, ret.length - n, 0, nb);
25883 if (nb === buf.length) {
25885 if (p.next) list.head = p.next;else list.head = list.tail = null;
25888 p.data = buf.slice(nb);
25898 function endReadable(stream) {
25899 var state = stream._readableState;
25901 // If we get here before consuming all the bytes, then that is a
25902 // bug in node. Should never happen.
25903 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
25905 if (!state.endEmitted) {
25906 state.ended = true;
25907 pna.nextTick(endReadableNT, state, stream);
25911 function endReadableNT(state, stream) {
25912 // Check that we didn't get one last unshift.
25913 if (!state.endEmitted && state.length === 0) {
25914 state.endEmitted = true;
25915 stream.readable = false;
25916 stream.emit('end');
25920 function indexOf(xs, x) {
25921 for (var i = 0, l = xs.length; i < l; i++) {
25922 if (xs[i] === x) return i;
25929 /***/ (function(module, exports, __webpack_require__) {
25934 if (typeof process === 'undefined' ||
25935 !process.version ||
25936 process.version.indexOf('v0.') === 0 ||
25937 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
25938 module.exports = { nextTick: nextTick };
25940 module.exports = process
25943 function nextTick(fn, arg1, arg2, arg3) {
25944 if (typeof fn !== 'function') {
25945 throw new TypeError('"callback" argument must be a function');
25947 var len = arguments.length;
25952 return process.nextTick(fn);
25954 return process.nextTick(function afterTickOne() {
25955 fn.call(null, arg1);
25958 return process.nextTick(function afterTickTwo() {
25959 fn.call(null, arg1, arg2);
25962 return process.nextTick(function afterTickThree() {
25963 fn.call(null, arg1, arg2, arg3);
25966 args = new Array(len - 1);
25968 while (i < args.length) {
25969 args[i++] = arguments[i];
25971 return process.nextTick(function afterTick() {
25972 fn.apply(null, args);
25981 /***/ (function(module, exports) {
25983 var toString = {}.toString;
25985 module.exports = Array.isArray || function (arr) {
25986 return toString.call(arr) == '[object Array]';
25992 /***/ (function(module, exports, __webpack_require__) {
25994 module.exports = __webpack_require__(44);
25999 /***/ (function(module, exports, __webpack_require__) {
26001 /* eslint-disable node/no-deprecated-api */
26002 var buffer = __webpack_require__(166)
26003 var Buffer = buffer.Buffer
26005 // alternative to using Object.keys for old browsers
26006 function copyProps (src, dst) {
26007 for (var key in src) {
26008 dst[key] = src[key]
26011 if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
26012 module.exports = buffer
26014 // Copy properties from require('buffer')
26015 copyProps(buffer, exports)
26016 exports.Buffer = SafeBuffer
26019 function SafeBuffer (arg, encodingOrOffset, length) {
26020 return Buffer(arg, encodingOrOffset, length)
26023 // Copy static methods from Buffer
26024 copyProps(Buffer, SafeBuffer)
26026 SafeBuffer.from = function (arg, encodingOrOffset, length) {
26027 if (typeof arg === 'number') {
26028 throw new TypeError('Argument must not be a number')
26030 return Buffer(arg, encodingOrOffset, length)
26033 SafeBuffer.alloc = function (size, fill, encoding) {
26034 if (typeof size !== 'number') {
26035 throw new TypeError('Argument must be a number')
26037 var buf = Buffer(size)
26038 if (fill !== undefined) {
26039 if (typeof encoding === 'string') {
26040 buf.fill(fill, encoding)
26050 SafeBuffer.allocUnsafe = function (size) {
26051 if (typeof size !== 'number') {
26052 throw new TypeError('Argument must be a number')
26054 return Buffer(size)
26057 SafeBuffer.allocUnsafeSlow = function (size) {
26058 if (typeof size !== 'number') {
26059 throw new TypeError('Argument must be a number')
26061 return buffer.SlowBuffer(size)
26067 /***/ (function(module, exports) {
26069 // Copyright Joyent, Inc. and other Node contributors.
26071 // Permission is hereby granted, free of charge, to any person obtaining a
26072 // copy of this software and associated documentation files (the
26073 // "Software"), to deal in the Software without restriction, including
26074 // without limitation the rights to use, copy, modify, merge, publish,
26075 // distribute, sublicense, and/or sell copies of the Software, and to permit
26076 // persons to whom the Software is furnished to do so, subject to the
26077 // following conditions:
26079 // The above copyright notice and this permission notice shall be included
26080 // in all copies or substantial portions of the Software.
26082 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26083 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26084 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26085 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26086 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26087 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26088 // USE OR OTHER DEALINGS IN THE SOFTWARE.
26090 // NOTE: These type checking functions intentionally don't use `instanceof`
26091 // because it is fragile and can be easily faked with `Object.create()`.
26093 function isArray(arg) {
26094 if (Array.isArray) {
26095 return Array.isArray(arg);
26097 return objectToString(arg) === '[object Array]';
26099 exports.isArray = isArray;
26101 function isBoolean(arg) {
26102 return typeof arg === 'boolean';
26104 exports.isBoolean = isBoolean;
26106 function isNull(arg) {
26107 return arg === null;
26109 exports.isNull = isNull;
26111 function isNullOrUndefined(arg) {
26112 return arg == null;
26114 exports.isNullOrUndefined = isNullOrUndefined;
26116 function isNumber(arg) {
26117 return typeof arg === 'number';
26119 exports.isNumber = isNumber;
26121 function isString(arg) {
26122 return typeof arg === 'string';
26124 exports.isString = isString;
26126 function isSymbol(arg) {
26127 return typeof arg === 'symbol';
26129 exports.isSymbol = isSymbol;
26131 function isUndefined(arg) {
26132 return arg === void 0;
26134 exports.isUndefined = isUndefined;
26136 function isRegExp(re) {
26137 return objectToString(re) === '[object RegExp]';
26139 exports.isRegExp = isRegExp;
26141 function isObject(arg) {
26142 return typeof arg === 'object' && arg !== null;
26144 exports.isObject = isObject;
26146 function isDate(d) {
26147 return objectToString(d) === '[object Date]';
26149 exports.isDate = isDate;
26151 function isError(e) {
26152 return (objectToString(e) === '[object Error]' || e instanceof Error);
26154 exports.isError = isError;
26156 function isFunction(arg) {
26157 return typeof arg === 'function';
26159 exports.isFunction = isFunction;
26161 function isPrimitive(arg) {
26162 return arg === null ||
26163 typeof arg === 'boolean' ||
26164 typeof arg === 'number' ||
26165 typeof arg === 'string' ||
26166 typeof arg === 'symbol' || // ES6 symbol
26167 typeof arg === 'undefined';
26169 exports.isPrimitive = isPrimitive;
26171 exports.isBuffer = Buffer.isBuffer;
26173 function objectToString(o) {
26174 return Object.prototype.toString.call(o);
26180 /***/ (function(module, exports, __webpack_require__) {
26185 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
26187 var Buffer = __webpack_require__(172).Buffer;
26188 var util = __webpack_require__(50);
26190 function copyBuffer(src, target, offset) {
26191 src.copy(target, offset);
26194 module.exports = function () {
26195 function BufferList() {
26196 _classCallCheck(this, BufferList);
26203 BufferList.prototype.push = function push(v) {
26204 var entry = { data: v, next: null };
26205 if (this.length > 0) this.tail.next = entry;else this.head = entry;
26210 BufferList.prototype.unshift = function unshift(v) {
26211 var entry = { data: v, next: this.head };
26212 if (this.length === 0) this.tail = entry;
26217 BufferList.prototype.shift = function shift() {
26218 if (this.length === 0) return;
26219 var ret = this.head.data;
26220 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
26225 BufferList.prototype.clear = function clear() {
26226 this.head = this.tail = null;
26230 BufferList.prototype.join = function join(s) {
26231 if (this.length === 0) return '';
26233 var ret = '' + p.data;
26234 while (p = p.next) {
26239 BufferList.prototype.concat = function concat(n) {
26240 if (this.length === 0) return Buffer.alloc(0);
26241 if (this.length === 1) return this.head.data;
26242 var ret = Buffer.allocUnsafe(n >>> 0);
26246 copyBuffer(p.data, ret, i);
26247 i += p.data.length;
26256 if (util && util.inspect && util.inspect.custom) {
26257 module.exports.prototype[util.inspect.custom] = function () {
26258 var obj = util.inspect({ length: this.length });
26259 return this.constructor.name + ' ' + obj;
26265 /***/ (function(module, exports, __webpack_require__) {
26272 var pna = __webpack_require__(169);
26275 // undocumented cb() API, needed for core, not for public API
26276 function destroy(err, cb) {
26279 var readableDestroyed = this._readableState && this._readableState.destroyed;
26280 var writableDestroyed = this._writableState && this._writableState.destroyed;
26282 if (readableDestroyed || writableDestroyed) {
26285 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
26286 pna.nextTick(emitErrorNT, this, err);
26291 // we set destroyed to true before firing error callbacks in order
26292 // to make it re-entrance safe in case destroy() is called within callbacks
26294 if (this._readableState) {
26295 this._readableState.destroyed = true;
26298 // if this is a duplex stream mark the writable part as destroyed as well
26299 if (this._writableState) {
26300 this._writableState.destroyed = true;
26303 this._destroy(err || null, function (err) {
26305 pna.nextTick(emitErrorNT, _this, err);
26306 if (_this._writableState) {
26307 _this._writableState.errorEmitted = true;
26317 function undestroy() {
26318 if (this._readableState) {
26319 this._readableState.destroyed = false;
26320 this._readableState.reading = false;
26321 this._readableState.ended = false;
26322 this._readableState.endEmitted = false;
26325 if (this._writableState) {
26326 this._writableState.destroyed = false;
26327 this._writableState.ended = false;
26328 this._writableState.ending = false;
26329 this._writableState.finished = false;
26330 this._writableState.errorEmitted = false;
26334 function emitErrorNT(self, err) {
26335 self.emit('error', err);
26340 undestroy: undestroy
26345 /***/ (function(module, exports, __webpack_require__) {
26348 // Copyright Joyent, Inc. and other Node contributors.
26350 // Permission is hereby granted, free of charge, to any person obtaining a
26351 // copy of this software and associated documentation files (the
26352 // "Software"), to deal in the Software without restriction, including
26353 // without limitation the rights to use, copy, modify, merge, publish,
26354 // distribute, sublicense, and/or sell copies of the Software, and to permit
26355 // persons to whom the Software is furnished to do so, subject to the
26356 // following conditions:
26358 // The above copyright notice and this permission notice shall be included
26359 // in all copies or substantial portions of the Software.
26361 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26362 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26363 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26364 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26365 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26366 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26367 // USE OR OTHER DEALINGS IN THE SOFTWARE.
26369 // a duplex stream is just a stream that is both readable and writable.
26370 // Since JS doesn't have multiple prototypal inheritance, this class
26371 // prototypally inherits from Readable, and then parasitically from
26378 var pna = __webpack_require__(169);
26382 var objectKeys = Object.keys || function (obj) {
26384 for (var key in obj) {
26390 module.exports = Duplex;
26393 var util = Object.create(__webpack_require__(173));
26394 util.inherits = __webpack_require__(66);
26397 var Readable = __webpack_require__(168);
26398 var Writable = __webpack_require__(177);
26400 util.inherits(Duplex, Readable);
26403 // avoid scope creep, the keys array can then be collected
26404 var keys = objectKeys(Writable.prototype);
26405 for (var v = 0; v < keys.length; v++) {
26406 var method = keys[v];
26407 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
26411 function Duplex(options) {
26412 if (!(this instanceof Duplex)) return new Duplex(options);
26414 Readable.call(this, options);
26415 Writable.call(this, options);
26417 if (options && options.readable === false) this.readable = false;
26419 if (options && options.writable === false) this.writable = false;
26421 this.allowHalfOpen = true;
26422 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
26424 this.once('end', onend);
26427 Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
26428 // making it explicit this property is not enumerable
26429 // because otherwise some prototype manipulation in
26430 // userland will fail
26433 return this._writableState.highWaterMark;
26437 // the no-half-open enforcer
26439 // if we allow half-open state, or if the writable side ended,
26441 if (this.allowHalfOpen || this._writableState.ended) return;
26443 // no more data can be written.
26444 // But allow more writes to happen in this tick.
26445 pna.nextTick(onEndNT, this);
26448 function onEndNT(self) {
26452 Object.defineProperty(Duplex.prototype, 'destroyed', {
26454 if (this._readableState === undefined || this._writableState === undefined) {
26457 return this._readableState.destroyed && this._writableState.destroyed;
26459 set: function (value) {
26460 // we ignore the value if the stream
26461 // has not been initialized yet
26462 if (this._readableState === undefined || this._writableState === undefined) {
26466 // backward compatibility, the user is explicitly
26467 // managing destroyed
26468 this._readableState.destroyed = value;
26469 this._writableState.destroyed = value;
26473 Duplex.prototype._destroy = function (err, cb) {
26477 pna.nextTick(cb, err);
26482 /***/ (function(module, exports, __webpack_require__) {
26485 // Copyright Joyent, Inc. and other Node contributors.
26487 // Permission is hereby granted, free of charge, to any person obtaining a
26488 // copy of this software and associated documentation files (the
26489 // "Software"), to deal in the Software without restriction, including
26490 // without limitation the rights to use, copy, modify, merge, publish,
26491 // distribute, sublicense, and/or sell copies of the Software, and to permit
26492 // persons to whom the Software is furnished to do so, subject to the
26493 // following conditions:
26495 // The above copyright notice and this permission notice shall be included
26496 // in all copies or substantial portions of the Software.
26498 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26499 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26500 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26501 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26502 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26503 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26504 // USE OR OTHER DEALINGS IN THE SOFTWARE.
26506 // A bit simpler than readable streams.
26507 // Implement an async ._write(chunk, encoding, cb), and it'll handle all
26508 // the drain event emission and buffering.
26514 var pna = __webpack_require__(169);
26517 module.exports = Writable;
26519 /* <replacement> */
26520 function WriteReq(chunk, encoding, cb) {
26521 this.chunk = chunk;
26522 this.encoding = encoding;
26523 this.callback = cb;
26527 // It seems a linked list but it is not
26528 // there will be only 2 of these for each stream
26529 function CorkedRequest(state) {
26534 this.finish = function () {
26535 onCorkedFinish(_this, state);
26538 /* </replacement> */
26541 var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
26548 Writable.WritableState = WritableState;
26551 var util = Object.create(__webpack_require__(173));
26552 util.inherits = __webpack_require__(66);
26556 var internalUtil = {
26557 deprecate: __webpack_require__(178)
26562 var Stream = __webpack_require__(171);
26567 var Buffer = __webpack_require__(172).Buffer;
26568 var OurUint8Array = global.Uint8Array || function () {};
26569 function _uint8ArrayToBuffer(chunk) {
26570 return Buffer.from(chunk);
26572 function _isUint8Array(obj) {
26573 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
26578 var destroyImpl = __webpack_require__(175);
26580 util.inherits(Writable, Stream);
26584 function WritableState(options, stream) {
26585 Duplex = Duplex || __webpack_require__(176);
26587 options = options || {};
26589 // Duplex streams are both readable and writable, but share
26590 // the same options object.
26591 // However, some cases require setting options to different
26592 // values for the readable and the writable sides of the duplex stream.
26593 // These options can be provided separately as readableXXX and writableXXX.
26594 var isDuplex = stream instanceof Duplex;
26596 // object stream flag to indicate whether or not this stream
26597 // contains buffers or objects.
26598 this.objectMode = !!options.objectMode;
26600 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
26602 // the point at which write() starts returning false
26603 // Note: 0 is a valid value, means that we always return false if
26604 // the entire buffer is not flushed immediately on write()
26605 var hwm = options.highWaterMark;
26606 var writableHwm = options.writableHighWaterMark;
26607 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
26609 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
26612 this.highWaterMark = Math.floor(this.highWaterMark);
26614 // if _final has been called
26615 this.finalCalled = false;
26617 // drain event flag.
26618 this.needDrain = false;
26619 // at the start of calling end()
26620 this.ending = false;
26621 // when end() has been called, and returned
26622 this.ended = false;
26623 // when 'finish' is emitted
26624 this.finished = false;
26626 // has it been destroyed
26627 this.destroyed = false;
26629 // should we decode strings into buffers before passing to _write?
26630 // this is here so that some node-core streams can optimize string
26631 // handling at a lower level.
26632 var noDecode = options.decodeStrings === false;
26633 this.decodeStrings = !noDecode;
26635 // Crypto is kind of old and crusty. Historically, its default string
26636 // encoding is 'binary' so we have to make this configurable.
26637 // Everything else in the universe uses 'utf8', though.
26638 this.defaultEncoding = options.defaultEncoding || 'utf8';
26640 // not an actual buffer we keep track of, but a measurement
26641 // of how much we're waiting to get pushed to some underlying
26645 // a flag to see when we're in the middle of a write.
26646 this.writing = false;
26648 // when true all writes will be buffered until .uncork() call
26651 // a flag to be able to tell if the onwrite cb is called immediately,
26652 // or on a later tick. We set this to true at first, because any
26653 // actions that shouldn't happen until "later" should generally also
26654 // not happen before the first write call.
26657 // a flag to know if we're processing previously buffered items, which
26658 // may call the _write() callback in the same tick, so that we don't
26659 // end up in an overlapped onwrite situation.
26660 this.bufferProcessing = false;
26662 // the callback that's passed to _write(chunk,cb)
26663 this.onwrite = function (er) {
26664 onwrite(stream, er);
26667 // the callback that the user supplies to write(chunk,encoding,cb)
26668 this.writecb = null;
26670 // the amount that is being written when _write is called.
26673 this.bufferedRequest = null;
26674 this.lastBufferedRequest = null;
26676 // number of pending user-supplied write callbacks
26677 // this must be 0 before 'finish' can be emitted
26678 this.pendingcb = 0;
26680 // emit prefinish if the only thing we're waiting for is _write cbs
26681 // This is relevant for synchronous Transform streams
26682 this.prefinished = false;
26684 // True if the error was already emitted and should not be thrown again
26685 this.errorEmitted = false;
26687 // count buffered requests
26688 this.bufferedRequestCount = 0;
26690 // allocate the first CorkedRequest, there is always
26691 // one allocated and free to use, and we maintain at most two
26692 this.corkedRequestsFree = new CorkedRequest(this);
26695 WritableState.prototype.getBuffer = function getBuffer() {
26696 var current = this.bufferedRequest;
26700 current = current.next;
26707 Object.defineProperty(WritableState.prototype, 'buffer', {
26708 get: internalUtil.deprecate(function () {
26709 return this.getBuffer();
26710 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
26715 // Test _writableState for inheritance to account for Duplex streams,
26716 // whose prototype chain only points to Readable.
26717 var realHasInstance;
26718 if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
26719 realHasInstance = Function.prototype[Symbol.hasInstance];
26720 Object.defineProperty(Writable, Symbol.hasInstance, {
26721 value: function (object) {
26722 if (realHasInstance.call(this, object)) return true;
26723 if (this !== Writable) return false;
26725 return object && object._writableState instanceof WritableState;
26729 realHasInstance = function (object) {
26730 return object instanceof this;
26734 function Writable(options) {
26735 Duplex = Duplex || __webpack_require__(176);
26737 // Writable ctor is applied to Duplexes, too.
26738 // `realHasInstance` is necessary because using plain `instanceof`
26739 // would return false, as no `_writableState` property is attached.
26741 // Trying to use the custom `instanceof` for Writable here will also break the
26742 // Node.js LazyTransform implementation, which has a non-trivial getter for
26743 // `_writableState` that would lead to infinite recursion.
26744 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
26745 return new Writable(options);
26748 this._writableState = new WritableState(options, this);
26751 this.writable = true;
26754 if (typeof options.write === 'function') this._write = options.write;
26756 if (typeof options.writev === 'function') this._writev = options.writev;
26758 if (typeof options.destroy === 'function') this._destroy = options.destroy;
26760 if (typeof options.final === 'function') this._final = options.final;
26766 // Otherwise people can pipe Writable streams, which is just wrong.
26767 Writable.prototype.pipe = function () {
26768 this.emit('error', new Error('Cannot pipe, not readable'));
26771 function writeAfterEnd(stream, cb) {
26772 var er = new Error('write after end');
26773 // TODO: defer error events consistently everywhere, not just the cb
26774 stream.emit('error', er);
26775 pna.nextTick(cb, er);
26778 // Checks that a user-supplied chunk is valid, especially for the particular
26779 // mode the stream is in. Currently this means that `null` is never accepted
26780 // and undefined/non-string values are only allowed in object mode.
26781 function validChunk(stream, state, chunk, cb) {
26785 if (chunk === null) {
26786 er = new TypeError('May not write null values to stream');
26787 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
26788 er = new TypeError('Invalid non-string/buffer chunk');
26791 stream.emit('error', er);
26792 pna.nextTick(cb, er);
26798 Writable.prototype.write = function (chunk, encoding, cb) {
26799 var state = this._writableState;
26801 var isBuf = !state.objectMode && _isUint8Array(chunk);
26803 if (isBuf && !Buffer.isBuffer(chunk)) {
26804 chunk = _uint8ArrayToBuffer(chunk);
26807 if (typeof encoding === 'function') {
26812 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
26814 if (typeof cb !== 'function') cb = nop;
26816 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
26818 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
26824 Writable.prototype.cork = function () {
26825 var state = this._writableState;
26830 Writable.prototype.uncork = function () {
26831 var state = this._writableState;
26833 if (state.corked) {
26836 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
26840 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
26841 // node::ParseEncoding() requires lower case.
26842 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
26843 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
26844 this._writableState.defaultEncoding = encoding;
26848 function decodeChunk(state, chunk, encoding) {
26849 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
26850 chunk = Buffer.from(chunk, encoding);
26855 Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
26856 // making it explicit this property is not enumerable
26857 // because otherwise some prototype manipulation in
26858 // userland will fail
26861 return this._writableState.highWaterMark;
26865 // if we're already writing something, then just put this
26866 // in the queue, and wait our turn. Otherwise, call _write
26867 // If we return false, then we need a drain event, so set that flag.
26868 function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
26870 var newChunk = decodeChunk(state, chunk, encoding);
26871 if (chunk !== newChunk) {
26873 encoding = 'buffer';
26877 var len = state.objectMode ? 1 : chunk.length;
26879 state.length += len;
26881 var ret = state.length < state.highWaterMark;
26882 // we must ensure that previous needDrain will not be reset to false.
26883 if (!ret) state.needDrain = true;
26885 if (state.writing || state.corked) {
26886 var last = state.lastBufferedRequest;
26887 state.lastBufferedRequest = {
26889 encoding: encoding,
26895 last.next = state.lastBufferedRequest;
26897 state.bufferedRequest = state.lastBufferedRequest;
26899 state.bufferedRequestCount += 1;
26901 doWrite(stream, state, false, len, chunk, encoding, cb);
26907 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
26908 state.writelen = len;
26909 state.writecb = cb;
26910 state.writing = true;
26912 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
26913 state.sync = false;
26916 function onwriteError(stream, state, sync, er, cb) {
26920 // defer the callback if we are being called synchronously
26921 // to avoid piling up things on the stack
26922 pna.nextTick(cb, er);
26923 // this can emit finish, and it will always happen
26925 pna.nextTick(finishMaybe, stream, state);
26926 stream._writableState.errorEmitted = true;
26927 stream.emit('error', er);
26929 // the caller expect this to happen before if
26932 stream._writableState.errorEmitted = true;
26933 stream.emit('error', er);
26934 // this can emit finish, but finish must
26935 // always follow error
26936 finishMaybe(stream, state);
26940 function onwriteStateUpdate(state) {
26941 state.writing = false;
26942 state.writecb = null;
26943 state.length -= state.writelen;
26944 state.writelen = 0;
26947 function onwrite(stream, er) {
26948 var state = stream._writableState;
26949 var sync = state.sync;
26950 var cb = state.writecb;
26952 onwriteStateUpdate(state);
26954 if (er) onwriteError(stream, state, sync, er, cb);else {
26955 // Check if we're actually ready to finish, but don't emit yet
26956 var finished = needFinish(state);
26958 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
26959 clearBuffer(stream, state);
26964 asyncWrite(afterWrite, stream, state, finished, cb);
26967 afterWrite(stream, state, finished, cb);
26972 function afterWrite(stream, state, finished, cb) {
26973 if (!finished) onwriteDrain(stream, state);
26976 finishMaybe(stream, state);
26979 // Must force callback to be called on nextTick, so that we don't
26980 // emit 'drain' before the write() consumer gets the 'false' return
26981 // value, and has a chance to attach a 'drain' listener.
26982 function onwriteDrain(stream, state) {
26983 if (state.length === 0 && state.needDrain) {
26984 state.needDrain = false;
26985 stream.emit('drain');
26989 // if there's something in the buffer waiting, then process it
26990 function clearBuffer(stream, state) {
26991 state.bufferProcessing = true;
26992 var entry = state.bufferedRequest;
26994 if (stream._writev && entry && entry.next) {
26995 // Fast case, write everything using _writev()
26996 var l = state.bufferedRequestCount;
26997 var buffer = new Array(l);
26998 var holder = state.corkedRequestsFree;
26999 holder.entry = entry;
27002 var allBuffers = true;
27004 buffer[count] = entry;
27005 if (!entry.isBuf) allBuffers = false;
27006 entry = entry.next;
27009 buffer.allBuffers = allBuffers;
27011 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
27013 // doWrite is almost always async, defer these to save a bit of time
27014 // as the hot path ends with doWrite
27016 state.lastBufferedRequest = null;
27018 state.corkedRequestsFree = holder.next;
27019 holder.next = null;
27021 state.corkedRequestsFree = new CorkedRequest(state);
27023 state.bufferedRequestCount = 0;
27025 // Slow case, write chunks one-by-one
27027 var chunk = entry.chunk;
27028 var encoding = entry.encoding;
27029 var cb = entry.callback;
27030 var len = state.objectMode ? 1 : chunk.length;
27032 doWrite(stream, state, false, len, chunk, encoding, cb);
27033 entry = entry.next;
27034 state.bufferedRequestCount--;
27035 // if we didn't call the onwrite immediately, then
27036 // it means that we need to wait until it does.
27037 // also, that means that the chunk and cb are currently
27038 // being processed, so move the buffer counter past them.
27039 if (state.writing) {
27044 if (entry === null) state.lastBufferedRequest = null;
27047 state.bufferedRequest = entry;
27048 state.bufferProcessing = false;
27051 Writable.prototype._write = function (chunk, encoding, cb) {
27052 cb(new Error('_write() is not implemented'));
27055 Writable.prototype._writev = null;
27057 Writable.prototype.end = function (chunk, encoding, cb) {
27058 var state = this._writableState;
27060 if (typeof chunk === 'function') {
27064 } else if (typeof encoding === 'function') {
27069 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
27071 // .end() fully uncorks
27072 if (state.corked) {
27077 // ignore unnecessary end() calls.
27078 if (!state.ending && !state.finished) endWritable(this, state, cb);
27081 function needFinish(state) {
27082 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
27084 function callFinal(stream, state) {
27085 stream._final(function (err) {
27088 stream.emit('error', err);
27090 state.prefinished = true;
27091 stream.emit('prefinish');
27092 finishMaybe(stream, state);
27095 function prefinish(stream, state) {
27096 if (!state.prefinished && !state.finalCalled) {
27097 if (typeof stream._final === 'function') {
27099 state.finalCalled = true;
27100 pna.nextTick(callFinal, stream, state);
27102 state.prefinished = true;
27103 stream.emit('prefinish');
27108 function finishMaybe(stream, state) {
27109 var need = needFinish(state);
27111 prefinish(stream, state);
27112 if (state.pendingcb === 0) {
27113 state.finished = true;
27114 stream.emit('finish');
27120 function endWritable(stream, state, cb) {
27121 state.ending = true;
27122 finishMaybe(stream, state);
27124 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
27126 state.ended = true;
27127 stream.writable = false;
27130 function onCorkedFinish(corkReq, state, err) {
27131 var entry = corkReq.entry;
27132 corkReq.entry = null;
27134 var cb = entry.callback;
27137 entry = entry.next;
27139 if (state.corkedRequestsFree) {
27140 state.corkedRequestsFree.next = corkReq;
27142 state.corkedRequestsFree = corkReq;
27146 Object.defineProperty(Writable.prototype, 'destroyed', {
27148 if (this._writableState === undefined) {
27151 return this._writableState.destroyed;
27153 set: function (value) {
27154 // we ignore the value if the stream
27155 // has not been initialized yet
27156 if (!this._writableState) {
27160 // backward compatibility, the user is explicitly
27161 // managing destroyed
27162 this._writableState.destroyed = value;
27166 Writable.prototype.destroy = destroyImpl.destroy;
27167 Writable.prototype._undestroy = destroyImpl.undestroy;
27168 Writable.prototype._destroy = function (err, cb) {
27175 /***/ (function(module, exports, __webpack_require__) {
27179 * For Node.js, simply re-export the core `util.deprecate` function.
27182 module.exports = __webpack_require__(50).deprecate;
27187 /***/ (function(module, exports, __webpack_require__) {
27190 // Copyright Joyent, Inc. and other Node contributors.
27192 // Permission is hereby granted, free of charge, to any person obtaining a
27193 // copy of this software and associated documentation files (the
27194 // "Software"), to deal in the Software without restriction, including
27195 // without limitation the rights to use, copy, modify, merge, publish,
27196 // distribute, sublicense, and/or sell copies of the Software, and to permit
27197 // persons to whom the Software is furnished to do so, subject to the
27198 // following conditions:
27200 // The above copyright notice and this permission notice shall be included
27201 // in all copies or substantial portions of the Software.
27203 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
27204 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27205 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
27206 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
27207 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
27208 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
27209 // USE OR OTHER DEALINGS IN THE SOFTWARE.
27215 var Buffer = __webpack_require__(172).Buffer;
27218 var isEncoding = Buffer.isEncoding || function (encoding) {
27219 encoding = '' + encoding;
27220 switch (encoding && encoding.toLowerCase()) {
27221 case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
27228 function _normalizeEncoding(enc) {
27229 if (!enc) return 'utf8';
27249 if (retried) return; // undefined
27250 enc = ('' + enc).toLowerCase();
27256 // Do not cache `Buffer.isEncoding` when checking encoding names as some
27257 // modules monkey-patch it to support additional encodings
27258 function normalizeEncoding(enc) {
27259 var nenc = _normalizeEncoding(enc);
27260 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
27261 return nenc || enc;
27264 // StringDecoder provides an interface for efficiently splitting a series of
27265 // buffers into a series of JS strings without breaking apart multi-byte
27267 exports.StringDecoder = StringDecoder;
27268 function StringDecoder(encoding) {
27269 this.encoding = normalizeEncoding(encoding);
27271 switch (this.encoding) {
27273 this.text = utf16Text;
27274 this.end = utf16End;
27278 this.fillLast = utf8FillLast;
27282 this.text = base64Text;
27283 this.end = base64End;
27287 this.write = simpleWrite;
27288 this.end = simpleEnd;
27292 this.lastTotal = 0;
27293 this.lastChar = Buffer.allocUnsafe(nb);
27296 StringDecoder.prototype.write = function (buf) {
27297 if (buf.length === 0) return '';
27300 if (this.lastNeed) {
27301 r = this.fillLast(buf);
27302 if (r === undefined) return '';
27308 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
27312 StringDecoder.prototype.end = utf8End;
27314 // Returns only complete characters in a Buffer
27315 StringDecoder.prototype.text = utf8Text;
27317 // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
27318 StringDecoder.prototype.fillLast = function (buf) {
27319 if (this.lastNeed <= buf.length) {
27320 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
27321 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
27323 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
27324 this.lastNeed -= buf.length;
27327 // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
27328 // continuation byte. If an invalid byte is detected, -2 is returned.
27329 function utf8CheckByte(byte) {
27330 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
27331 return byte >> 6 === 0x02 ? -1 : -2;
27334 // Checks at most 3 bytes at the end of a Buffer in order to detect an
27335 // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
27336 // needed to complete the UTF-8 character (if applicable) are returned.
27337 function utf8CheckIncomplete(self, buf, i) {
27338 var j = buf.length - 1;
27339 if (j < i) return 0;
27340 var nb = utf8CheckByte(buf[j]);
27342 if (nb > 0) self.lastNeed = nb - 1;
27345 if (--j < i || nb === -2) return 0;
27346 nb = utf8CheckByte(buf[j]);
27348 if (nb > 0) self.lastNeed = nb - 2;
27351 if (--j < i || nb === -2) return 0;
27352 nb = utf8CheckByte(buf[j]);
27355 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
27362 // Validates as many continuation bytes for a multi-byte UTF-8 character as
27363 // needed or are available. If we see a non-continuation byte where we expect
27364 // one, we "replace" the validated continuation bytes we've seen so far with
27365 // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
27366 // behavior. The continuation byte check is included three times in the case
27367 // where all of the continuation bytes for a character exist in the same buffer.
27368 // It is also done this way as a slight performance increase instead of using a
27370 function utf8CheckExtraBytes(self, buf, p) {
27371 if ((buf[0] & 0xC0) !== 0x80) {
27375 if (self.lastNeed > 1 && buf.length > 1) {
27376 if ((buf[1] & 0xC0) !== 0x80) {
27380 if (self.lastNeed > 2 && buf.length > 2) {
27381 if ((buf[2] & 0xC0) !== 0x80) {
27389 // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
27390 function utf8FillLast(buf) {
27391 var p = this.lastTotal - this.lastNeed;
27392 var r = utf8CheckExtraBytes(this, buf, p);
27393 if (r !== undefined) return r;
27394 if (this.lastNeed <= buf.length) {
27395 buf.copy(this.lastChar, p, 0, this.lastNeed);
27396 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
27398 buf.copy(this.lastChar, p, 0, buf.length);
27399 this.lastNeed -= buf.length;
27402 // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
27403 // partial character, the character's bytes are buffered until the required
27404 // number of bytes are available.
27405 function utf8Text(buf, i) {
27406 var total = utf8CheckIncomplete(this, buf, i);
27407 if (!this.lastNeed) return buf.toString('utf8', i);
27408 this.lastTotal = total;
27409 var end = buf.length - (total - this.lastNeed);
27410 buf.copy(this.lastChar, 0, end);
27411 return buf.toString('utf8', i, end);
27414 // For UTF-8, a replacement character is added when ending on a partial
27416 function utf8End(buf) {
27417 var r = buf && buf.length ? this.write(buf) : '';
27418 if (this.lastNeed) return r + '\ufffd';
27422 // UTF-16LE typically needs two bytes per character, but even if we have an even
27423 // number of bytes available, we need to check if we end on a leading/high
27424 // surrogate. In that case, we need to wait for the next two bytes in order to
27425 // decode the last character properly.
27426 function utf16Text(buf, i) {
27427 if ((buf.length - i) % 2 === 0) {
27428 var r = buf.toString('utf16le', i);
27430 var c = r.charCodeAt(r.length - 1);
27431 if (c >= 0xD800 && c <= 0xDBFF) {
27433 this.lastTotal = 4;
27434 this.lastChar[0] = buf[buf.length - 2];
27435 this.lastChar[1] = buf[buf.length - 1];
27436 return r.slice(0, -1);
27442 this.lastTotal = 2;
27443 this.lastChar[0] = buf[buf.length - 1];
27444 return buf.toString('utf16le', i, buf.length - 1);
27447 // For UTF-16LE we do not explicitly append special replacement characters if we
27448 // end on a partial character, we simply let v8 handle that.
27449 function utf16End(buf) {
27450 var r = buf && buf.length ? this.write(buf) : '';
27451 if (this.lastNeed) {
27452 var end = this.lastTotal - this.lastNeed;
27453 return r + this.lastChar.toString('utf16le', 0, end);
27458 function base64Text(buf, i) {
27459 var n = (buf.length - i) % 3;
27460 if (n === 0) return buf.toString('base64', i);
27461 this.lastNeed = 3 - n;
27462 this.lastTotal = 3;
27464 this.lastChar[0] = buf[buf.length - 1];
27466 this.lastChar[0] = buf[buf.length - 2];
27467 this.lastChar[1] = buf[buf.length - 1];
27469 return buf.toString('base64', i, buf.length - n);
27472 function base64End(buf) {
27473 var r = buf && buf.length ? this.write(buf) : '';
27474 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
27478 // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
27479 function simpleWrite(buf) {
27480 return buf.toString(this.encoding);
27483 function simpleEnd(buf) {
27484 return buf && buf.length ? this.write(buf) : '';
27489 /***/ (function(module, exports, __webpack_require__) {
27492 // Copyright Joyent, Inc. and other Node contributors.
27494 // Permission is hereby granted, free of charge, to any person obtaining a
27495 // copy of this software and associated documentation files (the
27496 // "Software"), to deal in the Software without restriction, including
27497 // without limitation the rights to use, copy, modify, merge, publish,
27498 // distribute, sublicense, and/or sell copies of the Software, and to permit
27499 // persons to whom the Software is furnished to do so, subject to the
27500 // following conditions:
27502 // The above copyright notice and this permission notice shall be included
27503 // in all copies or substantial portions of the Software.
27505 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
27506 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27507 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
27508 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
27509 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
27510 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
27511 // USE OR OTHER DEALINGS IN THE SOFTWARE.
27513 // a transform stream is a readable/writable stream where you do
27514 // something with the data. Sometimes it's called a "filter",
27515 // but that's not a great name for it, since that implies a thing where
27516 // some bits pass through, and others are simply ignored. (That would
27517 // be a valid example of a transform, of course.)
27519 // While the output is causally related to the input, it's not a
27520 // necessarily symmetric or synchronous transformation. For example,
27521 // a zlib stream might take multiple plain-text writes(), and then
27522 // emit a single compressed chunk some time in the future.
27524 // Here's how this works:
27526 // The Transform stream has all the aspects of the readable and writable
27527 // stream classes. When you write(chunk), that calls _write(chunk,cb)
27528 // internally, and returns false if there's a lot of pending writes
27529 // buffered up. When you call read(), that calls _read(n) until
27530 // there's enough pending readable data buffered up.
27532 // In a transform stream, the written data is placed in a buffer. When
27533 // _read(n) is called, it transforms the queued up data, calling the
27534 // buffered _write cb's as it consumes chunks. If consuming a single
27535 // written chunk would result in multiple output chunks, then the first
27536 // outputted bit calls the readcb, and subsequent chunks just go into
27537 // the read buffer, and will cause it to emit 'readable' if necessary.
27539 // This way, back-pressure is actually determined by the reading side,
27540 // since _read has to be called to start processing a new chunk. However,
27541 // a pathological inflate type of transform can cause excessive buffering
27542 // here. For example, imagine a stream where every byte of input is
27543 // interpreted as an integer from 0-255, and then results in that many
27544 // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
27545 // 1kb of data being output. In this case, you could write a very small
27546 // amount of input, and end up with a very large amount of output. In
27547 // such a pathological inflating mechanism, there'd be no way to tell
27548 // the system to stop doing the transform. A single 4MB write could
27549 // cause the system to run out of memory.
27551 // However, even in such a pathological case, only a single written chunk
27552 // would be consumed, and then the rest would wait (un-transformed) until
27553 // the results of the previous transformed chunk were consumed.
27557 module.exports = Transform;
27559 var Duplex = __webpack_require__(176);
27562 var util = Object.create(__webpack_require__(173));
27563 util.inherits = __webpack_require__(66);
27566 util.inherits(Transform, Duplex);
27568 function afterTransform(er, data) {
27569 var ts = this._transformState;
27570 ts.transforming = false;
27572 var cb = ts.writecb;
27575 return this.emit('error', new Error('write callback called multiple times'));
27578 ts.writechunk = null;
27581 if (data != null) // single equals check for both `null` and `undefined`
27586 var rs = this._readableState;
27587 rs.reading = false;
27588 if (rs.needReadable || rs.length < rs.highWaterMark) {
27589 this._read(rs.highWaterMark);
27593 function Transform(options) {
27594 if (!(this instanceof Transform)) return new Transform(options);
27596 Duplex.call(this, options);
27598 this._transformState = {
27599 afterTransform: afterTransform.bind(this),
27600 needTransform: false,
27601 transforming: false,
27604 writeencoding: null
27607 // start out asking for a readable event once data is transformed.
27608 this._readableState.needReadable = true;
27610 // we have implemented the _read method, and done the other things
27611 // that Readable wants before the first _read call, so unset the
27612 // sync guard flag.
27613 this._readableState.sync = false;
27616 if (typeof options.transform === 'function') this._transform = options.transform;
27618 if (typeof options.flush === 'function') this._flush = options.flush;
27621 // When the writable side finishes, then flush out anything remaining.
27622 this.on('prefinish', prefinish);
27625 function prefinish() {
27628 if (typeof this._flush === 'function') {
27629 this._flush(function (er, data) {
27630 done(_this, er, data);
27633 done(this, null, null);
27637 Transform.prototype.push = function (chunk, encoding) {
27638 this._transformState.needTransform = false;
27639 return Duplex.prototype.push.call(this, chunk, encoding);
27642 // This is the part where you do stuff!
27643 // override this function in implementation classes.
27644 // 'chunk' is an input chunk.
27646 // Call `push(newChunk)` to pass along transformed output
27647 // to the readable side. You may call 'push' zero or more times.
27649 // Call `cb(err)` when you are done with this chunk. If you pass
27650 // an error, then that'll put the hurt on the whole operation. If you
27651 // never call cb(), then you'll never get another chunk.
27652 Transform.prototype._transform = function (chunk, encoding, cb) {
27653 throw new Error('_transform() is not implemented');
27656 Transform.prototype._write = function (chunk, encoding, cb) {
27657 var ts = this._transformState;
27659 ts.writechunk = chunk;
27660 ts.writeencoding = encoding;
27661 if (!ts.transforming) {
27662 var rs = this._readableState;
27663 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
27667 // Doesn't matter what the args are here.
27668 // _transform does all the work.
27669 // That we got here means that the readable side wants more data.
27670 Transform.prototype._read = function (n) {
27671 var ts = this._transformState;
27673 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
27674 ts.transforming = true;
27675 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
27677 // mark that we need a transform, so that any data that comes in
27678 // will get processed, now that we've asked for it.
27679 ts.needTransform = true;
27683 Transform.prototype._destroy = function (err, cb) {
27686 Duplex.prototype._destroy.call(this, err, function (err2) {
27688 _this2.emit('close');
27692 function done(stream, er, data) {
27693 if (er) return stream.emit('error', er);
27695 if (data != null) // single equals check for both `null` and `undefined`
27698 // if there's nothing in the write buffer, then that means
27699 // that nothing more will ever be provided
27700 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
27702 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
27704 return stream.push(null);
27709 /***/ (function(module, exports, __webpack_require__) {
27712 // Copyright Joyent, Inc. and other Node contributors.
27714 // Permission is hereby granted, free of charge, to any person obtaining a
27715 // copy of this software and associated documentation files (the
27716 // "Software"), to deal in the Software without restriction, including
27717 // without limitation the rights to use, copy, modify, merge, publish,
27718 // distribute, sublicense, and/or sell copies of the Software, and to permit
27719 // persons to whom the Software is furnished to do so, subject to the
27720 // following conditions:
27722 // The above copyright notice and this permission notice shall be included
27723 // in all copies or substantial portions of the Software.
27725 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
27726 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27727 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
27728 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
27729 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
27730 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
27731 // USE OR OTHER DEALINGS IN THE SOFTWARE.
27733 // a passthrough stream.
27734 // basically just the most minimal sort of Transform stream.
27735 // Every written chunk gets output as-is.
27739 module.exports = PassThrough;
27741 var Transform = __webpack_require__(180);
27744 var util = Object.create(__webpack_require__(173));
27745 util.inherits = __webpack_require__(66);
27748 util.inherits(PassThrough, Transform);
27750 function PassThrough(options) {
27751 if (!(this instanceof PassThrough)) return new PassThrough(options);
27753 Transform.call(this, options);
27756 PassThrough.prototype._transform = function (chunk, encoding, cb) {
27762 /***/ (function(module, exports, __webpack_require__) {
27764 var Stream = __webpack_require__(44);
27765 var util = __webpack_require__(50);
27767 // Backwards compatibility for node versions < 8
27768 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
27769 Stream = __webpack_require__(167);
27771 function NoopStream() {
27772 if (!(this instanceof NoopStream)) {
27773 return new NoopStream();
27775 Stream.Transform.call(this);
27778 util.inherits(NoopStream,Stream.Transform);
27780 NoopStream.prototype._transform = function(d,e,cb) { cb() ;};
27782 module.exports = NoopStream;
27786 /***/ (function(module, exports, __webpack_require__) {
27788 var Promise = __webpack_require__(128);
27789 var Stream = __webpack_require__(44);
27790 var Buffer = __webpack_require__(165);
27792 // Backwards compatibility for node versions < 8
27793 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
27794 Stream = __webpack_require__(167);
27796 module.exports = function(entry) {
27797 return new Promise(function(resolve,reject) {
27799 var bufferStream = Stream.Transform()
27800 .on('finish',function() {
27801 resolve(Buffer.concat(chunks));
27803 .on('error',reject);
27805 bufferStream._transform = function(d,e,cb) {
27809 entry.on('error',reject)
27810 .pipe(bufferStream);
27817 /***/ (function(module, exports, __webpack_require__) {
27819 var binary = __webpack_require__(123);
27821 module.exports = function(extraField, vars) {
27823 // Find the ZIP64 header, if present.
27824 while(!extra && extraField && extraField.length) {
27825 var candidateExtra = binary.parse(extraField)
27826 .word16lu('signature')
27827 .word16lu('partsize')
27828 .word64lu('uncompressedSize')
27829 .word64lu('compressedSize')
27830 .word64lu('offset')
27831 .word64lu('disknum')
27834 if(candidateExtra.signature === 0x0001) {
27835 extra = candidateExtra;
27837 // Advance the buffer to the next part.
27838 // The total size of this part is the 4 byte header + partsize.
27839 extraField = extraField.slice(candidateExtra.partsize + 4);
27843 extra = extra || {};
27845 if (vars.compressedSize === 0xffffffff)
27846 vars.compressedSize = extra.compressedSize;
27848 if (vars.uncompressedSize === 0xffffffff)
27849 vars.uncompressedSize= extra.uncompressedSize;
27851 if (vars.offsetToLocalFileHeader === 0xffffffff)
27852 vars.offsetToLocalFileHeader= extra.offset;
27860 /***/ (function(module, exports) {
27862 // Dates in zip file entries are stored as DosDateTime
27863 // Spec is here: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-dosdatetimetofiletime
27865 module.exports = function parseDateTime(date, time) {
27866 const day = date & 0x1F;
27867 const month = date >> 5 & 0x0F;
27868 const year = (date >> 9 & 0x7F) + 1980;
27869 const seconds = time ? (time & 0x1F) * 2 : 0;
27870 const minutes = time ? (time >> 5) & 0x3F : 0;
27871 const hours = time ? (time >> 11): 0;
27873 return new Date(Date.UTC(year, month-1, day, hours, minutes, seconds));
27878 /***/ (function(module, exports, __webpack_require__) {
27880 var Stream = __webpack_require__(44);
27881 var Parse = __webpack_require__(122);
27882 var duplexer2 = __webpack_require__(187);
27883 var BufferStream = __webpack_require__(183);
27885 // Backwards compatibility for node versions < 8
27886 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
27887 Stream = __webpack_require__(167);
27889 function parseOne(match,opts) {
27890 var inStream = Stream.PassThrough({objectMode:true});
27891 var outStream = Stream.PassThrough();
27892 var transform = Stream.Transform({objectMode:true});
27893 var re = match instanceof RegExp ? match : (match && new RegExp(match));
27896 transform._transform = function(entry,e,cb) {
27897 if (found || (re && !re.exec(entry.path))) {
27902 out.emit('entry',entry);
27903 entry.on('error',function(e) {
27904 outStream.emit('error',e);
27906 entry.pipe(outStream)
27907 .on('error',function(err) {
27910 .on('finish',function(d) {
27916 inStream.pipe(Parse(opts))
27917 .on('error',function(err) {
27918 outStream.emit('error',err);
27921 .on('error',Object) // Silence error as its already addressed in transform
27922 .on('finish',function() {
27924 outStream.emit('error',new Error('PATTERN_NOT_FOUND'));
27929 var out = duplexer2(inStream,outStream);
27930 out.buffer = function() {
27931 return BufferStream(outStream);
27937 module.exports = parseOne;
27942 /***/ (function(module, exports, __webpack_require__) {
27947 var stream = __webpack_require__(167);
27949 function DuplexWrapper(options, writable, readable) {
27950 if (typeof readable === "undefined") {
27951 readable = writable;
27952 writable = options;
27956 stream.Duplex.call(this, options);
27958 if (typeof readable.read !== "function") {
27959 readable = (new stream.Readable(options)).wrap(readable);
27962 this._writable = writable;
27963 this._readable = readable;
27964 this._waiting = false;
27968 writable.once("finish", function() {
27972 this.once("finish", function() {
27976 readable.on("readable", function() {
27977 if (self._waiting) {
27978 self._waiting = false;
27983 readable.once("end", function() {
27987 if (!options || typeof options.bubbleErrors === "undefined" || options.bubbleErrors) {
27988 writable.on("error", function(err) {
27989 self.emit("error", err);
27992 readable.on("error", function(err) {
27993 self.emit("error", err);
27998 DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}});
28000 DuplexWrapper.prototype._write = function _write(input, encoding, done) {
28001 this._writable.write(input, encoding, done);
28004 DuplexWrapper.prototype._read = function _read() {
28007 while ((buf = this._readable.read()) !== null) {
28012 this._waiting = true;
28016 module.exports = function duplex2(options, writable, readable) {
28017 return new DuplexWrapper(options, writable, readable);
28020 module.exports.DuplexWrapper = DuplexWrapper;
28025 /***/ (function(module, exports, __webpack_require__) {
28027 module.exports = Extract;
28029 var Parse = __webpack_require__(122);
28030 var Writer = __webpack_require__(189).Writer;
28031 var path = __webpack_require__(2);
28032 var stream = __webpack_require__(44);
28033 var duplexer2 = __webpack_require__(187);
28034 var Promise = __webpack_require__(128);
28036 function Extract (opts) {
28037 // make sure path is normalized before using it
28038 opts.path = path.resolve(path.normalize(opts.path));
28040 var parser = new Parse(opts);
28042 var outStream = new stream.Writable({objectMode: true});
28043 outStream._write = function(entry, encoding, cb) {
28045 if (entry.type == 'Directory') return cb();
28047 // to avoid zip slip (writing outside of the destination), we resolve
28048 // the target path, and make sure it's nested in the intended
28049 // destination, or not extract it otherwise.
28050 var extractPath = path.join(opts.path, entry.path);
28051 if (extractPath.indexOf(opts.path) != 0) {
28055 const writer = opts.getWriter ? opts.getWriter({path: extractPath}) : Writer({ path: extractPath });
28062 var extract = duplexer2(parser,outStream);
28063 parser.once('crx-header', function(crxHeader) {
28064 extract.crxHeader = crxHeader;
28069 .on('finish',function() {
28070 extract.emit('close');
28073 extract.promise = function() {
28074 return new Promise(function(resolve, reject) {
28075 extract.on('close', resolve);
28076 extract.on('error',reject);
28086 /***/ (function(module, exports, __webpack_require__) {
28088 exports.Abstract = __webpack_require__(190)
28089 exports.Reader = __webpack_require__(191)
28090 exports.Writer = __webpack_require__(203)
28093 Reader: __webpack_require__(200),
28094 Writer: __webpack_require__(209)
28098 Reader: __webpack_require__(199),
28099 Writer: __webpack_require__(206)
28103 Reader: __webpack_require__(198),
28104 Writer: __webpack_require__(208)
28108 Reader: __webpack_require__(202),
28109 Writer: __webpack_require__(210)
28112 exports.Reader.Dir = exports.DirReader = exports.Dir.Reader
28113 exports.Reader.File = exports.FileReader = exports.File.Reader
28114 exports.Reader.Link = exports.LinkReader = exports.Link.Reader
28115 exports.Reader.Proxy = exports.ProxyReader = exports.Proxy.Reader
28117 exports.Writer.Dir = exports.DirWriter = exports.Dir.Writer
28118 exports.Writer.File = exports.FileWriter = exports.File.Writer
28119 exports.Writer.Link = exports.LinkWriter = exports.Link.Writer
28120 exports.Writer.Proxy = exports.ProxyWriter = exports.Proxy.Writer
28122 exports.collect = __webpack_require__(207)
28127 /***/ (function(module, exports, __webpack_require__) {
28129 // the parent class for all fstreams.
28131 module.exports = Abstract
28133 var Stream = __webpack_require__(44).Stream
28134 var inherits = __webpack_require__(66)
28136 function Abstract () {
28140 inherits(Abstract, Stream)
28142 Abstract.prototype.on = function (ev, fn) {
28143 if (ev === 'ready' && this.ready) {
28144 process.nextTick(fn.bind(this))
28146 Stream.prototype.on.call(this, ev, fn)
28151 Abstract.prototype.abort = function () {
28152 this._aborted = true
28156 Abstract.prototype.destroy = function () {}
28158 Abstract.prototype.warn = function (msg, code) {
28160 var er = decorate(msg, code, self)
28161 if (!self.listeners('warn')) {
28162 console.error('%s %s\n' +
28165 'fstream_type = %s\n' +
28166 'fstream_path = %s\n' +
28167 'fstream_unc_path = %s\n' +
28168 'fstream_class = %s\n' +
28169 'fstream_stack =\n%s\n',
28176 er.fstream_unc_path,
28178 er.fstream_stack.join('\n'))
28180 self.emit('warn', er)
28184 Abstract.prototype.info = function (msg, code) {
28185 this.emit('info', msg, code)
28188 Abstract.prototype.error = function (msg, code, th) {
28189 var er = decorate(msg, code, this)
28191 else this.emit('error', er)
28194 function decorate (er, code, self) {
28195 if (!(er instanceof Error)) er = new Error(er)
28196 er.code = er.code || code
28197 er.path = er.path || self.path
28198 er.fstream_type = er.fstream_type || self.type
28199 er.fstream_path = er.fstream_path || self.path
28200 if (self._path !== self.path) {
28201 er.fstream_unc_path = er.fstream_unc_path || self._path
28203 if (self.linkpath) {
28204 er.fstream_linkpath = er.fstream_linkpath || self.linkpath
28206 er.fstream_class = er.fstream_class || self.constructor.name
28207 er.fstream_stack = er.fstream_stack ||
28208 new Error().stack.split(/\n/).slice(3).map(function (s) {
28209 return s.replace(/^ {4}at /, '')
28218 /***/ (function(module, exports, __webpack_require__) {
28220 module.exports = Reader
28222 var fs = __webpack_require__(192)
28223 var Stream = __webpack_require__(44).Stream
28224 var inherits = __webpack_require__(66)
28225 var path = __webpack_require__(2)
28226 var getType = __webpack_require__(197)
28227 var hardLinks = Reader.hardLinks = {}
28228 var Abstract = __webpack_require__(190)
28230 // Must do this *before* loading the child classes
28231 inherits(Reader, Abstract)
28233 var LinkReader = __webpack_require__(198)
28235 function Reader (props, currentStat) {
28237 if (!(self instanceof Reader)) return new Reader(props, currentStat)
28239 if (typeof props === 'string') {
28240 props = { path: props }
28244 // call fstream.Reader(dir) to get a DirReader object, etc.
28245 // Note that, unlike in the Writer case, ProxyReader is going
28246 // to be the *normal* state of affairs, since we rarely know
28247 // the type of a file prior to reading it.
28252 if (props.type && typeof props.type === 'function') {
28256 type = getType(props)
28260 if (currentStat && !type) {
28261 type = getType(currentStat)
28268 ClassType = __webpack_require__(199)
28272 // XXX hard links are just files.
28273 // However, it would be good to keep track of files' dev+inode
28274 // and nlink values, and create a HardLinkReader that emits
28275 // a linkpath value of the original copy, so that the tar
28276 // writer can preserve them.
28277 // ClassType = HardLinkReader
28281 ClassType = __webpack_require__(200)
28284 case 'SymbolicLink':
28285 ClassType = LinkReader
28289 ClassType = __webpack_require__(201)
28293 ClassType = __webpack_require__(202)
28297 if (!(self instanceof ClassType)) {
28298 return new ClassType(props)
28301 Abstract.call(self)
28304 self.error('Must provide a path', null, true)
28307 self.readable = true
28308 self.writable = false
28312 self.depth = props.depth = props.depth || 0
28313 self.parent = props.parent || null
28314 self.root = props.root || (props.parent && props.parent.root) || self
28316 self._path = self.path = path.resolve(props.path)
28317 if (process.platform === 'win32') {
28318 self.path = self._path = self.path.replace(/\?/g, '_')
28319 if (self._path.length >= 260) {
28320 // how DOES one create files on the moon?
28321 // if the path has spaces in it, then UNC will fail.
28322 self._swallowErrors = true
28323 // if (self._path.indexOf(" ") === -1) {
28324 self._path = '\\\\?\\' + self.path.replace(/\//g, '\\')
28328 self.basename = props.basename = path.basename(self.path)
28329 self.dirname = props.dirname = path.dirname(self.path)
28331 // these have served their purpose, and are now just noisy clutter
28332 props.parent = props.root = null
28334 // console.error("\n\n\n%s setting size to", props.path, props.size)
28335 self.size = props.size
28336 self.filter = typeof props.filter === 'function' ? props.filter : null
28337 if (props.sort === 'alpha') props.sort = alphasort
28339 // start the ball rolling.
28340 // this will stat the thing, and then call self._read()
28341 // to start reading whatever it is.
28342 // console.error("calling stat", props.path, currentStat)
28343 self._stat(currentStat)
28346 function alphasort (a, b) {
28348 : a.toLowerCase() > b.toLowerCase() ? 1
28349 : a.toLowerCase() < b.toLowerCase() ? -1
28354 Reader.prototype._stat = function (currentStat) {
28356 var props = self.props
28357 var stat = props.follow ? 'stat' : 'lstat'
28358 // console.error("Reader._stat", self._path, currentStat)
28359 if (currentStat) process.nextTick(statCb.bind(null, null, currentStat))
28360 else fs[stat](self._path, statCb)
28362 function statCb (er, props_) {
28363 // console.error("Reader._stat, statCb", self._path, props_, props_.nlink)
28364 if (er) return self.error(er)
28366 Object.keys(props_).forEach(function (k) {
28367 props[k] = props_[k]
28370 // if it's not the expected size, then abort here.
28371 if (undefined !== self.size && props.size !== self.size) {
28372 return self.error('incorrect size')
28374 self.size = props.size
28376 var type = getType(props)
28377 var handleHardlinks = props.hardlinks !== false
28379 // special little thing for handling hardlinks.
28380 if (handleHardlinks && type !== 'Directory' && props.nlink && props.nlink > 1) {
28381 var k = props.dev + ':' + props.ino
28382 // console.error("Reader has nlink", self._path, k)
28383 if (hardLinks[k] === self._path || !hardLinks[k]) {
28384 hardLinks[k] = self._path
28386 // switch into hardlink mode.
28387 type = self.type = self.props.type = 'Link'
28388 self.Link = self.props.Link = true
28389 self.linkpath = self.props.linkpath = hardLinks[k]
28390 // console.error("Hardlink detected, switching mode", self._path, self.linkpath)
28391 // Setting __proto__ would arguably be the "correct"
28392 // approach here, but that just seems too wrong.
28393 self._stat = self._read = LinkReader.prototype._read
28397 if (self.type && self.type !== type) {
28398 self.error('Unexpected type: ' + type)
28401 // if the filter doesn't pass, then just skip over this one.
28402 // still have to emit end so that dir-walking can move on.
28404 var who = self._proxy || self
28405 // special handling for ProxyReaders
28406 if (!self.filter.call(who, who, props)) {
28407 if (!self._disowned) {
28416 // last chance to abort or disown before the flow starts!
28417 var events = ['_stat', 'stat', 'ready']
28420 if (self._aborted) {
28426 if (self._paused && self.type !== 'Directory') {
28427 self.once('resume', go)
28431 var ev = events[e++]
28433 return self._read()
28435 self.emit(ev, props)
28441 Reader.prototype.pipe = function (dest) {
28443 if (typeof dest.add === 'function') {
28444 // piping to a multi-compatible, and we've got directory entries.
28445 self.on('entry', function (entry) {
28446 var ret = dest.add(entry)
28447 if (ret === false) {
28453 // console.error("R Pipe apply Stream Pipe")
28454 return Stream.prototype.pipe.apply(this, arguments)
28457 Reader.prototype.pause = function (who) {
28458 this._paused = true
28460 this.emit('pause', who)
28461 if (this._stream) this._stream.pause(who)
28464 Reader.prototype.resume = function (who) {
28465 this._paused = false
28467 this.emit('resume', who)
28468 if (this._stream) this._stream.resume(who)
28472 Reader.prototype._read = function () {
28473 this.error('Cannot read unknown type: ' + this.type)
28479 /***/ (function(module, exports, __webpack_require__) {
28481 var fs = __webpack_require__(42)
28482 var polyfills = __webpack_require__(193)
28483 var legacy = __webpack_require__(195)
28484 var clone = __webpack_require__(196)
28486 var util = __webpack_require__(50)
28488 /* istanbul ignore next - node 0.x polyfill */
28492 /* istanbul ignore else - node 0.x polyfill */
28493 if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
28494 gracefulQueue = Symbol.for('graceful-fs.queue')
28495 // This is used in testing by future versions
28496 previousSymbol = Symbol.for('graceful-fs.previous')
28498 gracefulQueue = '___graceful-fs.queue'
28499 previousSymbol = '___graceful-fs.previous'
28502 function noop () {}
28506 debug = util.debuglog('gfs4')
28507 else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
28508 debug = function() {
28509 var m = util.format.apply(util, arguments)
28510 m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
28514 // Once time initialization
28515 if (!global[gracefulQueue]) {
28516 // This queue can be shared by multiple loaded instances
28518 Object.defineProperty(global, gracefulQueue, {
28524 // Patch fs.close/closeSync to shared queue version, because we need
28525 // to retry() whenever a close happens *anywhere* in the program.
28526 // This is essential when multiple graceful-fs instances are
28527 // in play at the same time.
28528 fs.close = (function (fs$close) {
28529 function close (fd, cb) {
28530 return fs$close.call(fs, fd, function (err) {
28531 // This function uses the graceful-fs shared queue
28536 if (typeof cb === 'function')
28537 cb.apply(this, arguments)
28541 Object.defineProperty(close, previousSymbol, {
28547 fs.closeSync = (function (fs$closeSync) {
28548 function closeSync (fd) {
28549 // This function uses the graceful-fs shared queue
28550 fs$closeSync.apply(fs, arguments)
28554 Object.defineProperty(closeSync, previousSymbol, {
28555 value: fs$closeSync
28560 if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
28561 process.on('exit', function() {
28562 debug(global[gracefulQueue])
28563 __webpack_require__(58).equal(global[gracefulQueue].length, 0)
28568 module.exports = patch(clone(fs))
28569 if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
28570 module.exports = patch(fs)
28571 fs.__patched = true;
28574 function patch (fs) {
28575 // Everything that references the open() function needs to be in here
28577 fs.gracefulify = patch
28579 fs.createReadStream = createReadStream
28580 fs.createWriteStream = createWriteStream
28581 var fs$readFile = fs.readFile
28582 fs.readFile = readFile
28583 function readFile (path, options, cb) {
28584 if (typeof options === 'function')
28585 cb = options, options = null
28587 return go$readFile(path, options, cb)
28589 function go$readFile (path, options, cb) {
28590 return fs$readFile(path, options, function (err) {
28591 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
28592 enqueue([go$readFile, [path, options, cb]])
28594 if (typeof cb === 'function')
28595 cb.apply(this, arguments)
28602 var fs$writeFile = fs.writeFile
28603 fs.writeFile = writeFile
28604 function writeFile (path, data, options, cb) {
28605 if (typeof options === 'function')
28606 cb = options, options = null
28608 return go$writeFile(path, data, options, cb)
28610 function go$writeFile (path, data, options, cb) {
28611 return fs$writeFile(path, data, options, function (err) {
28612 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
28613 enqueue([go$writeFile, [path, data, options, cb]])
28615 if (typeof cb === 'function')
28616 cb.apply(this, arguments)
28623 var fs$appendFile = fs.appendFile
28625 fs.appendFile = appendFile
28626 function appendFile (path, data, options, cb) {
28627 if (typeof options === 'function')
28628 cb = options, options = null
28630 return go$appendFile(path, data, options, cb)
28632 function go$appendFile (path, data, options, cb) {
28633 return fs$appendFile(path, data, options, function (err) {
28634 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
28635 enqueue([go$appendFile, [path, data, options, cb]])
28637 if (typeof cb === 'function')
28638 cb.apply(this, arguments)
28645 var fs$readdir = fs.readdir
28646 fs.readdir = readdir
28647 function readdir (path, options, cb) {
28649 if (typeof options !== 'function') {
28654 args.push(go$readdir$cb)
28656 return go$readdir(args)
28658 function go$readdir$cb (err, files) {
28659 if (files && files.sort)
28662 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
28663 enqueue([go$readdir, [args]])
28666 if (typeof cb === 'function')
28667 cb.apply(this, arguments)
28673 function go$readdir (args) {
28674 return fs$readdir.apply(fs, args)
28677 if (process.version.substr(0, 4) === 'v0.8') {
28678 var legStreams = legacy(fs)
28679 ReadStream = legStreams.ReadStream
28680 WriteStream = legStreams.WriteStream
28683 var fs$ReadStream = fs.ReadStream
28684 if (fs$ReadStream) {
28685 ReadStream.prototype = Object.create(fs$ReadStream.prototype)
28686 ReadStream.prototype.open = ReadStream$open
28689 var fs$WriteStream = fs.WriteStream
28690 if (fs$WriteStream) {
28691 WriteStream.prototype = Object.create(fs$WriteStream.prototype)
28692 WriteStream.prototype.open = WriteStream$open
28695 Object.defineProperty(fs, 'ReadStream', {
28699 set: function (val) {
28705 Object.defineProperty(fs, 'WriteStream', {
28709 set: function (val) {
28717 var FileReadStream = ReadStream
28718 Object.defineProperty(fs, 'FileReadStream', {
28720 return FileReadStream
28722 set: function (val) {
28723 FileReadStream = val
28728 var FileWriteStream = WriteStream
28729 Object.defineProperty(fs, 'FileWriteStream', {
28731 return FileWriteStream
28733 set: function (val) {
28734 FileWriteStream = val
28740 function ReadStream (path, options) {
28741 if (this instanceof ReadStream)
28742 return fs$ReadStream.apply(this, arguments), this
28744 return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
28747 function ReadStream$open () {
28749 open(that.path, that.flags, that.mode, function (err, fd) {
28751 if (that.autoClose)
28754 that.emit('error', err)
28757 that.emit('open', fd)
28763 function WriteStream (path, options) {
28764 if (this instanceof WriteStream)
28765 return fs$WriteStream.apply(this, arguments), this
28767 return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
28770 function WriteStream$open () {
28772 open(that.path, that.flags, that.mode, function (err, fd) {
28775 that.emit('error', err)
28778 that.emit('open', fd)
28783 function createReadStream (path, options) {
28784 return new fs.ReadStream(path, options)
28787 function createWriteStream (path, options) {
28788 return new fs.WriteStream(path, options)
28791 var fs$open = fs.open
28793 function open (path, flags, mode, cb) {
28794 if (typeof mode === 'function')
28795 cb = mode, mode = null
28797 return go$open(path, flags, mode, cb)
28799 function go$open (path, flags, mode, cb) {
28800 return fs$open(path, flags, mode, function (err, fd) {
28801 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
28802 enqueue([go$open, [path, flags, mode, cb]])
28804 if (typeof cb === 'function')
28805 cb.apply(this, arguments)
28815 function enqueue (elem) {
28816 debug('ENQUEUE', elem[0].name, elem[1])
28817 global[gracefulQueue].push(elem)
28820 function retry () {
28821 var elem = global[gracefulQueue].shift()
28823 debug('RETRY', elem[0].name, elem[1])
28824 elem[0].apply(null, elem[1])
28831 /***/ (function(module, exports, __webpack_require__) {
28833 var constants = __webpack_require__(194)
28835 var origCwd = process.cwd
28838 var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform
28840 process.cwd = function() {
28842 cwd = origCwd.call(process)
28849 var chdir = process.chdir
28850 process.chdir = function(d) {
28852 chdir.call(process, d)
28855 module.exports = patch
28857 function patch (fs) {
28858 // (re-)implement some things that are known busted or missing.
28860 // lchmod, broken prior to 0.6.2
28861 // back-port the fix here.
28862 if (constants.hasOwnProperty('O_SYMLINK') &&
28863 process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
28867 // lutimes implementation, or no-op
28872 // https://github.com/isaacs/node-graceful-fs/issues/4
28873 // Chown should not fail on einval or eperm if non-root.
28874 // It should not fail on enosys ever, as this just indicates
28875 // that a fs doesn't support the intended operation.
28877 fs.chown = chownFix(fs.chown)
28878 fs.fchown = chownFix(fs.fchown)
28879 fs.lchown = chownFix(fs.lchown)
28881 fs.chmod = chmodFix(fs.chmod)
28882 fs.fchmod = chmodFix(fs.fchmod)
28883 fs.lchmod = chmodFix(fs.lchmod)
28885 fs.chownSync = chownFixSync(fs.chownSync)
28886 fs.fchownSync = chownFixSync(fs.fchownSync)
28887 fs.lchownSync = chownFixSync(fs.lchownSync)
28889 fs.chmodSync = chmodFixSync(fs.chmodSync)
28890 fs.fchmodSync = chmodFixSync(fs.fchmodSync)
28891 fs.lchmodSync = chmodFixSync(fs.lchmodSync)
28893 fs.stat = statFix(fs.stat)
28894 fs.fstat = statFix(fs.fstat)
28895 fs.lstat = statFix(fs.lstat)
28897 fs.statSync = statFixSync(fs.statSync)
28898 fs.fstatSync = statFixSync(fs.fstatSync)
28899 fs.lstatSync = statFixSync(fs.lstatSync)
28901 // if lchmod/lchown do not exist, then make them no-ops
28903 fs.lchmod = function (path, mode, cb) {
28904 if (cb) process.nextTick(cb)
28906 fs.lchmodSync = function () {}
28909 fs.lchown = function (path, uid, gid, cb) {
28910 if (cb) process.nextTick(cb)
28912 fs.lchownSync = function () {}
28915 // on Windows, A/V software can lock the directory, causing this
28916 // to fail with an EACCES or EPERM if the directory contains newly
28917 // created files. Try again on failure, for up to 60 seconds.
28919 // Set the timeout this long because some Windows Anti-Virus, such as Parity
28920 // bit9, may lock files for up to a minute, causing npm package install
28921 // failures. Also, take care to yield the scheduler. Windows scheduling gives
28922 // CPU to a busy looping process, which can cause the program causing the lock
28923 // contention to be starved of CPU by node, so the contention doesn't resolve.
28924 if (platform === "win32") {
28925 fs.rename = (function (fs$rename) { return function (from, to, cb) {
28926 var start = Date.now()
28928 fs$rename(from, to, function CB (er) {
28930 && (er.code === "EACCES" || er.code === "EPERM")
28931 && Date.now() - start < 60000) {
28932 setTimeout(function() {
28933 fs.stat(to, function (stater, st) {
28934 if (stater && stater.code === "ENOENT")
28935 fs$rename(from, to, CB);
28949 // if read() returns EAGAIN, then just try it again.
28950 fs.read = (function (fs$read) {
28951 function read (fd, buffer, offset, length, position, callback_) {
28953 if (callback_ && typeof callback_ === 'function') {
28955 callback = function (er, _, __) {
28956 if (er && er.code === 'EAGAIN' && eagCounter < 10) {
28958 return fs$read.call(fs, fd, buffer, offset, length, position, callback)
28960 callback_.apply(this, arguments)
28963 return fs$read.call(fs, fd, buffer, offset, length, position, callback)
28966 // This ensures `util.promisify` works as it does for native `fs.read`.
28967 read.__proto__ = fs$read
28971 fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
28975 return fs$readSync.call(fs, fd, buffer, offset, length, position)
28977 if (er.code === 'EAGAIN' && eagCounter < 10) {
28986 function patchLchmod (fs) {
28987 fs.lchmod = function (path, mode, callback) {
28989 , constants.O_WRONLY | constants.O_SYMLINK
28991 , function (err, fd) {
28993 if (callback) callback(err)
28996 // prefer to return the chmod error, if one occurs,
28997 // but still try to close, and report closing errors if they occur.
28998 fs.fchmod(fd, mode, function (err) {
28999 fs.close(fd, function(err2) {
29000 if (callback) callback(err || err2)
29006 fs.lchmodSync = function (path, mode) {
29007 var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
29009 // prefer to return the chmod error, if one occurs,
29010 // but still try to close, and report closing errors if they occur.
29014 ret = fs.fchmodSync(fd, mode)
29029 function patchLutimes (fs) {
29030 if (constants.hasOwnProperty("O_SYMLINK")) {
29031 fs.lutimes = function (path, at, mt, cb) {
29032 fs.open(path, constants.O_SYMLINK, function (er, fd) {
29037 fs.futimes(fd, at, mt, function (er) {
29038 fs.close(fd, function (er2) {
29039 if (cb) cb(er || er2)
29045 fs.lutimesSync = function (path, at, mt) {
29046 var fd = fs.openSync(path, constants.O_SYMLINK)
29050 ret = fs.futimesSync(fd, at, mt)
29065 fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
29066 fs.lutimesSync = function () {}
29070 function chmodFix (orig) {
29071 if (!orig) return orig
29072 return function (target, mode, cb) {
29073 return orig.call(fs, target, mode, function (er) {
29074 if (chownErOk(er)) er = null
29075 if (cb) cb.apply(this, arguments)
29080 function chmodFixSync (orig) {
29081 if (!orig) return orig
29082 return function (target, mode) {
29084 return orig.call(fs, target, mode)
29086 if (!chownErOk(er)) throw er
29092 function chownFix (orig) {
29093 if (!orig) return orig
29094 return function (target, uid, gid, cb) {
29095 return orig.call(fs, target, uid, gid, function (er) {
29096 if (chownErOk(er)) er = null
29097 if (cb) cb.apply(this, arguments)
29102 function chownFixSync (orig) {
29103 if (!orig) return orig
29104 return function (target, uid, gid) {
29106 return orig.call(fs, target, uid, gid)
29108 if (!chownErOk(er)) throw er
29113 function statFix (orig) {
29114 if (!orig) return orig
29115 // Older versions of Node erroneously returned signed integers for
29117 return function (target, options, cb) {
29118 if (typeof options === 'function') {
29122 function callback (er, stats) {
29124 if (stats.uid < 0) stats.uid += 0x100000000
29125 if (stats.gid < 0) stats.gid += 0x100000000
29127 if (cb) cb.apply(this, arguments)
29129 return options ? orig.call(fs, target, options, callback)
29130 : orig.call(fs, target, callback)
29134 function statFixSync (orig) {
29135 if (!orig) return orig
29136 // Older versions of Node erroneously returned signed integers for
29138 return function (target, options) {
29139 var stats = options ? orig.call(fs, target, options)
29140 : orig.call(fs, target)
29141 if (stats.uid < 0) stats.uid += 0x100000000
29142 if (stats.gid < 0) stats.gid += 0x100000000
29147 // ENOSYS means that the fs doesn't support the op. Just ignore
29148 // that, because it doesn't matter.
29150 // if there's no getuid, or if getuid() is something other
29151 // than 0, and the error is EINVAL or EPERM, then just ignore
29154 // This specific case is a silent failure in cp, install, tar,
29155 // and most other unix tools that manage permissions.
29157 // When running as root, or if other types of errors are
29158 // encountered, then it's strict.
29159 function chownErOk (er) {
29163 if (er.code === "ENOSYS")
29166 var nonroot = !process.getuid || process.getuid() !== 0
29168 if (er.code === "EINVAL" || er.code === "EPERM")
29179 /***/ (function(module, exports) {
29181 module.exports = require("constants");
29185 /***/ (function(module, exports, __webpack_require__) {
29187 var Stream = __webpack_require__(44).Stream
29189 module.exports = legacy
29191 function legacy (fs) {
29193 ReadStream: ReadStream,
29194 WriteStream: WriteStream
29197 function ReadStream (path, options) {
29198 if (!(this instanceof ReadStream)) return new ReadStream(path, options);
29206 this.readable = true;
29207 this.paused = false;
29210 this.mode = 438; /*=0666*/
29211 this.bufferSize = 64 * 1024;
29213 options = options || {};
29215 // Mixin options into this
29216 var keys = Object.keys(options);
29217 for (var index = 0, length = keys.length; index < length; index++) {
29218 var key = keys[index];
29219 this[key] = options[key];
29222 if (this.encoding) this.setEncoding(this.encoding);
29224 if (this.start !== undefined) {
29225 if ('number' !== typeof this.start) {
29226 throw TypeError('start must be a Number');
29228 if (this.end === undefined) {
29229 this.end = Infinity;
29230 } else if ('number' !== typeof this.end) {
29231 throw TypeError('end must be a Number');
29234 if (this.start > this.end) {
29235 throw new Error('start must be <= end');
29238 this.pos = this.start;
29241 if (this.fd !== null) {
29242 process.nextTick(function() {
29248 fs.open(this.path, this.flags, this.mode, function (err, fd) {
29250 self.emit('error', err);
29251 self.readable = false;
29256 self.emit('open', fd);
29261 function WriteStream (path, options) {
29262 if (!(this instanceof WriteStream)) return new WriteStream(path, options);
29268 this.writable = true;
29271 this.encoding = 'binary';
29272 this.mode = 438; /*=0666*/
29273 this.bytesWritten = 0;
29275 options = options || {};
29277 // Mixin options into this
29278 var keys = Object.keys(options);
29279 for (var index = 0, length = keys.length; index < length; index++) {
29280 var key = keys[index];
29281 this[key] = options[key];
29284 if (this.start !== undefined) {
29285 if ('number' !== typeof this.start) {
29286 throw TypeError('start must be a Number');
29288 if (this.start < 0) {
29289 throw new Error('start must be >= zero');
29292 this.pos = this.start;
29298 if (this.fd === null) {
29299 this._open = fs.open;
29300 this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
29309 /***/ (function(module, exports, __webpack_require__) {
29314 module.exports = clone
29316 function clone (obj) {
29317 if (obj === null || typeof obj !== 'object')
29320 if (obj instanceof Object)
29321 var copy = { __proto__: obj.__proto__ }
29323 var copy = Object.create(null)
29325 Object.getOwnPropertyNames(obj).forEach(function (key) {
29326 Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
29335 /***/ (function(module, exports) {
29337 module.exports = getType
29339 function getType (st) {
29344 'Link', // special for hardlinks from tarballs
29352 if (st.type && types.indexOf(st.type) !== -1) {
29357 for (var i = 0, l = types.length; i < l; i++) {
29359 var is = st[type] || st['is' + type]
29360 if (typeof is === 'function') is = is.call(st)
29374 /***/ (function(module, exports, __webpack_require__) {
29376 // Basically just a wrapper around an fs.readlink
29378 // XXX: Enhance this to support the Link type, by keeping
29379 // a lookup table of {<dev+inode>:<path>}, so that hardlinks
29380 // can be preserved in tarballs.
29382 module.exports = LinkReader
29384 var fs = __webpack_require__(192)
29385 var inherits = __webpack_require__(66)
29386 var Reader = __webpack_require__(191)
29388 inherits(LinkReader, Reader)
29390 function LinkReader (props) {
29392 if (!(self instanceof LinkReader)) {
29393 throw new Error('LinkReader must be called as constructor.')
29396 if (!((props.type === 'Link' && props.Link) ||
29397 (props.type === 'SymbolicLink' && props.SymbolicLink))) {
29398 throw new Error('Non-link type ' + props.type)
29401 Reader.call(self, props)
29404 // When piping a LinkReader into a LinkWriter, we have to
29405 // already have the linkpath property set, so that has to
29406 // happen *before* the "ready" event, which means we need to
29407 // override the _stat method.
29408 LinkReader.prototype._stat = function (currentStat) {
29410 fs.readlink(self._path, function (er, linkpath) {
29411 if (er) return self.error(er)
29412 self.linkpath = self.props.linkpath = linkpath
29413 self.emit('linkpath', linkpath)
29414 Reader.prototype._stat.call(self, currentStat)
29418 LinkReader.prototype._read = function () {
29420 if (self._paused) return
29421 // basically just a no-op, since we got all the info we need
29422 // from the _stat method
29423 if (!self._ended) {
29433 /***/ (function(module, exports, __webpack_require__) {
29435 // A thing that emits "entry" events with Reader objects
29436 // Pausing it causes it to stop emitting entry events, and also
29437 // pauses the current entry if there is one.
29439 module.exports = DirReader
29441 var fs = __webpack_require__(192)
29442 var inherits = __webpack_require__(66)
29443 var path = __webpack_require__(2)
29444 var Reader = __webpack_require__(191)
29445 var assert = __webpack_require__(58).ok
29447 inherits(DirReader, Reader)
29449 function DirReader (props) {
29451 if (!(self instanceof DirReader)) {
29452 throw new Error('DirReader must be called as constructor.')
29455 // should already be established as a Directory type
29456 if (props.type !== 'Directory' || !props.Directory) {
29457 throw new Error('Non-directory type ' + props.type)
29460 self.entries = null
29462 self._paused = false
29466 this.sort = props.sort
29469 Reader.call(this, props)
29472 DirReader.prototype._getEntries = function () {
29475 // race condition. might pause() before calling _getEntries,
29476 // and then resume, and try to get them a second time.
29477 if (self._gotEntries) return
29478 self._gotEntries = true
29480 fs.readdir(self._path, function (er, entries) {
29481 if (er) return self.error(er)
29483 self.entries = entries
29485 self.emit('entries', entries)
29486 if (self._paused) self.once('resume', processEntries)
29487 else processEntries()
29489 function processEntries () {
29490 self._length = self.entries.length
29491 if (typeof self.sort === 'function') {
29492 self.entries = self.entries.sort(self.sort.bind(self))
29499 // start walking the dir, and emit an "entry" event for each one.
29500 DirReader.prototype._read = function () {
29503 if (!self.entries) return self._getEntries()
29505 if (self._paused || self._currentEntry || self._aborted) {
29506 // console.error('DR paused=%j, current=%j, aborted=%j', self._paused, !!self._currentEntry, self._aborted)
29511 if (self._index >= self.entries.length) {
29512 if (!self._ended) {
29520 // ok, handle this one, then.
29522 // save creating a proxy, by stat'ing the thing now.
29523 var p = path.resolve(self._path, self.entries[self._index])
29524 assert(p !== self._path)
29525 assert(self.entries[self._index])
29527 // set this to prevent trying to _read() again in the stat time.
29528 self._currentEntry = p
29529 fs[ self.props.follow ? 'stat' : 'lstat' ](p, function (er, stat) {
29530 if (er) return self.error(er)
29532 var who = self._proxy || self
29535 stat.basename = path.basename(p)
29536 stat.dirname = path.dirname(p)
29537 var childProps = self.getChildProps.call(who, stat)
29538 childProps.path = p
29539 childProps.basename = path.basename(p)
29540 childProps.dirname = path.dirname(p)
29542 var entry = Reader(childProps, stat)
29544 // console.error("DR Entry", p, stat.size)
29546 self._currentEntry = entry
29548 // "entry" events are for direct entries in a specific dir.
29549 // "child" events are for any and all children at all levels.
29550 // This nomenclature is not completely final.
29552 entry.on('pause', function (who) {
29553 if (!self._paused && !entry._disowned) {
29558 entry.on('resume', function (who) {
29559 if (self._paused && !entry._disowned) {
29564 entry.on('stat', function (props) {
29565 self.emit('_entryStat', entry, props)
29566 if (entry._aborted) return
29567 if (entry._paused) {
29568 entry.once('resume', function () {
29569 self.emit('entryStat', entry, props)
29571 } else self.emit('entryStat', entry, props)
29574 entry.on('ready', function EMITCHILD () {
29575 // console.error("DR emit child", entry._path)
29576 if (self._paused) {
29577 // console.error(" DR emit child - try again later")
29578 // pause the child, and emit the "entry" event once we drain.
29579 // console.error("DR pausing child entry")
29581 return self.once('resume', EMITCHILD)
29584 // skip over sockets. they can't be piped around properly,
29585 // so there's really no sense even acknowledging them.
29586 // if someone really wants to see them, they can listen to
29587 // the "socket" events.
29588 if (entry.type === 'Socket') {
29589 self.emit('socket', entry)
29591 self.emitEntry(entry)
29596 entry.on('close', onend)
29597 entry.on('disown', onend)
29598 function onend () {
29601 self.emit('childEnd', entry)
29602 self.emit('entryEnd', entry)
29603 self._currentEntry = null
29604 if (!self._paused) {
29609 // XXX Remove this. Works in node as of 0.6.2 or so.
29610 // Long filenames should not break stuff.
29611 entry.on('error', function (er) {
29612 if (entry._swallowErrors) {
29615 entry.emit('close')
29617 self.emit('error', er)
29621 // proxy up some events.
29626 ].forEach(function (ev) {
29627 entry.on(ev, self.emit.bind(self, ev))
29632 DirReader.prototype.disown = function (entry) {
29633 entry.emit('beforeDisown')
29634 entry._disowned = true
29635 entry.parent = entry.root = null
29636 if (entry === this._currentEntry) {
29637 this._currentEntry = null
29639 entry.emit('disown')
29642 DirReader.prototype.getChildProps = function () {
29644 depth: this.depth + 1,
29645 root: this.root || this,
29647 follow: this.follow,
29648 filter: this.filter,
29649 sort: this.props.sort,
29650 hardlinks: this.props.hardlinks
29654 DirReader.prototype.pause = function (who) {
29656 if (self._paused) return
29658 self._paused = true
29659 if (self._currentEntry && self._currentEntry.pause) {
29660 self._currentEntry.pause(who)
29662 self.emit('pause', who)
29665 DirReader.prototype.resume = function (who) {
29667 if (!self._paused) return
29670 self._paused = false
29671 // console.error('DR Emit Resume', self._path)
29672 self.emit('resume', who)
29673 if (self._paused) {
29674 // console.error('DR Re-paused', self._path)
29678 if (self._currentEntry) {
29679 if (self._currentEntry.resume) self._currentEntry.resume(who)
29680 } else self._read()
29683 DirReader.prototype.emitEntry = function (entry) {
29684 this.emit('entry', entry)
29685 this.emit('child', entry)
29691 /***/ (function(module, exports, __webpack_require__) {
29693 // Basically just a wrapper around an fs.ReadStream
29695 module.exports = FileReader
29697 var fs = __webpack_require__(192)
29698 var inherits = __webpack_require__(66)
29699 var Reader = __webpack_require__(191)
29700 var EOF = {EOF: true}
29701 var CLOSE = {CLOSE: true}
29703 inherits(FileReader, Reader)
29705 function FileReader (props) {
29706 // console.error(" FR create", props.path, props.size, new Error().stack)
29708 if (!(self instanceof FileReader)) {
29709 throw new Error('FileReader must be called as constructor.')
29712 // should already be established as a File type
29713 // XXX Todo: preserve hardlinks by tracking dev+inode+nlink,
29714 // with a HardLinkReader class.
29715 if (!((props.type === 'Link' && props.Link) ||
29716 (props.type === 'File' && props.File))) {
29717 throw new Error('Non-file type ' + props.type)
29721 self._bytesEmitted = 0
29722 Reader.call(self, props)
29725 FileReader.prototype._getStream = function () {
29727 var stream = self._stream = fs.createReadStream(self._path, self.props)
29729 if (self.props.blksize) {
29730 stream.bufferSize = self.props.blksize
29733 stream.on('open', self.emit.bind(self, 'open'))
29735 stream.on('data', function (c) {
29736 // console.error('\t\t%d %s', c.length, self.basename)
29737 self._bytesEmitted += c.length
29738 // no point saving empty chunks
29741 } else if (self._paused || self._buffer.length) {
29742 self._buffer.push(c)
29744 } else self.emit('data', c)
29747 stream.on('end', function () {
29748 if (self._paused || self._buffer.length) {
29749 // console.error('FR Buffering End', self._path)
29750 self._buffer.push(EOF)
29756 if (self._bytesEmitted !== self.props.size) {
29757 self.error("Didn't get expected byte count\n" +
29758 'expect: ' + self.props.size + '\n' +
29759 'actual: ' + self._bytesEmitted)
29763 stream.on('close', function () {
29764 if (self._paused || self._buffer.length) {
29765 // console.error('FR Buffering Close', self._path)
29766 self._buffer.push(CLOSE)
29769 // console.error('FR close 1', self._path)
29774 stream.on('error', function (e) {
29775 self.emit('error', e)
29781 FileReader.prototype._read = function () {
29783 // console.error('FR _read', self._path)
29784 if (self._paused) {
29785 // console.error('FR _read paused', self._path)
29789 if (!self._stream) {
29790 // console.error('FR _getStream calling', self._path)
29791 return self._getStream()
29794 // clear out the buffer, if there is one.
29795 if (self._buffer.length) {
29796 // console.error('FR _read has buffer', self._buffer.length, self._path)
29797 var buf = self._buffer
29798 for (var i = 0, l = buf.length; i < l; i++) {
29801 // console.error('FR Read emitting buffered end', self._path)
29803 } else if (c === CLOSE) {
29804 // console.error('FR Read emitting buffered close', self._path)
29807 // console.error('FR Read emitting buffered data', self._path)
29808 self.emit('data', c)
29811 if (self._paused) {
29812 // console.error('FR Read Re-pausing at '+i, self._path)
29813 self._buffer = buf.slice(i)
29817 self._buffer.length = 0
29819 // console.error("FR _read done")
29820 // that's about all there is to it.
29823 FileReader.prototype.pause = function (who) {
29825 // console.error('FR Pause', self._path)
29826 if (self._paused) return
29828 self._paused = true
29829 if (self._stream) self._stream.pause()
29830 self.emit('pause', who)
29833 FileReader.prototype.resume = function (who) {
29835 // console.error('FR Resume', self._path)
29836 if (!self._paused) return
29838 self.emit('resume', who)
29839 self._paused = false
29840 if (self._stream) self._stream.resume()
29847 /***/ (function(module, exports, __webpack_require__) {
29849 // Just get the stats, and then don't do anything.
29850 // You can't really "read" from a socket. You "connect" to it.
29851 // Mostly, this is here so that reading a dir with a socket in it
29852 // doesn't blow up.
29854 module.exports = SocketReader
29856 var inherits = __webpack_require__(66)
29857 var Reader = __webpack_require__(191)
29859 inherits(SocketReader, Reader)
29861 function SocketReader (props) {
29863 if (!(self instanceof SocketReader)) {
29864 throw new Error('SocketReader must be called as constructor.')
29867 if (!(props.type === 'Socket' && props.Socket)) {
29868 throw new Error('Non-socket type ' + props.type)
29871 Reader.call(self, props)
29874 SocketReader.prototype._read = function () {
29876 if (self._paused) return
29877 // basically just a no-op, since we got all the info we have
29878 // from the _stat method
29879 if (!self._ended) {
29889 /***/ (function(module, exports, __webpack_require__) {
29891 // A reader for when we don't yet know what kind of thing
29894 module.exports = ProxyReader
29896 var Reader = __webpack_require__(191)
29897 var getType = __webpack_require__(197)
29898 var inherits = __webpack_require__(66)
29899 var fs = __webpack_require__(192)
29901 inherits(ProxyReader, Reader)
29903 function ProxyReader (props) {
29905 if (!(self instanceof ProxyReader)) {
29906 throw new Error('ProxyReader must be called as constructor.')
29913 Reader.call(self, props)
29916 ProxyReader.prototype._stat = function () {
29918 var props = self.props
29919 // stat the thing to see what the proxy should be.
29920 var stat = props.follow ? 'stat' : 'lstat'
29922 fs[stat](props.path, function (er, current) {
29924 if (er || !current) {
29927 type = getType(current)
29931 props.type = self.type = type
29933 self._old = current
29934 self._addProxy(Reader(props, current))
29938 ProxyReader.prototype._addProxy = function (proxy) {
29940 if (self._proxyTarget) {
29941 return self.error('proxy already set')
29944 self._proxyTarget = proxy
29945 proxy._proxy = self
29959 ].forEach(function (ev) {
29960 // console.error('~~ proxy event', ev, self.path)
29961 proxy.on(ev, self.emit.bind(self, ev))
29964 self.emit('proxy', proxy)
29966 proxy.on('ready', function () {
29967 // console.error("~~ proxy is ready!", self.path)
29972 var calls = self._buffer
29973 self._buffer.length = 0
29974 calls.forEach(function (c) {
29975 proxy[c[0]].apply(proxy, c[1])
29979 ProxyReader.prototype.pause = function () {
29980 return this._proxyTarget ? this._proxyTarget.pause() : false
29983 ProxyReader.prototype.resume = function () {
29984 return this._proxyTarget ? this._proxyTarget.resume() : false
29990 /***/ (function(module, exports, __webpack_require__) {
29992 module.exports = Writer
29994 var fs = __webpack_require__(192)
29995 var inherits = __webpack_require__(66)
29996 var rimraf = __webpack_require__(204)
29997 var mkdir = __webpack_require__(205)
29998 var path = __webpack_require__(2)
29999 var umask = process.platform === 'win32' ? 0 : process.umask()
30000 var getType = __webpack_require__(197)
30001 var Abstract = __webpack_require__(190)
30003 // Must do this *before* loading the child classes
30004 inherits(Writer, Abstract)
30006 Writer.dirmode = parseInt('0777', 8) & (~umask)
30007 Writer.filemode = parseInt('0666', 8) & (~umask)
30009 var DirWriter = __webpack_require__(206)
30010 var LinkWriter = __webpack_require__(208)
30011 var FileWriter = __webpack_require__(209)
30012 var ProxyWriter = __webpack_require__(210)
30014 // props is the desired state. current is optionally the current stat,
30015 // provided here so that subclasses can avoid statting the target
30016 // more than necessary.
30017 function Writer (props, current) {
30020 if (typeof props === 'string') {
30021 props = { path: props }
30025 // call fstream.Writer(dir) to get a DirWriter object, etc.
30026 var type = getType(props)
30027 var ClassType = Writer
30031 ClassType = DirWriter
30034 ClassType = FileWriter
30037 case 'SymbolicLink':
30038 ClassType = LinkWriter
30042 // Don't know yet what type to create, so we wrap in a proxy.
30043 ClassType = ProxyWriter
30047 if (!(self instanceof ClassType)) return new ClassType(props)
30049 // now get down to business.
30051 Abstract.call(self)
30053 if (!props.path) self.error('Must provide a path', null, true)
30055 // props is what we want to set.
30056 // set some convenience properties as well.
30057 self.type = props.type
30059 self.depth = props.depth || 0
30060 self.clobber = props.clobber === false ? props.clobber : true
30061 self.parent = props.parent || null
30062 self.root = props.root || (props.parent && props.parent.root) || self
30064 self._path = self.path = path.resolve(props.path)
30065 if (process.platform === 'win32') {
30066 self.path = self._path = self.path.replace(/\?/g, '_')
30067 if (self._path.length >= 260) {
30068 self._swallowErrors = true
30069 self._path = '\\\\?\\' + self.path.replace(/\//g, '\\')
30072 self.basename = path.basename(props.path)
30073 self.dirname = path.dirname(props.path)
30074 self.linkpath = props.linkpath || null
30076 props.parent = props.root = null
30078 // console.error("\n\n\n%s setting size to", props.path, props.size)
30079 self.size = props.size
30081 if (typeof props.mode === 'string') {
30082 props.mode = parseInt(props.mode, 8)
30085 self.readable = false
30086 self.writable = true
30088 // buffer until ready, or while handling another entry
30092 self.filter = typeof props.filter === 'function' ? props.filter : null
30094 // start the ball rolling.
30095 // this checks what's there already, and then calls
30096 // self._create() to call the impl-specific creation stuff.
30097 self._stat(current)
30100 // Calling this means that it's something we can't create.
30101 // Just assert that it's already there, otherwise raise a warning.
30102 Writer.prototype._create = function () {
30104 fs[self.props.follow ? 'stat' : 'lstat'](self._path, function (er) {
30106 return self.warn('Cannot create ' + self._path + '\n' +
30107 'Unsupported type: ' + self.type, 'ENOTSUP')
30113 Writer.prototype._stat = function (current) {
30115 var props = self.props
30116 var stat = props.follow ? 'stat' : 'lstat'
30117 var who = self._proxy || self
30119 if (current) statCb(null, current)
30120 else fs[stat](self._path, statCb)
30122 function statCb (er, current) {
30123 if (self.filter && !self.filter.call(who, who, current)) {
30124 self._aborted = true
30130 // if it's not there, great. We'll just create it.
30131 // if it is there, then we'll need to change whatever differs
30132 if (er || !current) {
30133 return create(self)
30136 self._old = current
30137 var currentType = getType(current)
30139 // if it's a type change, then we need to clobber or error.
30140 // if it's not a type change, then let the impl take care of it.
30141 if (currentType !== self.type || self.type === 'File' && current.nlink > 1) {
30142 return rimraf(self._path, function (er) {
30143 if (er) return self.error(er)
30149 // otherwise, just handle in the app-specific way
30150 // this creates a fs.WriteStream, or mkdir's, or whatever
30155 function create (self) {
30156 // console.error("W create", self._path, Writer.dirmode)
30158 // XXX Need to clobber non-dirs that are in the way,
30159 // unless { clobber: false } in the props.
30160 mkdir(path.dirname(self._path), Writer.dirmode, function (er, made) {
30161 // console.error("W created", path.dirname(self._path), er)
30162 if (er) return self.error(er)
30164 // later on, we have to set the mode and owner for these
30165 self._madeDir = made
30166 return self._create()
30170 function endChmod (self, want, current, path, cb) {
30171 var wantMode = want.mode
30172 var chmod = want.follow || self.type !== 'SymbolicLink'
30173 ? 'chmod' : 'lchmod'
30175 if (!fs[chmod]) return cb()
30176 if (typeof wantMode !== 'number') return cb()
30178 var curMode = current.mode & parseInt('0777', 8)
30179 wantMode = wantMode & parseInt('0777', 8)
30180 if (wantMode === curMode) return cb()
30182 fs[chmod](path, wantMode, cb)
30185 function endChown (self, want, current, path, cb) {
30186 // Don't even try it unless root. Too easy to EPERM.
30187 if (process.platform === 'win32') return cb()
30188 if (!process.getuid || process.getuid() !== 0) return cb()
30189 if (typeof want.uid !== 'number' &&
30190 typeof want.gid !== 'number') return cb()
30192 if (current.uid === want.uid &&
30193 current.gid === want.gid) return cb()
30195 var chown = (self.props.follow || self.type !== 'SymbolicLink')
30196 ? 'chown' : 'lchown'
30197 if (!fs[chown]) return cb()
30199 if (typeof want.uid !== 'number') want.uid = current.uid
30200 if (typeof want.gid !== 'number') want.gid = current.gid
30202 fs[chown](path, want.uid, want.gid, cb)
30205 function endUtimes (self, want, current, path, cb) {
30206 if (!fs.utimes || process.platform === 'win32') return cb()
30208 var utimes = (want.follow || self.type !== 'SymbolicLink')
30209 ? 'utimes' : 'lutimes'
30211 if (utimes === 'lutimes' && !fs[utimes]) {
30215 if (!fs[utimes]) return cb()
30217 var curA = current.atime
30218 var curM = current.mtime
30219 var meA = want.atime
30220 var meM = want.mtime
30222 if (meA === undefined) meA = curA
30223 if (meM === undefined) meM = curM
30225 if (!isDate(meA)) meA = new Date(meA)
30226 if (!isDate(meM)) meA = new Date(meM)
30228 if (meA.getTime() === curA.getTime() &&
30229 meM.getTime() === curM.getTime()) return cb()
30231 fs[utimes](path, meA, meM, cb)
30234 // XXX This function is beastly. Break it up!
30235 Writer.prototype._finish = function () {
30238 if (self._finishing) return
30239 self._finishing = true
30241 // console.error(" W Finish", self._path, self.size)
30243 // set up all the things.
30244 // At this point, we're already done writing whatever we've gotta write,
30245 // adding files to the dir, etc.
30247 var errState = null
30251 // the times will almost *certainly* have changed.
30252 // adds the utimes syscall, but remove another stat.
30253 self._old.atime = new Date(0)
30254 self._old.mtime = new Date(0)
30255 // console.error(" W Finish Stale Stat", self._path, self.size)
30256 setProps(self._old)
30258 var stat = self.props.follow ? 'stat' : 'lstat'
30259 // console.error(" W Finish Stating", self._path, self.size)
30260 fs[stat](self._path, function (er, current) {
30261 // console.error(" W Finish Stated", self._path, self.size, current)
30263 // if we're in the process of writing out a
30264 // directory, it's very possible that the thing we're linking to
30265 // doesn't exist yet (especially if it was intended as a symlink),
30266 // so swallow ENOENT errors here and just soldier on.
30267 if (er.code === 'ENOENT' &&
30268 (self.type === 'Link' || self.type === 'SymbolicLink') &&
30269 process.platform === 'win32') {
30274 self.end = self._finish = function () {}
30276 } else return self.error(er)
30278 setProps(self._old = current)
30284 function setProps (current) {
30286 endChmod(self, self.props, current, self._path, next('chmod'))
30287 endChown(self, self.props, current, self._path, next('chown'))
30288 endUtimes(self, self.props, current, self._path, next('utimes'))
30291 function next (what) {
30292 return function (er) {
30293 // console.error(" W Finish", what, todo)
30294 if (errState) return
30296 er.fstream_finish_call = what
30297 return self.error(errState = er)
30299 if (--todo > 0) return
30303 // we may still need to set the mode/etc. on some parent dirs
30304 // that were created previously. delay end/close until then.
30305 if (!self._madeDir) return end()
30306 else endMadeDir(self, self._path, end)
30308 function end (er) {
30310 er.fstream_finish_call = 'setupMadeDir'
30311 return self.error(er)
30313 // all the props have been set, so we're completely done.
30321 function endMadeDir (self, p, cb) {
30322 var made = self._madeDir
30323 // everything *between* made and path.dirname(self._path)
30324 // needs to be set up. Note that this may just be one dir.
30325 var d = path.dirname(p)
30327 endMadeDir_(self, d, function (er) {
30328 if (er) return cb(er)
30332 endMadeDir(self, d, cb)
30336 function endMadeDir_ (self, p, cb) {
30338 Object.keys(self.props).forEach(function (k) {
30339 dirProps[k] = self.props[k]
30341 // only make non-readable dirs if explicitly requested.
30342 if (k === 'mode' && self.type !== 'Directory') {
30343 dirProps[k] = dirProps[k] | parseInt('0111', 8)
30348 var errState = null
30349 fs.stat(p, function (er, current) {
30350 if (er) return cb(errState = er)
30351 endChmod(self, dirProps, current, p, next)
30352 endChown(self, dirProps, current, p, next)
30353 endUtimes(self, dirProps, current, p, next)
30356 function next (er) {
30357 if (errState) return
30358 if (er) return cb(errState = er)
30359 if (--todo === 0) return cb()
30363 Writer.prototype.pipe = function () {
30364 this.error("Can't pipe from writable stream")
30367 Writer.prototype.add = function () {
30368 this.error("Can't add to non-Directory type")
30371 Writer.prototype.write = function () {
30375 function objectToString (d) {
30376 return Object.prototype.toString.call(d)
30379 function isDate (d) {
30380 return typeof d === 'object' && objectToString(d) === '[object Date]'
30386 /***/ (function(module, exports, __webpack_require__) {
30388 module.exports = rimraf
30389 rimraf.sync = rimrafSync
30391 var assert = __webpack_require__(58)
30392 var path = __webpack_require__(2)
30393 var fs = __webpack_require__(42)
30394 var glob = undefined
30396 glob = __webpack_require__(59)
30398 // treat glob as optional.
30400 var _0666 = parseInt('666', 8)
30402 var defaultGlobOpts = {
30407 // for EMFILE handling
30410 var isWindows = (process.platform === "win32")
30412 function defaults (options) {
30421 methods.forEach(function(m) {
30422 options[m] = options[m] || fs[m]
30424 options[m] = options[m] || fs[m]
30427 options.maxBusyTries = options.maxBusyTries || 3
30428 options.emfileWait = options.emfileWait || 1000
30429 if (options.glob === false) {
30430 options.disableGlob = true
30432 if (options.disableGlob !== true && glob === undefined) {
30433 throw Error('glob dependency not found, set `options.disableGlob = true` if intentional')
30435 options.disableGlob = options.disableGlob || false
30436 options.glob = options.glob || defaultGlobOpts
30439 function rimraf (p, options, cb) {
30440 if (typeof options === 'function') {
30445 assert(p, 'rimraf: missing path')
30446 assert.equal(typeof p, 'string', 'rimraf: path should be a string')
30447 assert.equal(typeof cb, 'function', 'rimraf: callback function required')
30448 assert(options, 'rimraf: invalid options argument provided')
30449 assert.equal(typeof options, 'object', 'rimraf: options should be object')
30454 var errState = null
30457 if (options.disableGlob || !glob.hasMagic(p))
30458 return afterGlob(null, [p])
30460 options.lstat(p, function (er, stat) {
30462 return afterGlob(null, [p])
30464 glob(p, options.glob, afterGlob)
30467 function next (er) {
30468 errState = errState || er
30473 function afterGlob (er, results) {
30481 results.forEach(function (p) {
30482 rimraf_(p, options, function CB (er) {
30484 if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") &&
30485 busyTries < options.maxBusyTries) {
30487 var time = busyTries * 100
30488 // try again, with the same exact callback as this one.
30489 return setTimeout(function () {
30490 rimraf_(p, options, CB)
30494 // this one won't happen if graceful-fs is used.
30495 if (er.code === "EMFILE" && timeout < options.emfileWait) {
30496 return setTimeout(function () {
30497 rimraf_(p, options, CB)
30502 if (er.code === "ENOENT") er = null
30512 // Two possible strategies.
30513 // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
30514 // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
30516 // Both result in an extra syscall when you guess wrong. However, there
30517 // are likely far more normal files in the world than directories. This
30518 // is based on the assumption that a the average number of files per
30519 // directory is >= 1.
30521 // If anyone ever complains about this, then I guess the strategy could
30522 // be made configurable somehow. But until then, YAGNI.
30523 function rimraf_ (p, options, cb) {
30526 assert(typeof cb === 'function')
30528 // sunos lets the root user unlink directories, which is... weird.
30529 // so we have to lstat here and make sure it's not a dir.
30530 options.lstat(p, function (er, st) {
30531 if (er && er.code === "ENOENT")
30534 // Windows can EPERM on stat. Life is suffering.
30535 if (er && er.code === "EPERM" && isWindows)
30536 fixWinEPERM(p, options, er, cb)
30538 if (st && st.isDirectory())
30539 return rmdir(p, options, er, cb)
30541 options.unlink(p, function (er) {
30543 if (er.code === "ENOENT")
30545 if (er.code === "EPERM")
30547 ? fixWinEPERM(p, options, er, cb)
30548 : rmdir(p, options, er, cb)
30549 if (er.code === "EISDIR")
30550 return rmdir(p, options, er, cb)
30557 function fixWinEPERM (p, options, er, cb) {
30560 assert(typeof cb === 'function')
30562 assert(er instanceof Error)
30564 options.chmod(p, _0666, function (er2) {
30566 cb(er2.code === "ENOENT" ? null : er)
30568 options.stat(p, function(er3, stats) {
30570 cb(er3.code === "ENOENT" ? null : er)
30571 else if (stats.isDirectory())
30572 rmdir(p, options, er, cb)
30574 options.unlink(p, cb)
30579 function fixWinEPERMSync (p, options, er) {
30583 assert(er instanceof Error)
30586 options.chmodSync(p, _0666)
30588 if (er2.code === "ENOENT")
30595 var stats = options.statSync(p)
30597 if (er3.code === "ENOENT")
30603 if (stats.isDirectory())
30604 rmdirSync(p, options, er)
30606 options.unlinkSync(p)
30609 function rmdir (p, options, originalEr, cb) {
30613 assert(originalEr instanceof Error)
30614 assert(typeof cb === 'function')
30616 // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
30617 // if we guessed wrong, and it's not a directory, then
30618 // raise the original error.
30619 options.rmdir(p, function (er) {
30620 if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
30621 rmkids(p, options, cb)
30622 else if (er && er.code === "ENOTDIR")
30629 function rmkids(p, options, cb) {
30632 assert(typeof cb === 'function')
30634 options.readdir(p, function (er, files) {
30637 var n = files.length
30639 return options.rmdir(p, cb)
30641 files.forEach(function (f) {
30642 rimraf(path.join(p, f), options, function (er) {
30646 return cb(errState = er)
30648 options.rmdir(p, cb)
30654 // this looks simpler, and is strictly *faster*, but will
30655 // tie up the JavaScript thread and fail on excessively
30656 // deep directory trees.
30657 function rimrafSync (p, options) {
30658 options = options || {}
30661 assert(p, 'rimraf: missing path')
30662 assert.equal(typeof p, 'string', 'rimraf: path should be a string')
30663 assert(options, 'rimraf: missing options')
30664 assert.equal(typeof options, 'object', 'rimraf: options should be object')
30668 if (options.disableGlob || !glob.hasMagic(p)) {
30672 options.lstatSync(p)
30675 results = glob.sync(p, options.glob)
30679 if (!results.length)
30682 for (var i = 0; i < results.length; i++) {
30686 var st = options.lstatSync(p)
30688 if (er.code === "ENOENT")
30691 // Windows can EPERM on stat. Life is suffering.
30692 if (er.code === "EPERM" && isWindows)
30693 fixWinEPERMSync(p, options, er)
30697 // sunos lets the root user unlink directories, which is... weird.
30698 if (st && st.isDirectory())
30699 rmdirSync(p, options, null)
30701 options.unlinkSync(p)
30703 if (er.code === "ENOENT")
30705 if (er.code === "EPERM")
30706 return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
30707 if (er.code !== "EISDIR")
30710 rmdirSync(p, options, er)
30715 function rmdirSync (p, options, originalEr) {
30719 assert(originalEr instanceof Error)
30722 options.rmdirSync(p)
30724 if (er.code === "ENOENT")
30726 if (er.code === "ENOTDIR")
30728 if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
30729 rmkidsSync(p, options)
30733 function rmkidsSync (p, options) {
30736 options.readdirSync(p).forEach(function (f) {
30737 rimrafSync(path.join(p, f), options)
30740 // We only end up here once we got ENOTEMPTY at least once, and
30741 // at this point, we are guaranteed to have removed all the kids.
30742 // So, we know that it won't be ENOENT or ENOTDIR or anything else.
30743 // try really hard to delete stuff on windows, because it has a
30744 // PROFOUNDLY annoying habit of not closing handles promptly when
30745 // files are deleted, resulting in spurious ENOTEMPTY errors.
30746 var retries = isWindows ? 100 : 1
30751 var ret = options.rmdirSync(p, options)
30755 if (++i < retries && threw)
30764 /***/ (function(module, exports, __webpack_require__) {
30766 var path = __webpack_require__(2);
30767 var fs = __webpack_require__(42);
30768 var _0777 = parseInt('0777', 8);
30770 module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
30772 function mkdirP (p, opts, f, made) {
30773 if (typeof opts === 'function') {
30777 else if (!opts || typeof opts !== 'object') {
30778 opts = { mode: opts };
30781 var mode = opts.mode;
30782 var xfs = opts.fs || fs;
30784 if (mode === undefined) {
30787 if (!made) made = null;
30789 var cb = f || function () {};
30790 p = path.resolve(p);
30792 xfs.mkdir(p, mode, function (er) {
30795 return cb(null, made);
30799 if (path.dirname(p) === p) return cb(er);
30800 mkdirP(path.dirname(p), opts, function (er, made) {
30801 if (er) cb(er, made);
30802 else mkdirP(p, opts, cb, made);
30806 // In the case of any other error, just see if there's a dir
30807 // there already. If so, then hooray! If not, then something
30810 xfs.stat(p, function (er2, stat) {
30811 // if the stat fails, then that's super weird.
30812 // let the original error be the failure reason.
30813 if (er2 || !stat.isDirectory()) cb(er, made)
30814 else cb(null, made);
30821 mkdirP.sync = function sync (p, opts, made) {
30822 if (!opts || typeof opts !== 'object') {
30823 opts = { mode: opts };
30826 var mode = opts.mode;
30827 var xfs = opts.fs || fs;
30829 if (mode === undefined) {
30832 if (!made) made = null;
30834 p = path.resolve(p);
30837 xfs.mkdirSync(p, mode);
30841 switch (err0.code) {
30843 made = sync(path.dirname(p), opts, made);
30844 sync(p, opts, made);
30847 // In the case of any other error, just see if there's a dir
30848 // there already. If so, then hooray! If not, then something
30853 stat = xfs.statSync(p);
30858 if (!stat.isDirectory()) throw err0;
30869 /***/ (function(module, exports, __webpack_require__) {
30871 // It is expected that, when .add() returns false, the consumer
30872 // of the DirWriter will pause until a "drain" event occurs. Note
30873 // that this is *almost always going to be the case*, unless the
30874 // thing being written is some sort of unsupported type, and thus
30877 module.exports = DirWriter
30879 var Writer = __webpack_require__(203)
30880 var inherits = __webpack_require__(66)
30881 var mkdir = __webpack_require__(205)
30882 var path = __webpack_require__(2)
30883 var collect = __webpack_require__(207)
30885 inherits(DirWriter, Writer)
30887 function DirWriter (props) {
30889 if (!(self instanceof DirWriter)) {
30890 self.error('DirWriter must be called as constructor.', null, true)
30893 // should already be established as a Directory type
30894 if (props.type !== 'Directory' || !props.Directory) {
30895 self.error('Non-directory type ' + props.type + ' ' +
30896 JSON.stringify(props), null, true)
30899 Writer.call(this, props)
30902 DirWriter.prototype._create = function () {
30904 mkdir(self._path, Writer.dirmode, function (er) {
30905 if (er) return self.error(er)
30906 // ready to start getting entries!
30913 // a DirWriter has an add(entry) method, but its .write() doesn't
30914 // do anything. Why a no-op rather than a throw? Because this
30915 // leaves open the door for writing directory metadata for
30916 // gnu/solaris style dumpdirs.
30917 DirWriter.prototype.write = function () {
30921 DirWriter.prototype.end = function () {
30926 DirWriter.prototype.add = function (entry) {
30929 // console.error('\tadd', entry._path, '->', self._path)
30931 if (!self.ready || self._currentEntry) {
30932 self._buffer.push(entry)
30936 // create a new writer, and pipe the incoming entry into it.
30938 return self.error('add after end')
30941 self._buffer.push(entry)
30944 return this._buffer.length === 0
30947 DirWriter.prototype._process = function () {
30950 // console.error('DW Process p=%j', self._processing, self.basename)
30952 if (self._processing) return
30954 var entry = self._buffer.shift()
30956 // console.error("DW Drain")
30958 if (self._ended) self._finish()
30962 self._processing = true
30963 // console.error("DW Entry", entry._path)
30965 self.emit('entry', entry)
30967 // ok, add this entry
30969 // don't allow recursive copying
30973 pp = p._path || p.path
30974 if (pp === self.root._path || pp === self._path ||
30975 (pp && pp.indexOf(self._path) === 0)) {
30976 // console.error('DW Exit (recursive)', entry.basename, self._path)
30977 self._processing = false
30978 if (entry._collected) entry.pipe()
30979 return self._process()
30984 // console.error("DW not recursive")
30986 // chop off the entry's root dir, replace with ours
30989 root: self.root || self,
30991 depth: self.depth + 1
30994 pp = entry._path || entry.path || entry.props.path
30995 if (entry.parent) {
30996 pp = pp.substr(entry.parent._path.length + 1)
30998 // get rid of any ../../ shenanigans
30999 props.path = path.join(self.path, path.join('/', pp))
31001 // if i have a filter, the child should inherit it.
31002 props.filter = self.filter
31004 // all the rest of the stuff, copy over from the source.
31005 Object.keys(entry.props).forEach(function (k) {
31006 if (!props.hasOwnProperty(k)) {
31007 props[k] = entry.props[k]
31011 // not sure at this point what kind of writer this is.
31012 var child = self._currentChild = new Writer(props)
31013 child.on('ready', function () {
31014 // console.error("DW Child Ready", child.type, child._path)
31015 // console.error(" resuming", entry._path)
31020 // XXX Make this work in node.
31021 // Long filenames should not break stuff.
31022 child.on('error', function (er) {
31023 if (child._swallowErrors) {
31026 child.emit('close')
31028 self.emit('error', er)
31032 // we fire _end internally *after* end, so that we don't move on
31033 // until any "end" listeners have had their chance to do stuff.
31034 child.on('close', onend)
31036 function onend () {
31039 // console.error("* DW Child end", child.basename)
31040 self._currentChild = null
31041 self._processing = false
31049 /***/ (function(module, exports) {
31051 module.exports = collect
31053 function collect (stream) {
31054 if (stream._collected) return
31056 if (stream._paused) return stream.on('resume', collect.bind(null, stream))
31058 stream._collected = true
31061 stream.on('data', save)
31062 stream.on('end', save)
31064 function save (b) {
31065 if (typeof b === 'string') b = new Buffer(b)
31066 if (Buffer.isBuffer(b) && !b.length) return
31070 stream.on('entry', saveEntry)
31071 var entryBuffer = []
31072 function saveEntry (e) {
31074 entryBuffer.push(e)
31077 stream.on('proxy', proxyPause)
31078 function proxyPause (p) {
31082 // replace the pipe method with a new version that will
31083 // unlock the buffered stuff. if you just call .pipe()
31084 // without a destination, then it'll re-play the events.
31085 stream.pipe = (function (orig) {
31086 return function (dest) {
31087 // console.error(' === open the pipes', dest && dest.path)
31089 // let the entries flow through one at a time.
31090 // Once they're all done, then we can resume completely.
31092 ;(function unblockEntry () {
31093 var entry = entryBuffer[e++]
31094 // console.error(" ==== unblock entry", entry && entry.path)
31095 if (!entry) return resume()
31096 entry.on('end', unblockEntry)
31097 if (dest) dest.add(entry)
31098 else stream.emit('entry', entry)
31101 function resume () {
31102 stream.removeListener('entry', saveEntry)
31103 stream.removeListener('data', save)
31104 stream.removeListener('end', save)
31107 if (dest) stream.pipe(dest)
31109 buf.forEach(function (b) {
31110 if (b) stream.emit('data', b)
31111 else stream.emit('end')
31125 /***/ (function(module, exports, __webpack_require__) {
31127 module.exports = LinkWriter
31129 var fs = __webpack_require__(192)
31130 var Writer = __webpack_require__(203)
31131 var inherits = __webpack_require__(66)
31132 var path = __webpack_require__(2)
31133 var rimraf = __webpack_require__(204)
31135 inherits(LinkWriter, Writer)
31137 function LinkWriter (props) {
31139 if (!(self instanceof LinkWriter)) {
31140 throw new Error('LinkWriter must be called as constructor.')
31143 // should already be established as a Link type
31144 if (!((props.type === 'Link' && props.Link) ||
31145 (props.type === 'SymbolicLink' && props.SymbolicLink))) {
31146 throw new Error('Non-link type ' + props.type)
31149 if (props.linkpath === '') props.linkpath = '.'
31150 if (!props.linkpath) {
31151 self.error('Need linkpath property to create ' + props.type)
31154 Writer.call(this, props)
31157 LinkWriter.prototype._create = function () {
31158 // console.error(" LW _create")
31160 var hard = self.type === 'Link' || process.platform === 'win32'
31161 var link = hard ? 'link' : 'symlink'
31162 var lp = hard ? path.resolve(self.dirname, self.linkpath) : self.linkpath
31164 // can only change the link path by clobbering
31165 // For hard links, let's just assume that's always the case, since
31166 // there's no good way to read them if we don't already know.
31167 if (hard) return clobber(self, lp, link)
31169 fs.readlink(self._path, function (er, p) {
31170 // only skip creation if it's exactly the same link
31171 if (p && p === lp) return finish(self)
31172 clobber(self, lp, link)
31176 function clobber (self, lp, link) {
31177 rimraf(self._path, function (er) {
31178 if (er) return self.error(er)
31179 create(self, lp, link)
31183 function create (self, lp, link) {
31184 fs[link](lp, self._path, function (er) {
31185 // if this is a hard link, and we're in the process of writing out a
31186 // directory, it's very possible that the thing we're linking to
31187 // doesn't exist yet (especially if it was intended as a symlink),
31188 // so swallow ENOENT errors here and just soldier in.
31189 // Additionally, an EPERM or EACCES can happen on win32 if it's trying
31190 // to make a link to a directory. Again, just skip it.
31191 // A better solution would be to have fs.symlink be supported on
31192 // windows in some nice fashion.
31194 if ((er.code === 'ENOENT' ||
31195 er.code === 'EACCES' ||
31196 er.code === 'EPERM') && process.platform === 'win32') {
31201 self.end = self._finish = function () {}
31202 } else return self.error(er)
31208 function finish (self) {
31211 if (self._ended && !self._finished) self._finish()
31214 LinkWriter.prototype.end = function () {
31215 // console.error("LW finish in end")
31218 this._finished = true
31226 /***/ (function(module, exports, __webpack_require__) {
31228 module.exports = FileWriter
31230 var fs = __webpack_require__(192)
31231 var Writer = __webpack_require__(203)
31232 var inherits = __webpack_require__(66)
31235 inherits(FileWriter, Writer)
31237 function FileWriter (props) {
31239 if (!(self instanceof FileWriter)) {
31240 throw new Error('FileWriter must be called as constructor.')
31243 // should already be established as a File type
31244 if (props.type !== 'File' || !props.File) {
31245 throw new Error('Non-file type ' + props.type)
31249 self._bytesWritten = 0
31251 Writer.call(this, props)
31254 FileWriter.prototype._create = function () {
31256 if (self._stream) return
31259 if (self.props.flags) so.flags = self.props.flags
31260 so.mode = Writer.filemode
31261 if (self._old && self._old.blksize) so.bufferSize = self._old.blksize
31263 self._stream = fs.createWriteStream(self._path, so)
31265 self._stream.on('open', function () {
31266 // console.error("FW open", self._buffer, self._path)
31268 self._buffer.forEach(function (c) {
31269 if (c === EOF) self._stream.end()
31270 else self._stream.write(c)
31273 // give this a kick just in case it needs it.
31277 self._stream.on('error', function (er) { self.emit('error', er) })
31279 self._stream.on('drain', function () { self.emit('drain') })
31281 self._stream.on('close', function () {
31282 // console.error('\n\nFW Stream Close', self._path, self.size)
31287 FileWriter.prototype.write = function (c) {
31290 self._bytesWritten += c.length
31293 if (!Buffer.isBuffer(c) && typeof c !== 'string') {
31294 throw new Error('invalid write data')
31296 self._buffer.push(c)
31300 var ret = self._stream.write(c)
31301 // console.error('\t-- fw wrote, _stream says', ret, self._stream._queue.length)
31303 // allow 2 buffered writes, because otherwise there's just too
31304 // much stop and go bs.
31305 if (ret === false && self._stream._queue) {
31306 return self._stream._queue.length <= 2
31312 FileWriter.prototype.end = function (c) {
31315 if (c) self.write(c)
31318 self._buffer.push(EOF)
31322 return self._stream.end()
31325 FileWriter.prototype._finish = function () {
31327 if (typeof self.size === 'number' && self._bytesWritten !== self.size) {
31329 'Did not get expected byte count.\n' +
31330 'expect: ' + self.size + '\n' +
31331 'actual: ' + self._bytesWritten)
31333 Writer.prototype._finish.call(self)
31339 /***/ (function(module, exports, __webpack_require__) {
31341 // A writer for when we don't know what kind of thing
31342 // the thing is. That is, it's not explicitly set,
31343 // so we're going to make it whatever the thing already
31346 // Until then, collect all events.
31348 module.exports = ProxyWriter
31350 var Writer = __webpack_require__(203)
31351 var getType = __webpack_require__(197)
31352 var inherits = __webpack_require__(66)
31353 var collect = __webpack_require__(207)
31354 var fs = __webpack_require__(42)
31356 inherits(ProxyWriter, Writer)
31358 function ProxyWriter (props) {
31360 if (!(self instanceof ProxyWriter)) {
31361 throw new Error('ProxyWriter must be called as constructor.')
31365 self._needDrain = false
31367 Writer.call(self, props)
31370 ProxyWriter.prototype._stat = function () {
31372 var props = self.props
31373 // stat the thing to see what the proxy should be.
31374 var stat = props.follow ? 'stat' : 'lstat'
31376 fs[stat](props.path, function (er, current) {
31378 if (er || !current) {
31381 type = getType(current)
31385 props.type = self.type = type
31387 self._old = current
31388 self._addProxy(Writer(props, current))
31392 ProxyWriter.prototype._addProxy = function (proxy) {
31393 // console.error("~~ set proxy", this.path)
31396 return self.error('proxy already set')
31399 self._proxy = proxy
31407 ].forEach(function (ev) {
31408 proxy.on(ev, self.emit.bind(self, ev))
31411 self.emit('proxy', proxy)
31413 var calls = self._buffer
31414 calls.forEach(function (c) {
31415 // console.error("~~ ~~ proxy buffered call", c[0], c[1])
31416 proxy[c[0]].apply(proxy, c[1])
31418 self._buffer.length = 0
31419 if (self._needsDrain) self.emit('drain')
31422 ProxyWriter.prototype.add = function (entry) {
31423 // console.error("~~ proxy add")
31426 if (!this._proxy) {
31427 this._buffer.push(['add', [entry]])
31428 this._needDrain = true
31431 return this._proxy.add(entry)
31434 ProxyWriter.prototype.write = function (c) {
31435 // console.error('~~ proxy write')
31436 if (!this._proxy) {
31437 this._buffer.push(['write', [c]])
31438 this._needDrain = true
31441 return this._proxy.write(c)
31444 ProxyWriter.prototype.end = function (c) {
31445 // console.error('~~ proxy end')
31446 if (!this._proxy) {
31447 this._buffer.push(['end', [c]])
31450 return this._proxy.end(c)
31456 /***/ (function(module, exports, __webpack_require__) {
31458 var fs = __webpack_require__(212);
31459 var Promise = __webpack_require__(128);
31460 var directory = __webpack_require__(216);
31461 var Stream = __webpack_require__(44);
31463 // Backwards compatibility for node versions < 8
31464 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
31465 Stream = __webpack_require__(167);
31468 buffer: function(buffer, options) {
31470 stream: function(offset, length) {
31471 var stream = Stream.PassThrough();
31472 stream.end(buffer.slice(offset, length));
31476 return Promise.resolve(buffer.length);
31479 return directory(source, options);
31481 file: function(filename, options) {
31483 stream: function(offset,length) {
31484 return fs.createReadStream(filename,{start: offset, end: length && offset+length});
31487 return new Promise(function(resolve,reject) {
31488 fs.stat(filename,function(err,d) {
31497 return directory(source, options);
31500 url: function(request, params, options) {
31501 if (typeof params === 'string')
31502 params = {url: params};
31504 throw 'URL missing';
31505 params.headers = params.headers || {};
31508 stream : function(offset,length) {
31509 var options = Object.create(params);
31510 options.headers = Object.create(params.headers);
31511 options.headers.range = 'bytes='+offset+'-' + (length ? length : '');
31512 return request(options);
31515 return new Promise(function(resolve,reject) {
31516 var req = request(params);
31517 req.on('response',function(d) {
31519 if (!d.headers['content-length'])
31520 reject(new Error('Missing content length header'));
31522 resolve(d.headers['content-length']);
31523 }).on('error',reject);
31528 return directory(source, options);
31531 s3 : function(client,params, options) {
31534 return new Promise(function(resolve,reject) {
31535 client.headObject(params, function(err,d) {
31539 resolve(d.ContentLength);
31543 stream: function(offset,length) {
31545 for (var key in params)
31546 d[key] = params[key];
31547 d.Range = 'bytes='+offset+'-' + (length ? length : '');
31548 return client.getObject(d).createReadStream();
31552 return directory(source, options);
31559 /***/ (function(module, exports, __webpack_require__) {
31561 var fs = __webpack_require__(42)
31562 var polyfills = __webpack_require__(213)
31563 var legacy = __webpack_require__(214)
31564 var clone = __webpack_require__(215)
31566 var util = __webpack_require__(50)
31568 /* istanbul ignore next - node 0.x polyfill */
31572 /* istanbul ignore else - node 0.x polyfill */
31573 if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
31574 gracefulQueue = Symbol.for('graceful-fs.queue')
31575 // This is used in testing by future versions
31576 previousSymbol = Symbol.for('graceful-fs.previous')
31578 gracefulQueue = '___graceful-fs.queue'
31579 previousSymbol = '___graceful-fs.previous'
31582 function noop () {}
31584 function publishQueue(context, queue) {
31585 Object.defineProperty(context, gracefulQueue, {
31594 debug = util.debuglog('gfs4')
31595 else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
31596 debug = function() {
31597 var m = util.format.apply(util, arguments)
31598 m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
31602 // Once time initialization
31603 if (!fs[gracefulQueue]) {
31604 // This queue can be shared by multiple loaded instances
31605 var queue = global[gracefulQueue] || []
31606 publishQueue(fs, queue)
31608 // Patch fs.close/closeSync to shared queue version, because we need
31609 // to retry() whenever a close happens *anywhere* in the program.
31610 // This is essential when multiple graceful-fs instances are
31611 // in play at the same time.
31612 fs.close = (function (fs$close) {
31613 function close (fd, cb) {
31614 return fs$close.call(fs, fd, function (err) {
31615 // This function uses the graceful-fs shared queue
31620 if (typeof cb === 'function')
31621 cb.apply(this, arguments)
31625 Object.defineProperty(close, previousSymbol, {
31631 fs.closeSync = (function (fs$closeSync) {
31632 function closeSync (fd) {
31633 // This function uses the graceful-fs shared queue
31634 fs$closeSync.apply(fs, arguments)
31638 Object.defineProperty(closeSync, previousSymbol, {
31639 value: fs$closeSync
31644 if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
31645 process.on('exit', function() {
31646 debug(fs[gracefulQueue])
31647 __webpack_require__(58).equal(fs[gracefulQueue].length, 0)
31652 if (!global[gracefulQueue]) {
31653 publishQueue(global, fs[gracefulQueue]);
31656 module.exports = patch(clone(fs))
31657 if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
31658 module.exports = patch(fs)
31659 fs.__patched = true;
31662 function patch (fs) {
31663 // Everything that references the open() function needs to be in here
31665 fs.gracefulify = patch
31667 fs.createReadStream = createReadStream
31668 fs.createWriteStream = createWriteStream
31669 var fs$readFile = fs.readFile
31670 fs.readFile = readFile
31671 function readFile (path, options, cb) {
31672 if (typeof options === 'function')
31673 cb = options, options = null
31675 return go$readFile(path, options, cb)
31677 function go$readFile (path, options, cb) {
31678 return fs$readFile(path, options, function (err) {
31679 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
31680 enqueue([go$readFile, [path, options, cb]])
31682 if (typeof cb === 'function')
31683 cb.apply(this, arguments)
31690 var fs$writeFile = fs.writeFile
31691 fs.writeFile = writeFile
31692 function writeFile (path, data, options, cb) {
31693 if (typeof options === 'function')
31694 cb = options, options = null
31696 return go$writeFile(path, data, options, cb)
31698 function go$writeFile (path, data, options, cb) {
31699 return fs$writeFile(path, data, options, function (err) {
31700 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
31701 enqueue([go$writeFile, [path, data, options, cb]])
31703 if (typeof cb === 'function')
31704 cb.apply(this, arguments)
31711 var fs$appendFile = fs.appendFile
31713 fs.appendFile = appendFile
31714 function appendFile (path, data, options, cb) {
31715 if (typeof options === 'function')
31716 cb = options, options = null
31718 return go$appendFile(path, data, options, cb)
31720 function go$appendFile (path, data, options, cb) {
31721 return fs$appendFile(path, data, options, function (err) {
31722 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
31723 enqueue([go$appendFile, [path, data, options, cb]])
31725 if (typeof cb === 'function')
31726 cb.apply(this, arguments)
31733 var fs$readdir = fs.readdir
31734 fs.readdir = readdir
31735 function readdir (path, options, cb) {
31737 if (typeof options !== 'function') {
31742 args.push(go$readdir$cb)
31744 return go$readdir(args)
31746 function go$readdir$cb (err, files) {
31747 if (files && files.sort)
31750 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
31751 enqueue([go$readdir, [args]])
31754 if (typeof cb === 'function')
31755 cb.apply(this, arguments)
31761 function go$readdir (args) {
31762 return fs$readdir.apply(fs, args)
31765 if (process.version.substr(0, 4) === 'v0.8') {
31766 var legStreams = legacy(fs)
31767 ReadStream = legStreams.ReadStream
31768 WriteStream = legStreams.WriteStream
31771 var fs$ReadStream = fs.ReadStream
31772 if (fs$ReadStream) {
31773 ReadStream.prototype = Object.create(fs$ReadStream.prototype)
31774 ReadStream.prototype.open = ReadStream$open
31777 var fs$WriteStream = fs.WriteStream
31778 if (fs$WriteStream) {
31779 WriteStream.prototype = Object.create(fs$WriteStream.prototype)
31780 WriteStream.prototype.open = WriteStream$open
31783 Object.defineProperty(fs, 'ReadStream', {
31787 set: function (val) {
31793 Object.defineProperty(fs, 'WriteStream', {
31797 set: function (val) {
31805 var FileReadStream = ReadStream
31806 Object.defineProperty(fs, 'FileReadStream', {
31808 return FileReadStream
31810 set: function (val) {
31811 FileReadStream = val
31816 var FileWriteStream = WriteStream
31817 Object.defineProperty(fs, 'FileWriteStream', {
31819 return FileWriteStream
31821 set: function (val) {
31822 FileWriteStream = val
31828 function ReadStream (path, options) {
31829 if (this instanceof ReadStream)
31830 return fs$ReadStream.apply(this, arguments), this
31832 return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
31835 function ReadStream$open () {
31837 open(that.path, that.flags, that.mode, function (err, fd) {
31839 if (that.autoClose)
31842 that.emit('error', err)
31845 that.emit('open', fd)
31851 function WriteStream (path, options) {
31852 if (this instanceof WriteStream)
31853 return fs$WriteStream.apply(this, arguments), this
31855 return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
31858 function WriteStream$open () {
31860 open(that.path, that.flags, that.mode, function (err, fd) {
31863 that.emit('error', err)
31866 that.emit('open', fd)
31871 function createReadStream (path, options) {
31872 return new fs.ReadStream(path, options)
31875 function createWriteStream (path, options) {
31876 return new fs.WriteStream(path, options)
31879 var fs$open = fs.open
31881 function open (path, flags, mode, cb) {
31882 if (typeof mode === 'function')
31883 cb = mode, mode = null
31885 return go$open(path, flags, mode, cb)
31887 function go$open (path, flags, mode, cb) {
31888 return fs$open(path, flags, mode, function (err, fd) {
31889 if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
31890 enqueue([go$open, [path, flags, mode, cb]])
31892 if (typeof cb === 'function')
31893 cb.apply(this, arguments)
31903 function enqueue (elem) {
31904 debug('ENQUEUE', elem[0].name, elem[1])
31905 fs[gracefulQueue].push(elem)
31908 function retry () {
31909 var elem = fs[gracefulQueue].shift()
31911 debug('RETRY', elem[0].name, elem[1])
31912 elem[0].apply(null, elem[1])
31919 /***/ (function(module, exports, __webpack_require__) {
31921 var constants = __webpack_require__(194)
31923 var origCwd = process.cwd
31926 var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform
31928 process.cwd = function() {
31930 cwd = origCwd.call(process)
31937 var chdir = process.chdir
31938 process.chdir = function(d) {
31940 chdir.call(process, d)
31943 module.exports = patch
31945 function patch (fs) {
31946 // (re-)implement some things that are known busted or missing.
31948 // lchmod, broken prior to 0.6.2
31949 // back-port the fix here.
31950 if (constants.hasOwnProperty('O_SYMLINK') &&
31951 process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
31955 // lutimes implementation, or no-op
31960 // https://github.com/isaacs/node-graceful-fs/issues/4
31961 // Chown should not fail on einval or eperm if non-root.
31962 // It should not fail on enosys ever, as this just indicates
31963 // that a fs doesn't support the intended operation.
31965 fs.chown = chownFix(fs.chown)
31966 fs.fchown = chownFix(fs.fchown)
31967 fs.lchown = chownFix(fs.lchown)
31969 fs.chmod = chmodFix(fs.chmod)
31970 fs.fchmod = chmodFix(fs.fchmod)
31971 fs.lchmod = chmodFix(fs.lchmod)
31973 fs.chownSync = chownFixSync(fs.chownSync)
31974 fs.fchownSync = chownFixSync(fs.fchownSync)
31975 fs.lchownSync = chownFixSync(fs.lchownSync)
31977 fs.chmodSync = chmodFixSync(fs.chmodSync)
31978 fs.fchmodSync = chmodFixSync(fs.fchmodSync)
31979 fs.lchmodSync = chmodFixSync(fs.lchmodSync)
31981 fs.stat = statFix(fs.stat)
31982 fs.fstat = statFix(fs.fstat)
31983 fs.lstat = statFix(fs.lstat)
31985 fs.statSync = statFixSync(fs.statSync)
31986 fs.fstatSync = statFixSync(fs.fstatSync)
31987 fs.lstatSync = statFixSync(fs.lstatSync)
31989 // if lchmod/lchown do not exist, then make them no-ops
31991 fs.lchmod = function (path, mode, cb) {
31992 if (cb) process.nextTick(cb)
31994 fs.lchmodSync = function () {}
31997 fs.lchown = function (path, uid, gid, cb) {
31998 if (cb) process.nextTick(cb)
32000 fs.lchownSync = function () {}
32003 // on Windows, A/V software can lock the directory, causing this
32004 // to fail with an EACCES or EPERM if the directory contains newly
32005 // created files. Try again on failure, for up to 60 seconds.
32007 // Set the timeout this long because some Windows Anti-Virus, such as Parity
32008 // bit9, may lock files for up to a minute, causing npm package install
32009 // failures. Also, take care to yield the scheduler. Windows scheduling gives
32010 // CPU to a busy looping process, which can cause the program causing the lock
32011 // contention to be starved of CPU by node, so the contention doesn't resolve.
32012 if (platform === "win32") {
32013 fs.rename = (function (fs$rename) { return function (from, to, cb) {
32014 var start = Date.now()
32016 fs$rename(from, to, function CB (er) {
32018 && (er.code === "EACCES" || er.code === "EPERM")
32019 && Date.now() - start < 60000) {
32020 setTimeout(function() {
32021 fs.stat(to, function (stater, st) {
32022 if (stater && stater.code === "ENOENT")
32023 fs$rename(from, to, CB);
32037 // if read() returns EAGAIN, then just try it again.
32038 fs.read = (function (fs$read) {
32039 function read (fd, buffer, offset, length, position, callback_) {
32041 if (callback_ && typeof callback_ === 'function') {
32043 callback = function (er, _, __) {
32044 if (er && er.code === 'EAGAIN' && eagCounter < 10) {
32046 return fs$read.call(fs, fd, buffer, offset, length, position, callback)
32048 callback_.apply(this, arguments)
32051 return fs$read.call(fs, fd, buffer, offset, length, position, callback)
32054 // This ensures `util.promisify` works as it does for native `fs.read`.
32055 read.__proto__ = fs$read
32059 fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
32063 return fs$readSync.call(fs, fd, buffer, offset, length, position)
32065 if (er.code === 'EAGAIN' && eagCounter < 10) {
32074 function patchLchmod (fs) {
32075 fs.lchmod = function (path, mode, callback) {
32077 , constants.O_WRONLY | constants.O_SYMLINK
32079 , function (err, fd) {
32081 if (callback) callback(err)
32084 // prefer to return the chmod error, if one occurs,
32085 // but still try to close, and report closing errors if they occur.
32086 fs.fchmod(fd, mode, function (err) {
32087 fs.close(fd, function(err2) {
32088 if (callback) callback(err || err2)
32094 fs.lchmodSync = function (path, mode) {
32095 var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
32097 // prefer to return the chmod error, if one occurs,
32098 // but still try to close, and report closing errors if they occur.
32102 ret = fs.fchmodSync(fd, mode)
32117 function patchLutimes (fs) {
32118 if (constants.hasOwnProperty("O_SYMLINK")) {
32119 fs.lutimes = function (path, at, mt, cb) {
32120 fs.open(path, constants.O_SYMLINK, function (er, fd) {
32125 fs.futimes(fd, at, mt, function (er) {
32126 fs.close(fd, function (er2) {
32127 if (cb) cb(er || er2)
32133 fs.lutimesSync = function (path, at, mt) {
32134 var fd = fs.openSync(path, constants.O_SYMLINK)
32138 ret = fs.futimesSync(fd, at, mt)
32153 fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
32154 fs.lutimesSync = function () {}
32158 function chmodFix (orig) {
32159 if (!orig) return orig
32160 return function (target, mode, cb) {
32161 return orig.call(fs, target, mode, function (er) {
32162 if (chownErOk(er)) er = null
32163 if (cb) cb.apply(this, arguments)
32168 function chmodFixSync (orig) {
32169 if (!orig) return orig
32170 return function (target, mode) {
32172 return orig.call(fs, target, mode)
32174 if (!chownErOk(er)) throw er
32180 function chownFix (orig) {
32181 if (!orig) return orig
32182 return function (target, uid, gid, cb) {
32183 return orig.call(fs, target, uid, gid, function (er) {
32184 if (chownErOk(er)) er = null
32185 if (cb) cb.apply(this, arguments)
32190 function chownFixSync (orig) {
32191 if (!orig) return orig
32192 return function (target, uid, gid) {
32194 return orig.call(fs, target, uid, gid)
32196 if (!chownErOk(er)) throw er
32201 function statFix (orig) {
32202 if (!orig) return orig
32203 // Older versions of Node erroneously returned signed integers for
32205 return function (target, options, cb) {
32206 if (typeof options === 'function') {
32210 function callback (er, stats) {
32212 if (stats.uid < 0) stats.uid += 0x100000000
32213 if (stats.gid < 0) stats.gid += 0x100000000
32215 if (cb) cb.apply(this, arguments)
32217 return options ? orig.call(fs, target, options, callback)
32218 : orig.call(fs, target, callback)
32222 function statFixSync (orig) {
32223 if (!orig) return orig
32224 // Older versions of Node erroneously returned signed integers for
32226 return function (target, options) {
32227 var stats = options ? orig.call(fs, target, options)
32228 : orig.call(fs, target)
32229 if (stats.uid < 0) stats.uid += 0x100000000
32230 if (stats.gid < 0) stats.gid += 0x100000000
32235 // ENOSYS means that the fs doesn't support the op. Just ignore
32236 // that, because it doesn't matter.
32238 // if there's no getuid, or if getuid() is something other
32239 // than 0, and the error is EINVAL or EPERM, then just ignore
32242 // This specific case is a silent failure in cp, install, tar,
32243 // and most other unix tools that manage permissions.
32245 // When running as root, or if other types of errors are
32246 // encountered, then it's strict.
32247 function chownErOk (er) {
32251 if (er.code === "ENOSYS")
32254 var nonroot = !process.getuid || process.getuid() !== 0
32256 if (er.code === "EINVAL" || er.code === "EPERM")
32267 /***/ (function(module, exports, __webpack_require__) {
32269 var Stream = __webpack_require__(44).Stream
32271 module.exports = legacy
32273 function legacy (fs) {
32275 ReadStream: ReadStream,
32276 WriteStream: WriteStream
32279 function ReadStream (path, options) {
32280 if (!(this instanceof ReadStream)) return new ReadStream(path, options);
32288 this.readable = true;
32289 this.paused = false;
32292 this.mode = 438; /*=0666*/
32293 this.bufferSize = 64 * 1024;
32295 options = options || {};
32297 // Mixin options into this
32298 var keys = Object.keys(options);
32299 for (var index = 0, length = keys.length; index < length; index++) {
32300 var key = keys[index];
32301 this[key] = options[key];
32304 if (this.encoding) this.setEncoding(this.encoding);
32306 if (this.start !== undefined) {
32307 if ('number' !== typeof this.start) {
32308 throw TypeError('start must be a Number');
32310 if (this.end === undefined) {
32311 this.end = Infinity;
32312 } else if ('number' !== typeof this.end) {
32313 throw TypeError('end must be a Number');
32316 if (this.start > this.end) {
32317 throw new Error('start must be <= end');
32320 this.pos = this.start;
32323 if (this.fd !== null) {
32324 process.nextTick(function() {
32330 fs.open(this.path, this.flags, this.mode, function (err, fd) {
32332 self.emit('error', err);
32333 self.readable = false;
32338 self.emit('open', fd);
32343 function WriteStream (path, options) {
32344 if (!(this instanceof WriteStream)) return new WriteStream(path, options);
32350 this.writable = true;
32353 this.encoding = 'binary';
32354 this.mode = 438; /*=0666*/
32355 this.bytesWritten = 0;
32357 options = options || {};
32359 // Mixin options into this
32360 var keys = Object.keys(options);
32361 for (var index = 0, length = keys.length; index < length; index++) {
32362 var key = keys[index];
32363 this[key] = options[key];
32366 if (this.start !== undefined) {
32367 if ('number' !== typeof this.start) {
32368 throw TypeError('start must be a Number');
32370 if (this.start < 0) {
32371 throw new Error('start must be >= zero');
32374 this.pos = this.start;
32380 if (this.fd === null) {
32381 this._open = fs.open;
32382 this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
32391 /***/ (function(module, exports, __webpack_require__) {
32396 module.exports = clone
32398 function clone (obj) {
32399 if (obj === null || typeof obj !== 'object')
32402 if (obj instanceof Object)
32403 var copy = { __proto__: obj.__proto__ }
32405 var copy = Object.create(null)
32407 Object.getOwnPropertyNames(obj).forEach(function (key) {
32408 Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
32417 /***/ (function(module, exports, __webpack_require__) {
32419 var binary = __webpack_require__(123);
32420 var PullStream = __webpack_require__(164);
32421 var unzip = __webpack_require__(217);
32422 var Promise = __webpack_require__(128);
32423 var BufferStream = __webpack_require__(183);
32424 var parseExtraField = __webpack_require__(184);
32425 var Buffer = __webpack_require__(165);
32426 var path = __webpack_require__(2);
32427 var Writer = __webpack_require__(189).Writer;
32428 var parseDateTime = __webpack_require__(185);
32430 var signature = Buffer.alloc(4);
32431 signature.writeUInt32LE(0x06054b50,0);
32433 function getCrxHeader(source) {
32434 var sourceStream = source.stream(0).pipe(PullStream());
32436 return sourceStream.pull(4).then(function(data) {
32437 var signature = data.readUInt32LE(0);
32438 if (signature === 0x34327243) {
32440 return sourceStream.pull(12).then(function(data) {
32441 crxHeader = binary.parse(data)
32442 .word32lu('version')
32443 .word32lu('pubKeyLength')
32444 .word32lu('signatureLength')
32446 }).then(function() {
32447 return sourceStream.pull(crxHeader.pubKeyLength +crxHeader.signatureLength);
32448 }).then(function(data) {
32449 crxHeader.publicKey = data.slice(0,crxHeader.pubKeyLength);
32450 crxHeader.signature = data.slice(crxHeader.pubKeyLength);
32451 crxHeader.size = 16 + crxHeader.pubKeyLength +crxHeader.signatureLength;
32458 // Zip64 File Format Notes: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
32459 function getZip64CentralDirectory(source, zip64CDL) {
32460 var d64loc = binary.parse(zip64CDL)
32461 .word32lu('signature')
32462 .word32lu('diskNumber')
32463 .word64lu('offsetToStartOfCentralDirectory')
32464 .word32lu('numberOfDisks')
32467 if (d64loc.signature != 0x07064b50) {
32468 throw new Error('invalid zip64 end of central dir locator signature (0x07064b50): 0x' + d64loc.signature.toString(16));
32471 var dir64 = PullStream();
32472 source.stream(d64loc.offsetToStartOfCentralDirectory).pipe(dir64);
32474 return dir64.pull(56)
32477 // Zip64 File Format Notes: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
32478 function parseZip64DirRecord (dir64record) {
32479 var vars = binary.parse(dir64record)
32480 .word32lu('signature')
32481 .word64lu('sizeOfCentralDirectory')
32482 .word16lu('version')
32483 .word16lu('versionsNeededToExtract')
32484 .word32lu('diskNumber')
32485 .word32lu('diskStart')
32486 .word64lu('numberOfRecordsOnDisk')
32487 .word64lu('numberOfRecords')
32488 .word64lu('sizeOfCentralDirectory')
32489 .word64lu('offsetToStartOfCentralDirectory')
32492 if (vars.signature != 0x06064b50) {
32493 throw new Error('invalid zip64 end of central dir locator signature (0x06064b50): 0x0' + vars.signature.toString(16));
32499 module.exports = function centralDirectory(source, options) {
32500 var endDir = PullStream(),
32501 records = PullStream(),
32502 tailSize = (options && options.tailSize) || 80,
32508 if (options && options.crx)
32509 crxHeader = getCrxHeader(source);
32511 return source.size()
32512 .then(function(size) {
32515 source.stream(Math.max(0,size-tailSize))
32516 .on('error', function (error) { endDir.emit('error', error) })
32519 return endDir.pull(signature);
32522 return Promise.props({directory: endDir.pull(22), crxHeader: crxHeader});
32524 .then(function(d) {
32525 var data = d.directory;
32526 startOffset = d.crxHeader && d.crxHeader.size || 0;
32528 vars = binary.parse(data)
32529 .word32lu('signature')
32530 .word16lu('diskNumber')
32531 .word16lu('diskStart')
32532 .word16lu('numberOfRecordsOnDisk')
32533 .word16lu('numberOfRecords')
32534 .word32lu('sizeOfCentralDirectory')
32535 .word32lu('offsetToStartOfCentralDirectory')
32536 .word16lu('commentLength')
32539 // Is this zip file using zip64 format? Use same check as Go:
32540 // https://github.com/golang/go/blob/master/src/archive/zip/reader.go#L503
32541 // For zip64 files, need to find zip64 central directory locator header to extract
32542 // relative offset for zip64 central directory record.
32543 if (vars.numberOfRecords == 0xffff|| vars.numberOfRecords == 0xffff ||
32544 vars.offsetToStartOfCentralDirectory == 0xffffffff) {
32546 // Offset to zip64 CDL is 20 bytes before normal CDR
32547 const zip64CDLSize = 20
32548 const zip64CDLOffset = sourceSize - (tailSize - endDir.match + zip64CDLSize)
32549 const zip64CDLStream = PullStream();
32551 source.stream(zip64CDLOffset).pipe(zip64CDLStream);
32553 return zip64CDLStream.pull(zip64CDLSize)
32554 .then(function (d) { return getZip64CentralDirectory(source, d) })
32555 .then(function (dir64record) {
32556 vars = parseZip64DirRecord(dir64record)
32559 vars.offsetToStartOfCentralDirectory += startOffset;
32563 source.stream(vars.offsetToStartOfCentralDirectory).pipe(records);
32565 vars.extract = function(opts) {
32566 if (!opts || !opts.path) throw new Error('PATH_MISSING');
32567 return vars.files.then(function(files) {
32568 return Promise.map(files, function(entry) {
32569 if (entry.type == 'Directory') return;
32571 // to avoid zip slip (writing outside of the destination), we resolve
32572 // the target path, and make sure it's nested in the intended
32573 // destination, or not extract it otherwise.
32574 var extractPath = path.join(opts.path, entry.path);
32575 if (extractPath.indexOf(opts.path) != 0) {
32578 var writer = opts.getWriter ? opts.getWriter({path: extractPath}) : Writer({ path: extractPath });
32580 return new Promise(function(resolve, reject) {
32581 entry.stream(opts.password)
32582 .on('error',reject)
32584 .on('close',resolve)
32585 .on('error',reject);
32587 }, opts.concurrency > 1 ? {concurrency: opts.concurrency || undefined} : undefined);
32591 vars.files = Promise.mapSeries(Array(vars.numberOfRecords),function() {
32592 return records.pull(46).then(function(data) {
32593 var vars = binary.parse(data)
32594 .word32lu('signature')
32595 .word16lu('versionMadeBy')
32596 .word16lu('versionsNeededToExtract')
32598 .word16lu('compressionMethod')
32599 .word16lu('lastModifiedTime')
32600 .word16lu('lastModifiedDate')
32602 .word32lu('compressedSize')
32603 .word32lu('uncompressedSize')
32604 .word16lu('fileNameLength')
32605 .word16lu('extraFieldLength')
32606 .word16lu('fileCommentLength')
32607 .word16lu('diskNumber')
32608 .word16lu('internalFileAttributes')
32609 .word32lu('externalFileAttributes')
32610 .word32lu('offsetToLocalFileHeader')
32613 vars.offsetToLocalFileHeader += startOffset;
32614 vars.lastModifiedDateTime = parseDateTime(vars.lastModifiedDate, vars.lastModifiedTime);
32616 return records.pull(vars.fileNameLength).then(function(fileNameBuffer) {
32617 vars.pathBuffer = fileNameBuffer;
32618 vars.path = fileNameBuffer.toString('utf8');
32619 vars.isUnicode = vars.flags & 0x11;
32620 return records.pull(vars.extraFieldLength);
32622 .then(function(extraField) {
32623 vars.extra = parseExtraField(extraField, vars);
32624 return records.pull(vars.fileCommentLength);
32626 .then(function(comment) {
32627 vars.comment = comment;
32628 vars.type = (vars.uncompressedSize === 0 && /[\/\\]$/.test(vars.path)) ? 'Directory' : 'File';
32629 vars.stream = function(_password) {
32630 return unzip(source, vars.offsetToLocalFileHeader,_password, vars);
32632 vars.buffer = function(_password) {
32633 return BufferStream(vars.stream(_password));
32640 return Promise.props(vars);
32647 /***/ (function(module, exports, __webpack_require__) {
32649 var Promise = __webpack_require__(128);
32650 var Decrypt = __webpack_require__(218);
32651 var PullStream = __webpack_require__(164);
32652 var Stream = __webpack_require__(44);
32653 var binary = __webpack_require__(123);
32654 var zlib = __webpack_require__(48);
32655 var parseExtraField = __webpack_require__(184);
32656 var Buffer = __webpack_require__(165);
32657 var parseDateTime = __webpack_require__(185);
32659 // Backwards compatibility for node versions < 8
32660 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
32661 Stream = __webpack_require__(167);
32663 module.exports = function unzip(source,offset,_password, directoryVars) {
32664 var file = PullStream(),
32665 entry = Stream.PassThrough();
32667 var req = source.stream(offset);
32668 req.pipe(file).on('error', function(e) {
32669 entry.emit('error', e);
32672 entry.vars = file.pull(30)
32673 .then(function(data) {
32674 var vars = binary.parse(data)
32675 .word32lu('signature')
32676 .word16lu('versionsNeededToExtract')
32678 .word16lu('compressionMethod')
32679 .word16lu('lastModifiedTime')
32680 .word16lu('lastModifiedDate')
32682 .word32lu('compressedSize')
32683 .word32lu('uncompressedSize')
32684 .word16lu('fileNameLength')
32685 .word16lu('extraFieldLength')
32688 vars.lastModifiedDateTime = parseDateTime(vars.lastModifiedDate, vars.lastModifiedTime);
32690 return file.pull(vars.fileNameLength)
32691 .then(function(fileName) {
32692 vars.fileName = fileName.toString('utf8');
32693 return file.pull(vars.extraFieldLength);
32695 .then(function(extraField) {
32696 var checkEncryption;
32697 vars.extra = parseExtraField(extraField, vars);
32698 // Ignore logal file header vars if the directory vars are available
32699 if (directoryVars && directoryVars.compressedSize) vars = directoryVars;
32701 if (vars.flags & 0x01) checkEncryption = file.pull(12)
32702 .then(function(header) {
32704 throw new Error('MISSING_PASSWORD');
32706 var decrypt = Decrypt();
32708 String(_password).split('').forEach(function(d) {
32712 for (var i=0; i < header.length; i++)
32713 header[i] = decrypt.decryptByte(header[i]);
32715 vars.decrypt = decrypt;
32716 vars.compressedSize -= 12;
32718 var check = (vars.flags & 0x8) ? (vars.lastModifiedTime >> 8) & 0xff : (vars.crc32 >> 24) & 0xff;
32719 if (header[11] !== check)
32720 throw new Error('BAD_PASSWORD');
32725 return Promise.resolve(checkEncryption)
32727 entry.emit('vars',vars);
32733 entry.vars.then(function(vars) {
32734 var fileSizeKnown = !(vars.flags & 0x08) || vars.compressedSize > 0,
32737 var inflater = vars.compressionMethod ? zlib.createInflateRaw() : Stream.PassThrough();
32739 if (fileSizeKnown) {
32740 entry.size = vars.uncompressedSize;
32741 eof = vars.compressedSize;
32743 eof = Buffer.alloc(4);
32744 eof.writeUInt32LE(0x08074b50, 0);
32747 var stream = file.stream(eof);
32750 stream = stream.pipe(vars.decrypt.stream());
32754 .on('error',function(err) { entry.emit('error',err);})
32756 .on('finish', function() {
32759 else if (req.close)
32764 console.log('warning - unable to close stream');
32767 .catch(function(e) {
32768 entry.emit('error',e);
32777 /***/ (function(module, exports, __webpack_require__) {
32779 var bigInt = __webpack_require__(219);
32780 var Stream = __webpack_require__(44);
32782 // Backwards compatibility for node versions < 8
32783 if (!Stream.Writable || !Stream.Writable.prototype.destroy)
32784 Stream = __webpack_require__(167);
32788 function generateTable() {
32789 var poly = 0xEDB88320,c,n,k;
32791 for (n = 0; n < 256; n++) {
32793 for (k = 0; k < 8; k++)
32794 c = (c & 1) ? poly ^ (c >>> 1) : c = c >>> 1;
32795 table[n] = c >>> 0;
32799 function crc(ch,crc) {
32804 ch = ch.charCodeAt(0);
32806 return (bigInt(crc).shiftRight(8).and(0xffffff)).xor(table[bigInt(crc).xor(ch).and(0xff)]).value;
32809 function Decrypt() {
32810 if (!(this instanceof Decrypt))
32811 return new Decrypt();
32813 this.key0 = 305419896;
32814 this.key1 = 591751049;
32815 this.key2 = 878082192;
32818 Decrypt.prototype.update = function(h) {
32819 this.key0 = crc(h,this.key0);
32820 this.key1 = bigInt(this.key0).and(255).and(4294967295).add(this.key1)
32821 this.key1 = bigInt(this.key1).multiply(134775813).add(1).and(4294967295).value;
32822 this.key2 = crc(bigInt(this.key1).shiftRight(24).and(255), this.key2);
32826 Decrypt.prototype.decryptByte = function(c) {
32827 var k = bigInt(this.key2).or(2);
32828 c = c ^ bigInt(k).multiply(bigInt(k^1)).shiftRight(8).and(255);
32833 Decrypt.prototype.stream = function() {
32834 var stream = Stream.Transform(),
32837 stream._transform = function(d,e,cb) {
32838 for (var i = 0; i<d.length;i++) {
32839 d[i] = self.decryptByte(d[i]);
32850 module.exports = Decrypt;
32854 /***/ (function(module, exports, __webpack_require__) {
32856 /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;var bigInt = (function (undefined) {
\r
32861 MAX_INT = 9007199254740992,
\r
32862 MAX_INT_ARR = smallToArray(MAX_INT),
\r
32863 DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
\r
32865 var supportsNativeBigInt = typeof BigInt === "function";
\r
32867 function Integer(v, radix, alphabet, caseSensitive) {
\r
32868 if (typeof v === "undefined") return Integer[0];
\r
32869 if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);
\r
32870 return parseValue(v);
\r
32873 function BigInteger(value, sign) {
\r
32874 this.value = value;
\r
32875 this.sign = sign;
\r
32876 this.isSmall = false;
\r
32878 BigInteger.prototype = Object.create(Integer.prototype);
\r
32880 function SmallInteger(value) {
\r
32881 this.value = value;
\r
32882 this.sign = value < 0;
\r
32883 this.isSmall = true;
\r
32885 SmallInteger.prototype = Object.create(Integer.prototype);
\r
32887 function NativeBigInt(value) {
\r
32888 this.value = value;
\r
32890 NativeBigInt.prototype = Object.create(Integer.prototype);
\r
32892 function isPrecise(n) {
\r
32893 return -MAX_INT < n && n < MAX_INT;
\r
32896 function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
\r
32900 return [n % 1e7, Math.floor(n / 1e7)];
\r
32901 return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
\r
32904 function arrayToSmall(arr) { // If BASE changes this function may need to change
\r
32906 var length = arr.length;
\r
32907 if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
\r
32908 switch (length) {
\r
32909 case 0: return 0;
\r
32910 case 1: return arr[0];
\r
32911 case 2: return arr[0] + arr[1] * BASE;
\r
32912 default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
\r
32918 function trim(v) {
\r
32919 var i = v.length;
\r
32920 while (v[--i] === 0);
\r
32921 v.length = i + 1;
\r
32924 function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
\r
32925 var x = new Array(length);
\r
32927 while (++i < length) {
\r
32933 function truncate(n) {
\r
32934 if (n > 0) return Math.floor(n);
\r
32935 return Math.ceil(n);
\r
32938 function add(a, b) { // assumes a and b are arrays with a.length >= b.length
\r
32939 var l_a = a.length,
\r
32941 r = new Array(l_a),
\r
32945 for (i = 0; i < l_b; i++) {
\r
32946 sum = a[i] + b[i] + carry;
\r
32947 carry = sum >= base ? 1 : 0;
\r
32948 r[i] = sum - carry * base;
\r
32950 while (i < l_a) {
\r
32951 sum = a[i] + carry;
\r
32952 carry = sum === base ? 1 : 0;
\r
32953 r[i++] = sum - carry * base;
\r
32955 if (carry > 0) r.push(carry);
\r
32959 function addAny(a, b) {
\r
32960 if (a.length >= b.length) return add(a, b);
\r
32961 return add(b, a);
\r
32964 function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
\r
32965 var l = a.length,
\r
32966 r = new Array(l),
\r
32969 for (i = 0; i < l; i++) {
\r
32970 sum = a[i] - base + carry;
\r
32971 carry = Math.floor(sum / base);
\r
32972 r[i] = sum - carry * base;
\r
32975 while (carry > 0) {
\r
32976 r[i++] = carry % base;
\r
32977 carry = Math.floor(carry / base);
\r
32982 BigInteger.prototype.add = function (v) {
\r
32983 var n = parseValue(v);
\r
32984 if (this.sign !== n.sign) {
\r
32985 return this.subtract(n.negate());
\r
32987 var a = this.value, b = n.value;
\r
32989 return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
\r
32991 return new BigInteger(addAny(a, b), this.sign);
\r
32993 BigInteger.prototype.plus = BigInteger.prototype.add;
\r
32995 SmallInteger.prototype.add = function (v) {
\r
32996 var n = parseValue(v);
\r
32997 var a = this.value;
\r
32998 if (a < 0 !== n.sign) {
\r
32999 return this.subtract(n.negate());
\r
33003 if (isPrecise(a + b)) return new SmallInteger(a + b);
\r
33004 b = smallToArray(Math.abs(b));
\r
33006 return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
\r
33008 SmallInteger.prototype.plus = SmallInteger.prototype.add;
\r
33010 NativeBigInt.prototype.add = function (v) {
\r
33011 return new NativeBigInt(this.value + parseValue(v).value);
\r
33013 NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
\r
33015 function subtract(a, b) { // assumes a and b are arrays with a >= b
\r
33016 var a_l = a.length,
\r
33018 r = new Array(a_l),
\r
33022 for (i = 0; i < b_l; i++) {
\r
33023 difference = a[i] - borrow - b[i];
\r
33024 if (difference < 0) {
\r
33025 difference += base;
\r
33027 } else borrow = 0;
\r
33028 r[i] = difference;
\r
33030 for (i = b_l; i < a_l; i++) {
\r
33031 difference = a[i] - borrow;
\r
33032 if (difference < 0) difference += base;
\r
33034 r[i++] = difference;
\r
33037 r[i] = difference;
\r
33039 for (; i < a_l; i++) {
\r
33046 function subtractAny(a, b, sign) {
\r
33048 if (compareAbs(a, b) >= 0) {
\r
33049 value = subtract(a, b);
\r
33051 value = subtract(b, a);
\r
33054 value = arrayToSmall(value);
\r
33055 if (typeof value === "number") {
\r
33056 if (sign) value = -value;
\r
33057 return new SmallInteger(value);
\r
33059 return new BigInteger(value, sign);
\r
33062 function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
\r
33063 var l = a.length,
\r
33064 r = new Array(l),
\r
33068 for (i = 0; i < l; i++) {
\r
33069 difference = a[i] + carry;
\r
33070 carry = Math.floor(difference / base);
\r
33071 difference %= base;
\r
33072 r[i] = difference < 0 ? difference + base : difference;
\r
33074 r = arrayToSmall(r);
\r
33075 if (typeof r === "number") {
\r
33076 if (sign) r = -r;
\r
33077 return new SmallInteger(r);
\r
33078 } return new BigInteger(r, sign);
\r
33081 BigInteger.prototype.subtract = function (v) {
\r
33082 var n = parseValue(v);
\r
33083 if (this.sign !== n.sign) {
\r
33084 return this.add(n.negate());
\r
33086 var a = this.value, b = n.value;
\r
33088 return subtractSmall(a, Math.abs(b), this.sign);
\r
33089 return subtractAny(a, b, this.sign);
\r
33091 BigInteger.prototype.minus = BigInteger.prototype.subtract;
\r
33093 SmallInteger.prototype.subtract = function (v) {
\r
33094 var n = parseValue(v);
\r
33095 var a = this.value;
\r
33096 if (a < 0 !== n.sign) {
\r
33097 return this.add(n.negate());
\r
33101 return new SmallInteger(a - b);
\r
33103 return subtractSmall(b, Math.abs(a), a >= 0);
\r
33105 SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
\r
33107 NativeBigInt.prototype.subtract = function (v) {
\r
33108 return new NativeBigInt(this.value - parseValue(v).value);
\r
33110 NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
\r
33112 BigInteger.prototype.negate = function () {
\r
33113 return new BigInteger(this.value, !this.sign);
\r
33115 SmallInteger.prototype.negate = function () {
\r
33116 var sign = this.sign;
\r
33117 var small = new SmallInteger(-this.value);
\r
33118 small.sign = !sign;
\r
33121 NativeBigInt.prototype.negate = function () {
\r
33122 return new NativeBigInt(-this.value);
\r
33125 BigInteger.prototype.abs = function () {
\r
33126 return new BigInteger(this.value, false);
\r
33128 SmallInteger.prototype.abs = function () {
\r
33129 return new SmallInteger(Math.abs(this.value));
\r
33131 NativeBigInt.prototype.abs = function () {
\r
33132 return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
\r
33136 function multiplyLong(a, b) {
\r
33137 var a_l = a.length,
\r
33140 r = createArray(l),
\r
33142 product, carry, i, a_i, b_j;
\r
33143 for (i = 0; i < a_l; ++i) {
\r
33145 for (var j = 0; j < b_l; ++j) {
\r
33147 product = a_i * b_j + r[i + j];
\r
33148 carry = Math.floor(product / base);
\r
33149 r[i + j] = product - carry * base;
\r
33150 r[i + j + 1] += carry;
\r
33157 function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
\r
33158 var l = a.length,
\r
33159 r = new Array(l),
\r
33163 for (i = 0; i < l; i++) {
\r
33164 product = a[i] * b + carry;
\r
33165 carry = Math.floor(product / base);
\r
33166 r[i] = product - carry * base;
\r
33168 while (carry > 0) {
\r
33169 r[i++] = carry % base;
\r
33170 carry = Math.floor(carry / base);
\r
33175 function shiftLeft(x, n) {
\r
33177 while (n-- > 0) r.push(0);
\r
33178 return r.concat(x);
\r
33181 function multiplyKaratsuba(x, y) {
\r
33182 var n = Math.max(x.length, y.length);
\r
33184 if (n <= 30) return multiplyLong(x, y);
\r
33185 n = Math.ceil(n / 2);
\r
33187 var b = x.slice(n),
\r
33188 a = x.slice(0, n),
\r
33190 c = y.slice(0, n);
\r
33192 var ac = multiplyKaratsuba(a, c),
\r
33193 bd = multiplyKaratsuba(b, d),
\r
33194 abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
\r
33196 var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
\r
33201 // The following function is derived from a surface fit of a graph plotting the performance difference
\r
33202 // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
\r
33203 function useKaratsuba(l1, l2) {
\r
33204 return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
\r
33207 BigInteger.prototype.multiply = function (v) {
\r
33208 var n = parseValue(v),
\r
33209 a = this.value, b = n.value,
\r
33210 sign = this.sign !== n.sign,
\r
33213 if (b === 0) return Integer[0];
\r
33214 if (b === 1) return this;
\r
33215 if (b === -1) return this.negate();
\r
33216 abs = Math.abs(b);
\r
33217 if (abs < BASE) {
\r
33218 return new BigInteger(multiplySmall(a, abs), sign);
\r
33220 b = smallToArray(abs);
\r
33222 if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
\r
33223 return new BigInteger(multiplyKaratsuba(a, b), sign);
\r
33224 return new BigInteger(multiplyLong(a, b), sign);
\r
33227 BigInteger.prototype.times = BigInteger.prototype.multiply;
\r
33229 function multiplySmallAndArray(a, b, sign) { // a >= 0
\r
33231 return new BigInteger(multiplySmall(b, a), sign);
\r
33233 return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
\r
33235 SmallInteger.prototype._multiplyBySmall = function (a) {
\r
33236 if (isPrecise(a.value * this.value)) {
\r
33237 return new SmallInteger(a.value * this.value);
\r
33239 return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
\r
33241 BigInteger.prototype._multiplyBySmall = function (a) {
\r
33242 if (a.value === 0) return Integer[0];
\r
33243 if (a.value === 1) return this;
\r
33244 if (a.value === -1) return this.negate();
\r
33245 return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
\r
33247 SmallInteger.prototype.multiply = function (v) {
\r
33248 return parseValue(v)._multiplyBySmall(this);
\r
33250 SmallInteger.prototype.times = SmallInteger.prototype.multiply;
\r
33252 NativeBigInt.prototype.multiply = function (v) {
\r
33253 return new NativeBigInt(this.value * parseValue(v).value);
\r
33255 NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
\r
33257 function square(a) {
\r
33258 //console.assert(2 * BASE * BASE < MAX_INT);
\r
33259 var l = a.length,
\r
33260 r = createArray(l + l),
\r
33262 product, carry, i, a_i, a_j;
\r
33263 for (i = 0; i < l; i++) {
\r
33265 carry = 0 - a_i * a_i;
\r
33266 for (var j = i; j < l; j++) {
\r
33268 product = 2 * (a_i * a_j) + r[i + j] + carry;
\r
33269 carry = Math.floor(product / base);
\r
33270 r[i + j] = product - carry * base;
\r
33272 r[i + l] = carry;
\r
33278 BigInteger.prototype.square = function () {
\r
33279 return new BigInteger(square(this.value), false);
\r
33282 SmallInteger.prototype.square = function () {
\r
33283 var value = this.value * this.value;
\r
33284 if (isPrecise(value)) return new SmallInteger(value);
\r
33285 return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
\r
33288 NativeBigInt.prototype.square = function (v) {
\r
33289 return new NativeBigInt(this.value * this.value);
\r
33292 function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
\r
33293 var a_l = a.length,
\r
33296 result = createArray(b.length),
\r
33297 divisorMostSignificantDigit = b[b_l - 1],
\r
33299 lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
\r
33300 remainder = multiplySmall(a, lambda),
\r
33301 divisor = multiplySmall(b, lambda),
\r
33302 quotientDigit, shift, carry, borrow, i, l, q;
\r
33303 if (remainder.length <= a_l) remainder.push(0);
\r
33305 divisorMostSignificantDigit = divisor[b_l - 1];
\r
33306 for (shift = a_l - b_l; shift >= 0; shift--) {
\r
33307 quotientDigit = base - 1;
\r
33308 if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
\r
33309 quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
\r
33311 // quotientDigit <= base - 1
\r
33314 l = divisor.length;
\r
33315 for (i = 0; i < l; i++) {
\r
33316 carry += quotientDigit * divisor[i];
\r
33317 q = Math.floor(carry / base);
\r
33318 borrow += remainder[shift + i] - (carry - q * base);
\r
33320 if (borrow < 0) {
\r
33321 remainder[shift + i] = borrow + base;
\r
33324 remainder[shift + i] = borrow;
\r
33328 while (borrow !== 0) {
\r
33329 quotientDigit -= 1;
\r
33331 for (i = 0; i < l; i++) {
\r
33332 carry += remainder[shift + i] - base + divisor[i];
\r
33334 remainder[shift + i] = carry + base;
\r
33337 remainder[shift + i] = carry;
\r
33343 result[shift] = quotientDigit;
\r
33345 // denormalization
\r
33346 remainder = divModSmall(remainder, lambda)[0];
\r
33347 return [arrayToSmall(result), arrayToSmall(remainder)];
\r
33350 function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
\r
33351 // Performs faster than divMod1 on larger input sizes.
\r
33352 var a_l = a.length,
\r
33357 guess, xlen, highx, highy, check;
\r
33359 part.unshift(a[--a_l]);
\r
33361 if (compareAbs(part, b) < 0) {
\r
33365 xlen = part.length;
\r
33366 highx = part[xlen - 1] * base + part[xlen - 2];
\r
33367 highy = b[b_l - 1] * base + b[b_l - 2];
\r
33368 if (xlen > b_l) {
\r
33369 highx = (highx + 1) * base;
\r
33371 guess = Math.ceil(highx / highy);
\r
33373 check = multiplySmall(b, guess);
\r
33374 if (compareAbs(check, part) <= 0) break;
\r
33377 result.push(guess);
\r
33378 part = subtract(part, check);
\r
33380 result.reverse();
\r
33381 return [arrayToSmall(result), arrayToSmall(part)];
\r
33384 function divModSmall(value, lambda) {
\r
33385 var length = value.length,
\r
33386 quotient = createArray(length),
\r
33388 i, q, remainder, divisor;
\r
33390 for (i = length - 1; i >= 0; --i) {
\r
33391 divisor = remainder * base + value[i];
\r
33392 q = truncate(divisor / lambda);
\r
33393 remainder = divisor - q * lambda;
\r
33394 quotient[i] = q | 0;
\r
33396 return [quotient, remainder | 0];
\r
33399 function divModAny(self, v) {
\r
33400 var value, n = parseValue(v);
\r
33401 if (supportsNativeBigInt) {
\r
33402 return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];
\r
33404 var a = self.value, b = n.value;
\r
33406 if (b === 0) throw new Error("Cannot divide by zero");
\r
33407 if (self.isSmall) {
\r
33409 return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
\r
33411 return [Integer[0], self];
\r
33414 if (b === 1) return [self, Integer[0]];
\r
33415 if (b == -1) return [self.negate(), Integer[0]];
\r
33416 var abs = Math.abs(b);
\r
33417 if (abs < BASE) {
\r
33418 value = divModSmall(a, abs);
\r
33419 quotient = arrayToSmall(value[0]);
\r
33420 var remainder = value[1];
\r
33421 if (self.sign) remainder = -remainder;
\r
33422 if (typeof quotient === "number") {
\r
33423 if (self.sign !== n.sign) quotient = -quotient;
\r
33424 return [new SmallInteger(quotient), new SmallInteger(remainder)];
\r
33426 return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
\r
33428 b = smallToArray(abs);
\r
33430 var comparison = compareAbs(a, b);
\r
33431 if (comparison === -1) return [Integer[0], self];
\r
33432 if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
\r
33434 // divMod1 is faster on smaller input sizes
\r
33435 if (a.length + b.length <= 200)
\r
33436 value = divMod1(a, b);
\r
33437 else value = divMod2(a, b);
\r
33439 quotient = value[0];
\r
33440 var qSign = self.sign !== n.sign,
\r
33442 mSign = self.sign;
\r
33443 if (typeof quotient === "number") {
\r
33444 if (qSign) quotient = -quotient;
\r
33445 quotient = new SmallInteger(quotient);
\r
33446 } else quotient = new BigInteger(quotient, qSign);
\r
33447 if (typeof mod === "number") {
\r
33448 if (mSign) mod = -mod;
\r
33449 mod = new SmallInteger(mod);
\r
33450 } else mod = new BigInteger(mod, mSign);
\r
33451 return [quotient, mod];
\r
33454 BigInteger.prototype.divmod = function (v) {
\r
33455 var result = divModAny(this, v);
\r
33457 quotient: result[0],
\r
33458 remainder: result[1]
\r
33461 NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
\r
33464 BigInteger.prototype.divide = function (v) {
\r
33465 return divModAny(this, v)[0];
\r
33467 NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {
\r
33468 return new NativeBigInt(this.value / parseValue(v).value);
\r
33470 SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
\r
33472 BigInteger.prototype.mod = function (v) {
\r
33473 return divModAny(this, v)[1];
\r
33475 NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {
\r
33476 return new NativeBigInt(this.value % parseValue(v).value);
\r
33478 SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
\r
33480 BigInteger.prototype.pow = function (v) {
\r
33481 var n = parseValue(v),
\r
33485 if (b === 0) return Integer[1];
\r
33486 if (a === 0) return Integer[0];
\r
33487 if (a === 1) return Integer[1];
\r
33488 if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
\r
33490 return Integer[0];
\r
33492 if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
\r
33493 if (this.isSmall) {
\r
33494 if (isPrecise(value = Math.pow(a, b)))
\r
33495 return new SmallInteger(truncate(value));
\r
33500 if (b & 1 === 1) {
\r
33504 if (b === 0) break;
\r
33510 SmallInteger.prototype.pow = BigInteger.prototype.pow;
\r
33512 NativeBigInt.prototype.pow = function (v) {
\r
33513 var n = parseValue(v);
\r
33514 var a = this.value, b = n.value;
\r
33515 var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
\r
33516 if (b === _0) return Integer[1];
\r
33517 if (a === _0) return Integer[0];
\r
33518 if (a === _1) return Integer[1];
\r
33519 if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];
\r
33520 if (n.isNegative()) return new NativeBigInt(_0);
\r
33522 var y = Integer[1];
\r
33524 if ((b & _1) === _1) {
\r
33528 if (b === _0) break;
\r
33535 BigInteger.prototype.modPow = function (exp, mod) {
\r
33536 exp = parseValue(exp);
\r
33537 mod = parseValue(mod);
\r
33538 if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
\r
33539 var r = Integer[1],
\r
33540 base = this.mod(mod);
\r
33541 if (exp.isNegative()) {
\r
33542 exp = exp.multiply(Integer[-1]);
\r
33543 base = base.modInv(mod);
\r
33545 while (exp.isPositive()) {
\r
33546 if (base.isZero()) return Integer[0];
\r
33547 if (exp.isOdd()) r = r.multiply(base).mod(mod);
\r
33548 exp = exp.divide(2);
\r
33549 base = base.square().mod(mod);
\r
33553 NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
\r
33555 function compareAbs(a, b) {
\r
33556 if (a.length !== b.length) {
\r
33557 return a.length > b.length ? 1 : -1;
\r
33559 for (var i = a.length - 1; i >= 0; i--) {
\r
33560 if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
\r
33565 BigInteger.prototype.compareAbs = function (v) {
\r
33566 var n = parseValue(v),
\r
33569 if (n.isSmall) return 1;
\r
33570 return compareAbs(a, b);
\r
33572 SmallInteger.prototype.compareAbs = function (v) {
\r
33573 var n = parseValue(v),
\r
33574 a = Math.abs(this.value),
\r
33578 return a === b ? 0 : a > b ? 1 : -1;
\r
33582 NativeBigInt.prototype.compareAbs = function (v) {
\r
33583 var a = this.value;
\r
33584 var b = parseValue(v).value;
\r
33585 a = a >= 0 ? a : -a;
\r
33586 b = b >= 0 ? b : -b;
\r
33587 return a === b ? 0 : a > b ? 1 : -1;
\r
33590 BigInteger.prototype.compare = function (v) {
\r
33591 // See discussion about comparison with Infinity:
\r
33592 // https://github.com/peterolson/BigInteger.js/issues/61
\r
33593 if (v === Infinity) {
\r
33596 if (v === -Infinity) {
\r
33600 var n = parseValue(v),
\r
33603 if (this.sign !== n.sign) {
\r
33604 return n.sign ? 1 : -1;
\r
33607 return this.sign ? -1 : 1;
\r
33609 return compareAbs(a, b) * (this.sign ? -1 : 1);
\r
33611 BigInteger.prototype.compareTo = BigInteger.prototype.compare;
\r
33613 SmallInteger.prototype.compare = function (v) {
\r
33614 if (v === Infinity) {
\r
33617 if (v === -Infinity) {
\r
33621 var n = parseValue(v),
\r
33625 return a == b ? 0 : a > b ? 1 : -1;
\r
33627 if (a < 0 !== n.sign) {
\r
33628 return a < 0 ? -1 : 1;
\r
33630 return a < 0 ? 1 : -1;
\r
33632 SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
\r
33634 NativeBigInt.prototype.compare = function (v) {
\r
33635 if (v === Infinity) {
\r
33638 if (v === -Infinity) {
\r
33641 var a = this.value;
\r
33642 var b = parseValue(v).value;
\r
33643 return a === b ? 0 : a > b ? 1 : -1;
\r
33645 NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
\r
33647 BigInteger.prototype.equals = function (v) {
\r
33648 return this.compare(v) === 0;
\r
33650 NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
\r
33652 BigInteger.prototype.notEquals = function (v) {
\r
33653 return this.compare(v) !== 0;
\r
33655 NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
\r
33657 BigInteger.prototype.greater = function (v) {
\r
33658 return this.compare(v) > 0;
\r
33660 NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
\r
33662 BigInteger.prototype.lesser = function (v) {
\r
33663 return this.compare(v) < 0;
\r
33665 NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
\r
33667 BigInteger.prototype.greaterOrEquals = function (v) {
\r
33668 return this.compare(v) >= 0;
\r
33670 NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
\r
33672 BigInteger.prototype.lesserOrEquals = function (v) {
\r
33673 return this.compare(v) <= 0;
\r
33675 NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
\r
33677 BigInteger.prototype.isEven = function () {
\r
33678 return (this.value[0] & 1) === 0;
\r
33680 SmallInteger.prototype.isEven = function () {
\r
33681 return (this.value & 1) === 0;
\r
33683 NativeBigInt.prototype.isEven = function () {
\r
33684 return (this.value & BigInt(1)) === BigInt(0);
\r
33687 BigInteger.prototype.isOdd = function () {
\r
33688 return (this.value[0] & 1) === 1;
\r
33690 SmallInteger.prototype.isOdd = function () {
\r
33691 return (this.value & 1) === 1;
\r
33693 NativeBigInt.prototype.isOdd = function () {
\r
33694 return (this.value & BigInt(1)) === BigInt(1);
\r
33697 BigInteger.prototype.isPositive = function () {
\r
33698 return !this.sign;
\r
33700 SmallInteger.prototype.isPositive = function () {
\r
33701 return this.value > 0;
\r
33703 NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
\r
33705 BigInteger.prototype.isNegative = function () {
\r
33706 return this.sign;
\r
33708 SmallInteger.prototype.isNegative = function () {
\r
33709 return this.value < 0;
\r
33711 NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
\r
33713 BigInteger.prototype.isUnit = function () {
\r
33716 SmallInteger.prototype.isUnit = function () {
\r
33717 return Math.abs(this.value) === 1;
\r
33719 NativeBigInt.prototype.isUnit = function () {
\r
33720 return this.abs().value === BigInt(1);
\r
33723 BigInteger.prototype.isZero = function () {
\r
33726 SmallInteger.prototype.isZero = function () {
\r
33727 return this.value === 0;
\r
33729 NativeBigInt.prototype.isZero = function () {
\r
33730 return this.value === BigInt(0);
\r
33733 BigInteger.prototype.isDivisibleBy = function (v) {
\r
33734 var n = parseValue(v);
\r
33735 if (n.isZero()) return false;
\r
33736 if (n.isUnit()) return true;
\r
33737 if (n.compareAbs(2) === 0) return this.isEven();
\r
33738 return this.mod(n).isZero();
\r
33740 NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
\r
33742 function isBasicPrime(v) {
\r
33744 if (n.isUnit()) return false;
\r
33745 if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
\r
33746 if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
\r
33747 if (n.lesser(49)) return true;
\r
33748 // we don't know if it's prime: let the other functions figure it out
\r
33751 function millerRabinTest(n, a) {
\r
33752 var nPrev = n.prev(),
\r
33756 while (b.isEven()) b = b.divide(2), r++;
\r
33757 next: for (i = 0; i < a.length; i++) {
\r
33758 if (n.lesser(a[i])) continue;
\r
33759 x = bigInt(a[i]).modPow(b, n);
\r
33760 if (x.isUnit() || x.equals(nPrev)) continue;
\r
33761 for (d = r - 1; d != 0; d--) {
\r
33762 x = x.square().mod(n);
\r
33763 if (x.isUnit()) return false;
\r
33764 if (x.equals(nPrev)) continue next;
\r
33771 // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
\r
33772 BigInteger.prototype.isPrime = function (strict) {
\r
33773 var isPrime = isBasicPrime(this);
\r
33774 if (isPrime !== undefined) return isPrime;
\r
33775 var n = this.abs();
\r
33776 var bits = n.bitLength();
\r
33778 return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
\r
33779 var logN = Math.log(2) * bits.toJSNumber();
\r
33780 var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
\r
33781 for (var a = [], i = 0; i < t; i++) {
\r
33782 a.push(bigInt(i + 2));
\r
33784 return millerRabinTest(n, a);
\r
33786 NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
\r
33788 BigInteger.prototype.isProbablePrime = function (iterations, rng) {
\r
33789 var isPrime = isBasicPrime(this);
\r
33790 if (isPrime !== undefined) return isPrime;
\r
33791 var n = this.abs();
\r
33792 var t = iterations === undefined ? 5 : iterations;
\r
33793 for (var a = [], i = 0; i < t; i++) {
\r
33794 a.push(bigInt.randBetween(2, n.minus(2), rng));
\r
33796 return millerRabinTest(n, a);
\r
33798 NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
\r
33800 BigInteger.prototype.modInv = function (n) {
\r
33801 var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
\r
33802 while (!newR.isZero()) {
\r
33803 q = r.divide(newR);
\r
33808 newT = lastT.subtract(q.multiply(newT));
\r
33809 newR = lastR.subtract(q.multiply(newR));
\r
33811 if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
\r
33812 if (t.compare(0) === -1) {
\r
33815 if (this.isNegative()) {
\r
33816 return t.negate();
\r
33821 NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
\r
33823 BigInteger.prototype.next = function () {
\r
33824 var value = this.value;
\r
33826 return subtractSmall(value, 1, this.sign);
\r
33828 return new BigInteger(addSmall(value, 1), this.sign);
\r
33830 SmallInteger.prototype.next = function () {
\r
33831 var value = this.value;
\r
33832 if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
\r
33833 return new BigInteger(MAX_INT_ARR, false);
\r
33835 NativeBigInt.prototype.next = function () {
\r
33836 return new NativeBigInt(this.value + BigInt(1));
\r
33839 BigInteger.prototype.prev = function () {
\r
33840 var value = this.value;
\r
33842 return new BigInteger(addSmall(value, 1), true);
\r
33844 return subtractSmall(value, 1, this.sign);
\r
33846 SmallInteger.prototype.prev = function () {
\r
33847 var value = this.value;
\r
33848 if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
\r
33849 return new BigInteger(MAX_INT_ARR, true);
\r
33851 NativeBigInt.prototype.prev = function () {
\r
33852 return new NativeBigInt(this.value - BigInt(1));
\r
33855 var powersOfTwo = [1];
\r
33856 while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
\r
33857 var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
\r
33859 function shift_isSmall(n) {
\r
33860 return Math.abs(n) <= BASE;
\r
33863 BigInteger.prototype.shiftLeft = function (v) {
\r
33864 var n = parseValue(v).toJSNumber();
\r
33865 if (!shift_isSmall(n)) {
\r
33866 throw new Error(String(n) + " is too large for shifting.");
\r
33868 if (n < 0) return this.shiftRight(-n);
\r
33869 var result = this;
\r
33870 if (result.isZero()) return result;
\r
33871 while (n >= powers2Length) {
\r
33872 result = result.multiply(highestPower2);
\r
33873 n -= powers2Length - 1;
\r
33875 return result.multiply(powersOfTwo[n]);
\r
33877 NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
\r
33879 BigInteger.prototype.shiftRight = function (v) {
\r
33881 var n = parseValue(v).toJSNumber();
\r
33882 if (!shift_isSmall(n)) {
\r
33883 throw new Error(String(n) + " is too large for shifting.");
\r
33885 if (n < 0) return this.shiftLeft(-n);
\r
33886 var result = this;
\r
33887 while (n >= powers2Length) {
\r
33888 if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
\r
33889 remQuo = divModAny(result, highestPower2);
\r
33890 result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
\r
33891 n -= powers2Length - 1;
\r
33893 remQuo = divModAny(result, powersOfTwo[n]);
\r
33894 return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
\r
33896 NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
\r
33898 function bitwise(x, y, fn) {
\r
33899 y = parseValue(y);
\r
33900 var xSign = x.isNegative(), ySign = y.isNegative();
\r
33901 var xRem = xSign ? x.not() : x,
\r
33902 yRem = ySign ? y.not() : y;
\r
33903 var xDigit = 0, yDigit = 0;
\r
33904 var xDivMod = null, yDivMod = null;
\r
33906 while (!xRem.isZero() || !yRem.isZero()) {
\r
33907 xDivMod = divModAny(xRem, highestPower2);
\r
33908 xDigit = xDivMod[1].toJSNumber();
\r
33910 xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
\r
33913 yDivMod = divModAny(yRem, highestPower2);
\r
33914 yDigit = yDivMod[1].toJSNumber();
\r
33916 yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
\r
33919 xRem = xDivMod[0];
\r
33920 yRem = yDivMod[0];
\r
33921 result.push(fn(xDigit, yDigit));
\r
33923 var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
\r
33924 for (var i = result.length - 1; i >= 0; i -= 1) {
\r
33925 sum = sum.multiply(highestPower2).add(bigInt(result[i]));
\r
33930 BigInteger.prototype.not = function () {
\r
33931 return this.negate().prev();
\r
33933 NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
\r
33935 BigInteger.prototype.and = function (n) {
\r
33936 return bitwise(this, n, function (a, b) { return a & b; });
\r
33938 NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
\r
33940 BigInteger.prototype.or = function (n) {
\r
33941 return bitwise(this, n, function (a, b) { return a | b; });
\r
33943 NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
\r
33945 BigInteger.prototype.xor = function (n) {
\r
33946 return bitwise(this, n, function (a, b) { return a ^ b; });
\r
33948 NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
\r
33950 var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
\r
33951 function roughLOB(n) { // get lowestOneBit (rough)
\r
33952 // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
\r
33953 // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
\r
33955 x = typeof v === "number" ? v | LOBMASK_I :
\r
33956 typeof v === "bigint" ? v | BigInt(LOBMASK_I) :
\r
33957 v[0] + v[1] * BASE | LOBMASK_BI;
\r
33961 function integerLogarithm(value, base) {
\r
33962 if (base.compareTo(value) <= 0) {
\r
33963 var tmp = integerLogarithm(value, base.square(base));
\r
33966 var t = p.multiply(base);
\r
33967 return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
\r
33969 return { p: bigInt(1), e: 0 };
\r
33972 BigInteger.prototype.bitLength = function () {
\r
33974 if (n.compareTo(bigInt(0)) < 0) {
\r
33975 n = n.negate().subtract(bigInt(1));
\r
33977 if (n.compareTo(bigInt(0)) === 0) {
\r
33978 return bigInt(0);
\r
33980 return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
\r
33982 NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
\r
33984 function max(a, b) {
\r
33985 a = parseValue(a);
\r
33986 b = parseValue(b);
\r
33987 return a.greater(b) ? a : b;
\r
33989 function min(a, b) {
\r
33990 a = parseValue(a);
\r
33991 b = parseValue(b);
\r
33992 return a.lesser(b) ? a : b;
\r
33994 function gcd(a, b) {
\r
33995 a = parseValue(a).abs();
\r
33996 b = parseValue(b).abs();
\r
33997 if (a.equals(b)) return a;
\r
33998 if (a.isZero()) return b;
\r
33999 if (b.isZero()) return a;
\r
34000 var c = Integer[1], d, t;
\r
34001 while (a.isEven() && b.isEven()) {
\r
34002 d = min(roughLOB(a), roughLOB(b));
\r
34005 c = c.multiply(d);
\r
34007 while (a.isEven()) {
\r
34008 a = a.divide(roughLOB(a));
\r
34011 while (b.isEven()) {
\r
34012 b = b.divide(roughLOB(b));
\r
34014 if (a.greater(b)) {
\r
34015 t = b; b = a; a = t;
\r
34017 b = b.subtract(a);
\r
34018 } while (!b.isZero());
\r
34019 return c.isUnit() ? a : a.multiply(c);
\r
34021 function lcm(a, b) {
\r
34022 a = parseValue(a).abs();
\r
34023 b = parseValue(b).abs();
\r
34024 return a.divide(gcd(a, b)).multiply(b);
\r
34026 function randBetween(a, b, rng) {
\r
34027 a = parseValue(a);
\r
34028 b = parseValue(b);
\r
34029 var usedRNG = rng || Math.random;
\r
34030 var low = min(a, b), high = max(a, b);
\r
34031 var range = high.subtract(low).add(1);
\r
34032 if (range.isSmall) return low.add(Math.floor(usedRNG() * range));
\r
34033 var digits = toBase(range, BASE).value;
\r
34034 var result = [], restricted = true;
\r
34035 for (var i = 0; i < digits.length; i++) {
\r
34036 var top = restricted ? digits[i] : BASE;
\r
34037 var digit = truncate(usedRNG() * top);
\r
34038 result.push(digit);
\r
34039 if (digit < top) restricted = false;
\r
34041 return low.add(Integer.fromArray(result, BASE, false));
\r
34044 var parseBase = function (text, base, alphabet, caseSensitive) {
\r
34045 alphabet = alphabet || DEFAULT_ALPHABET;
\r
34046 text = String(text);
\r
34047 if (!caseSensitive) {
\r
34048 text = text.toLowerCase();
\r
34049 alphabet = alphabet.toLowerCase();
\r
34051 var length = text.length;
\r
34053 var absBase = Math.abs(base);
\r
34054 var alphabetValues = {};
\r
34055 for (i = 0; i < alphabet.length; i++) {
\r
34056 alphabetValues[alphabet[i]] = i;
\r
34058 for (i = 0; i < length; i++) {
\r
34060 if (c === "-") continue;
\r
34061 if (c in alphabetValues) {
\r
34062 if (alphabetValues[c] >= absBase) {
\r
34063 if (c === "1" && absBase === 1) continue;
\r
34064 throw new Error(c + " is not a valid digit in base " + base + ".");
\r
34068 base = parseValue(base);
\r
34070 var isNegative = text[0] === "-";
\r
34071 for (i = isNegative ? 1 : 0; i < text.length; i++) {
\r
34073 if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));
\r
34074 else if (c === "<") {
\r
34076 do { i++; } while (text[i] !== ">" && i < text.length);
\r
34077 digits.push(parseValue(text.slice(start + 1, i)));
\r
34079 else throw new Error(c + " is not a valid character");
\r
34081 return parseBaseFromArray(digits, base, isNegative);
\r
34084 function parseBaseFromArray(digits, base, isNegative) {
\r
34085 var val = Integer[0], pow = Integer[1], i;
\r
34086 for (i = digits.length - 1; i >= 0; i--) {
\r
34087 val = val.add(digits[i].times(pow));
\r
34088 pow = pow.times(base);
\r
34090 return isNegative ? val.negate() : val;
\r
34093 function stringify(digit, alphabet) {
\r
34094 alphabet = alphabet || DEFAULT_ALPHABET;
\r
34095 if (digit < alphabet.length) {
\r
34096 return alphabet[digit];
\r
34098 return "<" + digit + ">";
\r
34101 function toBase(n, base) {
\r
34102 base = bigInt(base);
\r
34103 if (base.isZero()) {
\r
34104 if (n.isZero()) return { value: [0], isNegative: false };
\r
34105 throw new Error("Cannot convert nonzero numbers to base 0.");
\r
34107 if (base.equals(-1)) {
\r
34108 if (n.isZero()) return { value: [0], isNegative: false };
\r
34109 if (n.isNegative())
\r
34111 value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))
\r
34112 .map(Array.prototype.valueOf, [1, 0])
\r
34114 isNegative: false
\r
34117 var arr = Array.apply(null, Array(n.toJSNumber() - 1))
\r
34118 .map(Array.prototype.valueOf, [0, 1]);
\r
34119 arr.unshift([1]);
\r
34121 value: [].concat.apply([], arr),
\r
34122 isNegative: false
\r
34127 if (n.isNegative() && base.isPositive()) {
\r
34131 if (base.isUnit()) {
\r
34132 if (n.isZero()) return { value: [0], isNegative: false };
\r
34135 value: Array.apply(null, Array(n.toJSNumber()))
\r
34136 .map(Number.prototype.valueOf, 1),
\r
34141 var left = n, divmod;
\r
34142 while (left.isNegative() || left.compareAbs(base) >= 0) {
\r
34143 divmod = left.divmod(base);
\r
34144 left = divmod.quotient;
\r
34145 var digit = divmod.remainder;
\r
34146 if (digit.isNegative()) {
\r
34147 digit = base.minus(digit).abs();
\r
34148 left = left.next();
\r
34150 out.push(digit.toJSNumber());
\r
34152 out.push(left.toJSNumber());
\r
34153 return { value: out.reverse(), isNegative: neg };
\r
34156 function toBaseString(n, base, alphabet) {
\r
34157 var arr = toBase(n, base);
\r
34158 return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {
\r
34159 return stringify(x, alphabet);
\r
34163 BigInteger.prototype.toArray = function (radix) {
\r
34164 return toBase(this, radix);
\r
34167 SmallInteger.prototype.toArray = function (radix) {
\r
34168 return toBase(this, radix);
\r
34171 NativeBigInt.prototype.toArray = function (radix) {
\r
34172 return toBase(this, radix);
\r
34175 BigInteger.prototype.toString = function (radix, alphabet) {
\r
34176 if (radix === undefined) radix = 10;
\r
34177 if (radix !== 10) return toBaseString(this, radix, alphabet);
\r
34178 var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
\r
34179 while (--l >= 0) {
\r
34180 digit = String(v[l]);
\r
34181 str += zeros.slice(digit.length) + digit;
\r
34183 var sign = this.sign ? "-" : "";
\r
34184 return sign + str;
\r
34187 SmallInteger.prototype.toString = function (radix, alphabet) {
\r
34188 if (radix === undefined) radix = 10;
\r
34189 if (radix != 10) return toBaseString(this, radix, alphabet);
\r
34190 return String(this.value);
\r
34193 NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
\r
34195 NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }
\r
34197 BigInteger.prototype.valueOf = function () {
\r
34198 return parseInt(this.toString(), 10);
\r
34200 BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
\r
34202 SmallInteger.prototype.valueOf = function () {
\r
34203 return this.value;
\r
34205 SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
\r
34206 NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {
\r
34207 return parseInt(this.toString(), 10);
\r
34210 function parseStringValue(v) {
\r
34211 if (isPrecise(+v)) {
\r
34213 if (x === truncate(x))
\r
34214 return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
\r
34215 throw new Error("Invalid integer: " + v);
\r
34217 var sign = v[0] === "-";
\r
34218 if (sign) v = v.slice(1);
\r
34219 var split = v.split(/e/i);
\r
34220 if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
\r
34221 if (split.length === 2) {
\r
34222 var exp = split[1];
\r
34223 if (exp[0] === "+") exp = exp.slice(1);
\r
34225 if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
\r
34226 var text = split[0];
\r
34227 var decimalPlace = text.indexOf(".");
\r
34228 if (decimalPlace >= 0) {
\r
34229 exp -= text.length - decimalPlace - 1;
\r
34230 text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
\r
34232 if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
\r
34233 text += (new Array(exp + 1)).join("0");
\r
34236 var isValid = /^([0-9][0-9]*)$/.test(v);
\r
34237 if (!isValid) throw new Error("Invalid integer: " + v);
\r
34238 if (supportsNativeBigInt) {
\r
34239 return new NativeBigInt(BigInt(sign ? "-" + v : v));
\r
34241 var r = [], max = v.length, l = LOG_BASE, min = max - l;
\r
34242 while (max > 0) {
\r
34243 r.push(+v.slice(min, max));
\r
34245 if (min < 0) min = 0;
\r
34249 return new BigInteger(r, sign);
\r
34252 function parseNumberValue(v) {
\r
34253 if (supportsNativeBigInt) {
\r
34254 return new NativeBigInt(BigInt(v));
\r
34256 if (isPrecise(v)) {
\r
34257 if (v !== truncate(v)) throw new Error(v + " is not an integer.");
\r
34258 return new SmallInteger(v);
\r
34260 return parseStringValue(v.toString());
\r
34263 function parseValue(v) {
\r
34264 if (typeof v === "number") {
\r
34265 return parseNumberValue(v);
\r
34267 if (typeof v === "string") {
\r
34268 return parseStringValue(v);
\r
34270 if (typeof v === "bigint") {
\r
34271 return new NativeBigInt(v);
\r
34275 // Pre-define numbers in range [-999,999]
\r
34276 for (var i = 0; i < 1000; i++) {
\r
34277 Integer[i] = parseValue(i);
\r
34278 if (i > 0) Integer[-i] = parseValue(-i);
\r
34280 // Backwards compatibility
\r
34281 Integer.one = Integer[1];
\r
34282 Integer.zero = Integer[0];
\r
34283 Integer.minusOne = Integer[-1];
\r
34284 Integer.max = max;
\r
34285 Integer.min = min;
\r
34286 Integer.gcd = gcd;
\r
34287 Integer.lcm = lcm;
\r
34288 Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };
\r
34289 Integer.randBetween = randBetween;
\r
34291 Integer.fromArray = function (digits, base, isNegative) {
\r
34292 return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
\r
34299 if ( true && module.hasOwnProperty("exports")) {
\r
34300 module.exports = bigInt;
\r
34305 !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
\r
34307 }).call(exports, __webpack_require__, exports, module),
34308 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
\r
34311 /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(220)(module)))
34315 /***/ (function(module, exports) {
34317 module.exports = function(module) {
34318 if (!module.webpackPolyfill) {
34319 module.deprecate = function() {};
34321 // module.parent = undefined by default
34322 if (!module.children) module.children = [];
34323 Object.defineProperty(module, "loaded", {
34329 Object.defineProperty(module, "id", {
34335 module.webpackPolyfill = 1;
34343 /***/ (function(module, exports, __webpack_require__) {
34345 const isWindows = process.platform === 'win32' ||
34346 process.env.OSTYPE === 'cygwin' ||
34347 process.env.OSTYPE === 'msys'
34349 const path = __webpack_require__(2)
34350 const COLON = isWindows ? ';' : ':'
34351 const isexe = __webpack_require__(222)
34353 const getNotFoundError = (cmd) =>
34354 Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' })
34356 const getPathInfo = (cmd, opt) => {
34357 const colon = opt.colon || COLON
34359 // If it has a slash, then we don't bother searching the pathenv.
34360 // just check the file itself, and that's it.
34361 const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
34364 // windows always checks the cwd first
34365 ...(isWindows ? [process.cwd()] : []),
34366 ...(opt.path || process.env.PATH ||
34367 /* istanbul ignore next: very unusual */ '').split(colon),
34370 const pathExtExe = isWindows
34371 ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
34373 const pathExt = isWindows ? pathExtExe.split(colon) : ['']
34376 if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
34377 pathExt.unshift('')
34387 const which = (cmd, opt, cb) => {
34388 if (typeof opt === 'function') {
34395 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
34398 const step = i => new Promise((resolve, reject) => {
34399 if (i === pathEnv.length)
34400 return opt.all && found.length ? resolve(found)
34401 : reject(getNotFoundError(cmd))
34403 const ppRaw = pathEnv[i]
34404 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
34406 const pCmd = path.join(pathPart, cmd)
34407 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
34410 resolve(subStep(p, i, 0))
34413 const subStep = (p, i, ii) => new Promise((resolve, reject) => {
34414 if (ii === pathExt.length)
34415 return resolve(step(i + 1))
34416 const ext = pathExt[ii]
34417 isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
34420 found.push(p + ext)
34422 return resolve(p + ext)
34424 return resolve(subStep(p, i, ii + 1))
34428 return cb ? step(0).then(res => cb(null, res), cb) : step(0)
34431 const whichSync = (cmd, opt) => {
34434 const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt)
34437 for (let i = 0; i < pathEnv.length; i ++) {
34438 const ppRaw = pathEnv[i]
34439 const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw
34441 const pCmd = path.join(pathPart, cmd)
34442 const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
34445 for (let j = 0; j < pathExt.length; j ++) {
34446 const cur = p + pathExt[j]
34448 const is = isexe.sync(cur, { pathExt: pathExtExe })
34459 if (opt.all && found.length)
34465 throw getNotFoundError(cmd)
34468 module.exports = which
34469 which.sync = whichSync
34474 /***/ (function(module, exports, __webpack_require__) {
34476 var fs = __webpack_require__(42)
34478 if (process.platform === 'win32' || global.TESTING_WINDOWS) {
34479 core = __webpack_require__(223)
34481 core = __webpack_require__(224)
34484 module.exports = isexe
34487 function isexe (path, options, cb) {
34488 if (typeof options === 'function') {
34494 if (typeof Promise !== 'function') {
34495 throw new TypeError('callback not provided')
34498 return new Promise(function (resolve, reject) {
34499 isexe(path, options || {}, function (er, is) {
34509 core(path, options || {}, function (er, is) {
34510 // ignore EACCES because that just means we aren't allowed to run it
34512 if (er.code === 'EACCES' || options && options.ignoreErrors) {
34521 function sync (path, options) {
34522 // my kingdom for a filtered catch
34524 return core.sync(path, options || {})
34526 if (options && options.ignoreErrors || er.code === 'EACCES') {
34537 /***/ (function(module, exports, __webpack_require__) {
34539 module.exports = isexe
34542 var fs = __webpack_require__(42)
34544 function checkPathExt (path, options) {
34545 var pathext = options.pathExt !== undefined ?
34546 options.pathExt : process.env.PATHEXT
34552 pathext = pathext.split(';')
34553 if (pathext.indexOf('') !== -1) {
34556 for (var i = 0; i < pathext.length; i++) {
34557 var p = pathext[i].toLowerCase()
34558 if (p && path.substr(-p.length).toLowerCase() === p) {
34565 function checkStat (stat, path, options) {
34566 if (!stat.isSymbolicLink() && !stat.isFile()) {
34569 return checkPathExt(path, options)
34572 function isexe (path, options, cb) {
34573 fs.stat(path, function (er, stat) {
34574 cb(er, er ? false : checkStat(stat, path, options))
34578 function sync (path, options) {
34579 return checkStat(fs.statSync(path), path, options)
34585 /***/ (function(module, exports, __webpack_require__) {
34587 module.exports = isexe
34590 var fs = __webpack_require__(42)
34592 function isexe (path, options, cb) {
34593 fs.stat(path, function (er, stat) {
34594 cb(er, er ? false : checkStat(stat, options))
34598 function sync (path, options) {
34599 return checkStat(fs.statSync(path), options)
34602 function checkStat (stat, options) {
34603 return stat.isFile() && checkMode(stat, options)
34606 function checkMode (stat, options) {
34607 var mod = stat.mode
34611 var myUid = options.uid !== undefined ?
34612 options.uid : process.getuid && process.getuid()
34613 var myGid = options.gid !== undefined ?
34614 options.gid : process.getgid && process.getgid()
34616 var u = parseInt('100', 8)
34617 var g = parseInt('010', 8)
34618 var o = parseInt('001', 8)
34621 var ret = (mod & o) ||
34622 (mod & g) && gid === myGid ||
34623 (mod & u) && uid === myUid ||
34624 (mod & ug) && myUid === 0