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 = 33);
86 /************************************************************************/
90 /***/ (function(module, exports) {
92 module.exports = require("path");
96 /***/ (function(module, exports) {
98 module.exports = require("fs");
102 /***/ (function(module, exports, __webpack_require__) {
105 /* --------------------------------------------------------------------------------------------
\r
106 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
107 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
108 * ------------------------------------------------------------------------------------------ */
\r
110 function __export(m) {
\r
111 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
113 Object.defineProperty(exports, "__esModule", { value: true });
\r
114 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
115 exports.ErrorCodes = vscode_jsonrpc_1.ErrorCodes;
\r
116 exports.ResponseError = vscode_jsonrpc_1.ResponseError;
\r
117 exports.CancellationToken = vscode_jsonrpc_1.CancellationToken;
\r
118 exports.CancellationTokenSource = vscode_jsonrpc_1.CancellationTokenSource;
\r
119 exports.Disposable = vscode_jsonrpc_1.Disposable;
\r
120 exports.Event = vscode_jsonrpc_1.Event;
\r
121 exports.Emitter = vscode_jsonrpc_1.Emitter;
\r
122 exports.Trace = vscode_jsonrpc_1.Trace;
\r
123 exports.TraceFormat = vscode_jsonrpc_1.TraceFormat;
\r
124 exports.SetTraceNotification = vscode_jsonrpc_1.SetTraceNotification;
\r
125 exports.LogTraceNotification = vscode_jsonrpc_1.LogTraceNotification;
\r
126 exports.RequestType = vscode_jsonrpc_1.RequestType;
\r
127 exports.RequestType0 = vscode_jsonrpc_1.RequestType0;
\r
128 exports.NotificationType = vscode_jsonrpc_1.NotificationType;
\r
129 exports.NotificationType0 = vscode_jsonrpc_1.NotificationType0;
\r
130 exports.MessageReader = vscode_jsonrpc_1.MessageReader;
\r
131 exports.MessageWriter = vscode_jsonrpc_1.MessageWriter;
\r
132 exports.ConnectionStrategy = vscode_jsonrpc_1.ConnectionStrategy;
\r
133 exports.StreamMessageReader = vscode_jsonrpc_1.StreamMessageReader;
\r
134 exports.StreamMessageWriter = vscode_jsonrpc_1.StreamMessageWriter;
\r
135 exports.IPCMessageReader = vscode_jsonrpc_1.IPCMessageReader;
\r
136 exports.IPCMessageWriter = vscode_jsonrpc_1.IPCMessageWriter;
\r
137 exports.createClientPipeTransport = vscode_jsonrpc_1.createClientPipeTransport;
\r
138 exports.createServerPipeTransport = vscode_jsonrpc_1.createServerPipeTransport;
\r
139 exports.generateRandomPipeName = vscode_jsonrpc_1.generateRandomPipeName;
\r
140 exports.createClientSocketTransport = vscode_jsonrpc_1.createClientSocketTransport;
\r
141 exports.createServerSocketTransport = vscode_jsonrpc_1.createServerSocketTransport;
\r
142 __export(__webpack_require__(17));
\r
143 __export(__webpack_require__(18));
\r
144 const callHierarchy = __webpack_require__(27);
\r
145 const progress = __webpack_require__(28);
\r
146 const sr = __webpack_require__(29);
\r
148 (function (Proposed) {
\r
149 let SelectionRangeRequest;
\r
150 (function (SelectionRangeRequest) {
\r
151 SelectionRangeRequest.type = sr.SelectionRangeRequest.type;
\r
152 })(SelectionRangeRequest = Proposed.SelectionRangeRequest || (Proposed.SelectionRangeRequest = {}));
\r
153 let CallHierarchyRequest;
\r
154 (function (CallHierarchyRequest) {
\r
155 CallHierarchyRequest.type = callHierarchy.CallHierarchyRequest.type;
\r
156 })(CallHierarchyRequest = Proposed.CallHierarchyRequest || (Proposed.CallHierarchyRequest = {}));
\r
157 let CallHierarchyDirection;
\r
158 (function (CallHierarchyDirection) {
\r
159 CallHierarchyDirection.CallsFrom = callHierarchy.CallHierarchyDirection.CallsFrom;
\r
160 CallHierarchyDirection.CallsTo = callHierarchy.CallHierarchyDirection.CallsTo;
\r
161 })(CallHierarchyDirection = Proposed.CallHierarchyDirection || (Proposed.CallHierarchyDirection = {}));
\r
162 let ProgressStartNotification;
\r
163 (function (ProgressStartNotification) {
\r
164 ProgressStartNotification.type = progress.ProgressStartNotification.type;
\r
165 })(ProgressStartNotification = Proposed.ProgressStartNotification || (Proposed.ProgressStartNotification = {}));
\r
166 let ProgressReportNotification;
\r
167 (function (ProgressReportNotification) {
\r
168 ProgressReportNotification.type = progress.ProgressReportNotification.type;
\r
169 })(ProgressReportNotification = Proposed.ProgressReportNotification || (Proposed.ProgressReportNotification = {}));
\r
170 let ProgressDoneNotification;
\r
171 (function (ProgressDoneNotification) {
\r
172 ProgressDoneNotification.type = progress.ProgressDoneNotification.type;
\r
173 })(ProgressDoneNotification = Proposed.ProgressDoneNotification || (Proposed.ProgressDoneNotification = {}));
\r
174 let ProgressCancelNotification;
\r
175 (function (ProgressCancelNotification) {
\r
176 ProgressCancelNotification.type = progress.ProgressCancelNotification.type;
\r
177 })(ProgressCancelNotification = Proposed.ProgressCancelNotification || (Proposed.ProgressCancelNotification = {}));
\r
178 })(Proposed = exports.Proposed || (exports.Proposed = {}));
\r
179 function createProtocolConnection(reader, writer, logger, strategy) {
\r
180 return vscode_jsonrpc_1.createMessageConnection(reader, writer, logger, strategy);
\r
182 exports.createProtocolConnection = createProtocolConnection;
\r
187 /***/ (function(module, exports, __webpack_require__) {
190 /* --------------------------------------------------------------------------------------------
\r
191 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
192 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
193 * ------------------------------------------------------------------------------------------ */
\r
194 /// <reference path="./thenable.ts" />
\r
196 function __export(m) {
\r
197 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
199 Object.defineProperty(exports, "__esModule", { value: true });
\r
200 const Is = __webpack_require__(5);
\r
201 const messages_1 = __webpack_require__(6);
\r
202 exports.RequestType = messages_1.RequestType;
\r
203 exports.RequestType0 = messages_1.RequestType0;
\r
204 exports.RequestType1 = messages_1.RequestType1;
\r
205 exports.RequestType2 = messages_1.RequestType2;
\r
206 exports.RequestType3 = messages_1.RequestType3;
\r
207 exports.RequestType4 = messages_1.RequestType4;
\r
208 exports.RequestType5 = messages_1.RequestType5;
\r
209 exports.RequestType6 = messages_1.RequestType6;
\r
210 exports.RequestType7 = messages_1.RequestType7;
\r
211 exports.RequestType8 = messages_1.RequestType8;
\r
212 exports.RequestType9 = messages_1.RequestType9;
\r
213 exports.ResponseError = messages_1.ResponseError;
\r
214 exports.ErrorCodes = messages_1.ErrorCodes;
\r
215 exports.NotificationType = messages_1.NotificationType;
\r
216 exports.NotificationType0 = messages_1.NotificationType0;
\r
217 exports.NotificationType1 = messages_1.NotificationType1;
\r
218 exports.NotificationType2 = messages_1.NotificationType2;
\r
219 exports.NotificationType3 = messages_1.NotificationType3;
\r
220 exports.NotificationType4 = messages_1.NotificationType4;
\r
221 exports.NotificationType5 = messages_1.NotificationType5;
\r
222 exports.NotificationType6 = messages_1.NotificationType6;
\r
223 exports.NotificationType7 = messages_1.NotificationType7;
\r
224 exports.NotificationType8 = messages_1.NotificationType8;
\r
225 exports.NotificationType9 = messages_1.NotificationType9;
\r
226 const messageReader_1 = __webpack_require__(7);
\r
227 exports.MessageReader = messageReader_1.MessageReader;
\r
228 exports.StreamMessageReader = messageReader_1.StreamMessageReader;
\r
229 exports.IPCMessageReader = messageReader_1.IPCMessageReader;
\r
230 exports.SocketMessageReader = messageReader_1.SocketMessageReader;
\r
231 const messageWriter_1 = __webpack_require__(9);
\r
232 exports.MessageWriter = messageWriter_1.MessageWriter;
\r
233 exports.StreamMessageWriter = messageWriter_1.StreamMessageWriter;
\r
234 exports.IPCMessageWriter = messageWriter_1.IPCMessageWriter;
\r
235 exports.SocketMessageWriter = messageWriter_1.SocketMessageWriter;
\r
236 const events_1 = __webpack_require__(8);
\r
237 exports.Disposable = events_1.Disposable;
\r
238 exports.Event = events_1.Event;
\r
239 exports.Emitter = events_1.Emitter;
\r
240 const cancellation_1 = __webpack_require__(10);
\r
241 exports.CancellationTokenSource = cancellation_1.CancellationTokenSource;
\r
242 exports.CancellationToken = cancellation_1.CancellationToken;
\r
243 const linkedMap_1 = __webpack_require__(11);
\r
244 __export(__webpack_require__(12));
\r
245 __export(__webpack_require__(16));
\r
246 var CancelNotification;
\r
247 (function (CancelNotification) {
\r
248 CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');
\r
249 })(CancelNotification || (CancelNotification = {}));
\r
250 exports.NullLogger = Object.freeze({
\r
257 (function (Trace) {
\r
258 Trace[Trace["Off"] = 0] = "Off";
\r
259 Trace[Trace["Messages"] = 1] = "Messages";
\r
260 Trace[Trace["Verbose"] = 2] = "Verbose";
\r
261 })(Trace = exports.Trace || (exports.Trace = {}));
\r
262 (function (Trace) {
\r
263 function fromString(value) {
\r
264 value = value.toLowerCase();
\r
269 return Trace.Messages;
\r
271 return Trace.Verbose;
\r
276 Trace.fromString = fromString;
\r
277 function toString(value) {
\r
281 case Trace.Messages:
\r
283 case Trace.Verbose:
\r
289 Trace.toString = toString;
\r
290 })(Trace = exports.Trace || (exports.Trace = {}));
\r
292 (function (TraceFormat) {
\r
293 TraceFormat["Text"] = "text";
\r
294 TraceFormat["JSON"] = "json";
\r
295 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
296 (function (TraceFormat) {
\r
297 function fromString(value) {
\r
298 value = value.toLowerCase();
\r
299 if (value === 'json') {
\r
300 return TraceFormat.JSON;
\r
303 return TraceFormat.Text;
\r
306 TraceFormat.fromString = fromString;
\r
307 })(TraceFormat = exports.TraceFormat || (exports.TraceFormat = {}));
\r
308 var SetTraceNotification;
\r
309 (function (SetTraceNotification) {
\r
310 SetTraceNotification.type = new messages_1.NotificationType('$/setTraceNotification');
\r
311 })(SetTraceNotification = exports.SetTraceNotification || (exports.SetTraceNotification = {}));
\r
312 var LogTraceNotification;
\r
313 (function (LogTraceNotification) {
\r
314 LogTraceNotification.type = new messages_1.NotificationType('$/logTraceNotification');
\r
315 })(LogTraceNotification = exports.LogTraceNotification || (exports.LogTraceNotification = {}));
\r
316 var ConnectionErrors;
\r
317 (function (ConnectionErrors) {
\r
319 * The connection is closed.
\r
321 ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
\r
323 * The connection got disposed.
\r
325 ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
\r
327 * The connection is already in listening mode.
\r
329 ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
\r
330 })(ConnectionErrors = exports.ConnectionErrors || (exports.ConnectionErrors = {}));
\r
331 class ConnectionError extends Error {
\r
332 constructor(code, message) {
\r
335 Object.setPrototypeOf(this, ConnectionError.prototype);
\r
338 exports.ConnectionError = ConnectionError;
\r
339 var ConnectionStrategy;
\r
340 (function (ConnectionStrategy) {
\r
341 function is(value) {
\r
342 let candidate = value;
\r
343 return candidate && Is.func(candidate.cancelUndispatched);
\r
345 ConnectionStrategy.is = is;
\r
346 })(ConnectionStrategy = exports.ConnectionStrategy || (exports.ConnectionStrategy = {}));
\r
347 var ConnectionState;
\r
348 (function (ConnectionState) {
\r
349 ConnectionState[ConnectionState["New"] = 1] = "New";
\r
350 ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
\r
351 ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
\r
352 ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
\r
353 })(ConnectionState || (ConnectionState = {}));
\r
354 function _createMessageConnection(messageReader, messageWriter, logger, strategy) {
\r
355 let sequenceNumber = 0;
\r
356 let notificationSquenceNumber = 0;
\r
357 let unknownResponseSquenceNumber = 0;
\r
358 const version = '2.0';
\r
359 let starRequestHandler = undefined;
\r
360 let requestHandlers = Object.create(null);
\r
361 let starNotificationHandler = undefined;
\r
362 let notificationHandlers = Object.create(null);
\r
364 let messageQueue = new linkedMap_1.LinkedMap();
\r
365 let responsePromises = Object.create(null);
\r
366 let requestTokens = Object.create(null);
\r
367 let trace = Trace.Off;
\r
368 let traceFormat = TraceFormat.Text;
\r
370 let state = ConnectionState.New;
\r
371 let errorEmitter = new events_1.Emitter();
\r
372 let closeEmitter = new events_1.Emitter();
\r
373 let unhandledNotificationEmitter = new events_1.Emitter();
\r
374 let disposeEmitter = new events_1.Emitter();
\r
375 function createRequestQueueKey(id) {
\r
376 return 'req-' + id.toString();
\r
378 function createResponseQueueKey(id) {
\r
380 return 'res-unknown-' + (++unknownResponseSquenceNumber).toString();
\r
383 return 'res-' + id.toString();
\r
386 function createNotificationQueueKey() {
\r
387 return 'not-' + (++notificationSquenceNumber).toString();
\r
389 function addMessageToQueue(queue, message) {
\r
390 if (messages_1.isRequestMessage(message)) {
\r
391 queue.set(createRequestQueueKey(message.id), message);
\r
393 else if (messages_1.isResponseMessage(message)) {
\r
394 queue.set(createResponseQueueKey(message.id), message);
\r
397 queue.set(createNotificationQueueKey(), message);
\r
400 function cancelUndispatched(_message) {
\r
403 function isListening() {
\r
404 return state === ConnectionState.Listening;
\r
406 function isClosed() {
\r
407 return state === ConnectionState.Closed;
\r
409 function isDisposed() {
\r
410 return state === ConnectionState.Disposed;
\r
412 function closeHandler() {
\r
413 if (state === ConnectionState.New || state === ConnectionState.Listening) {
\r
414 state = ConnectionState.Closed;
\r
415 closeEmitter.fire(undefined);
\r
417 // If the connection is disposed don't sent close events.
\r
420 function readErrorHandler(error) {
\r
421 errorEmitter.fire([error, undefined, undefined]);
\r
423 function writeErrorHandler(data) {
\r
424 errorEmitter.fire(data);
\r
426 messageReader.onClose(closeHandler);
\r
427 messageReader.onError(readErrorHandler);
\r
428 messageWriter.onClose(closeHandler);
\r
429 messageWriter.onError(writeErrorHandler);
\r
430 function triggerMessageQueue() {
\r
431 if (timer || messageQueue.size === 0) {
\r
434 timer = setImmediate(() => {
\r
436 processMessageQueue();
\r
439 function processMessageQueue() {
\r
440 if (messageQueue.size === 0) {
\r
443 let message = messageQueue.shift();
\r
445 if (messages_1.isRequestMessage(message)) {
\r
446 handleRequest(message);
\r
448 else if (messages_1.isNotificationMessage(message)) {
\r
449 handleNotification(message);
\r
451 else if (messages_1.isResponseMessage(message)) {
\r
452 handleResponse(message);
\r
455 handleInvalidMessage(message);
\r
459 triggerMessageQueue();
\r
462 let callback = (message) => {
\r
464 // We have received a cancellation message. Check if the message is still in the queue
\r
465 // and cancel it if allowed to do so.
\r
466 if (messages_1.isNotificationMessage(message) && message.method === CancelNotification.type.method) {
\r
467 let key = createRequestQueueKey(message.params.id);
\r
468 let toCancel = messageQueue.get(key);
\r
469 if (messages_1.isRequestMessage(toCancel)) {
\r
470 let response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
\r
471 if (response && (response.error !== void 0 || response.result !== void 0)) {
\r
472 messageQueue.delete(key);
\r
473 response.id = toCancel.id;
\r
474 traceSendingResponse(response, message.method, Date.now());
\r
475 messageWriter.write(response);
\r
480 addMessageToQueue(messageQueue, message);
\r
483 triggerMessageQueue();
\r
486 function handleRequest(requestMessage) {
\r
487 if (isDisposed()) {
\r
488 // we return here silently since we fired an event when the
\r
489 // connection got disposed.
\r
492 function reply(resultOrError, method, startTime) {
\r
495 id: requestMessage.id
\r
497 if (resultOrError instanceof messages_1.ResponseError) {
\r
498 message.error = resultOrError.toJson();
\r
501 message.result = resultOrError === void 0 ? null : resultOrError;
\r
503 traceSendingResponse(message, method, startTime);
\r
504 messageWriter.write(message);
\r
506 function replyError(error, method, startTime) {
\r
509 id: requestMessage.id,
\r
510 error: error.toJson()
\r
512 traceSendingResponse(message, method, startTime);
\r
513 messageWriter.write(message);
\r
515 function replySuccess(result, method, startTime) {
\r
516 // The JSON RPC defines that a response must either have a result or an error
\r
517 // So we can't treat undefined as a valid response result.
\r
518 if (result === void 0) {
\r
523 id: requestMessage.id,
\r
526 traceSendingResponse(message, method, startTime);
\r
527 messageWriter.write(message);
\r
529 traceReceivedRequest(requestMessage);
\r
530 let element = requestHandlers[requestMessage.method];
\r
532 let requestHandler;
\r
534 type = element.type;
\r
535 requestHandler = element.handler;
\r
537 let startTime = Date.now();
\r
538 if (requestHandler || starRequestHandler) {
\r
539 let cancellationSource = new cancellation_1.CancellationTokenSource();
\r
540 let tokenKey = String(requestMessage.id);
\r
541 requestTokens[tokenKey] = cancellationSource;
\r
544 if (requestMessage.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
545 handlerResult = requestHandler
\r
546 ? requestHandler(cancellationSource.token)
\r
547 : starRequestHandler(requestMessage.method, cancellationSource.token);
\r
549 else if (Is.array(requestMessage.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
550 handlerResult = requestHandler
\r
551 ? requestHandler(...requestMessage.params, cancellationSource.token)
\r
552 : starRequestHandler(requestMessage.method, ...requestMessage.params, cancellationSource.token);
\r
555 handlerResult = requestHandler
\r
556 ? requestHandler(requestMessage.params, cancellationSource.token)
\r
557 : starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
\r
559 let promise = handlerResult;
\r
560 if (!handlerResult) {
\r
561 delete requestTokens[tokenKey];
\r
562 replySuccess(handlerResult, requestMessage.method, startTime);
\r
564 else if (promise.then) {
\r
565 promise.then((resultOrError) => {
\r
566 delete requestTokens[tokenKey];
\r
567 reply(resultOrError, requestMessage.method, startTime);
\r
569 delete requestTokens[tokenKey];
\r
570 if (error instanceof messages_1.ResponseError) {
\r
571 replyError(error, requestMessage.method, startTime);
\r
573 else if (error && Is.string(error.message)) {
\r
574 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
577 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
582 delete requestTokens[tokenKey];
\r
583 reply(handlerResult, requestMessage.method, startTime);
\r
587 delete requestTokens[tokenKey];
\r
588 if (error instanceof messages_1.ResponseError) {
\r
589 reply(error, requestMessage.method, startTime);
\r
591 else if (error && Is.string(error.message)) {
\r
592 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
\r
595 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
\r
600 replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
\r
603 function handleResponse(responseMessage) {
\r
604 if (isDisposed()) {
\r
605 // See handle request.
\r
608 if (responseMessage.id === null) {
\r
609 if (responseMessage.error) {
\r
610 logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`);
\r
613 logger.error(`Received response message without id. No further error information provided.`);
\r
617 let key = String(responseMessage.id);
\r
618 let responsePromise = responsePromises[key];
\r
619 traceReceivedResponse(responseMessage, responsePromise);
\r
620 if (responsePromise) {
\r
621 delete responsePromises[key];
\r
623 if (responseMessage.error) {
\r
624 let error = responseMessage.error;
\r
625 responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
\r
627 else if (responseMessage.result !== void 0) {
\r
628 responsePromise.resolve(responseMessage.result);
\r
631 throw new Error('Should never happen.');
\r
635 if (error.message) {
\r
636 logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
\r
639 logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
\r
645 function handleNotification(message) {
\r
646 if (isDisposed()) {
\r
647 // See handle request.
\r
650 let type = undefined;
\r
651 let notificationHandler;
\r
652 if (message.method === CancelNotification.type.method) {
\r
653 notificationHandler = (params) => {
\r
654 let id = params.id;
\r
655 let source = requestTokens[String(id)];
\r
662 let element = notificationHandlers[message.method];
\r
664 notificationHandler = element.handler;
\r
665 type = element.type;
\r
668 if (notificationHandler || starNotificationHandler) {
\r
670 traceReceivedNotification(message);
\r
671 if (message.params === void 0 || (type !== void 0 && type.numberOfParams === 0)) {
\r
672 notificationHandler ? notificationHandler() : starNotificationHandler(message.method);
\r
674 else if (Is.array(message.params) && (type === void 0 || type.numberOfParams > 1)) {
\r
675 notificationHandler ? notificationHandler(...message.params) : starNotificationHandler(message.method, ...message.params);
\r
678 notificationHandler ? notificationHandler(message.params) : starNotificationHandler(message.method, message.params);
\r
682 if (error.message) {
\r
683 logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
\r
686 logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
\r
691 unhandledNotificationEmitter.fire(message);
\r
694 function handleInvalidMessage(message) {
\r
696 logger.error('Received empty message.');
\r
699 logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
\r
700 // Test whether we find an id to reject the promise
\r
701 let responseMessage = message;
\r
702 if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
\r
703 let key = String(responseMessage.id);
\r
704 let responseHandler = responsePromises[key];
\r
705 if (responseHandler) {
\r
706 responseHandler.reject(new Error('The received response has neither a result nor an error property.'));
\r
710 function traceSendingRequest(message) {
\r
711 if (trace === Trace.Off || !tracer) {
\r
714 if (traceFormat === TraceFormat.Text) {
\r
715 let data = undefined;
\r
716 if (trace === Trace.Verbose && message.params) {
\r
717 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
719 tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
\r
722 logLSPMessage('send-request', message);
\r
725 function traceSendingNotification(message) {
\r
726 if (trace === Trace.Off || !tracer) {
\r
729 if (traceFormat === TraceFormat.Text) {
\r
730 let data = undefined;
\r
731 if (trace === Trace.Verbose) {
\r
732 if (message.params) {
\r
733 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
736 data = 'No parameters provided.\n\n';
\r
739 tracer.log(`Sending notification '${message.method}'.`, data);
\r
742 logLSPMessage('send-notification', message);
\r
745 function traceSendingResponse(message, method, startTime) {
\r
746 if (trace === Trace.Off || !tracer) {
\r
749 if (traceFormat === TraceFormat.Text) {
\r
750 let data = undefined;
\r
751 if (trace === Trace.Verbose) {
\r
752 if (message.error && message.error.data) {
\r
753 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
756 if (message.result) {
\r
757 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
759 else if (message.error === void 0) {
\r
760 data = 'No result returned.\n\n';
\r
764 tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
\r
767 logLSPMessage('send-response', message);
\r
770 function traceReceivedRequest(message) {
\r
771 if (trace === Trace.Off || !tracer) {
\r
774 if (traceFormat === TraceFormat.Text) {
\r
775 let data = undefined;
\r
776 if (trace === Trace.Verbose && message.params) {
\r
777 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
779 tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
\r
782 logLSPMessage('receive-request', message);
\r
785 function traceReceivedNotification(message) {
\r
786 if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
\r
789 if (traceFormat === TraceFormat.Text) {
\r
790 let data = undefined;
\r
791 if (trace === Trace.Verbose) {
\r
792 if (message.params) {
\r
793 data = `Params: ${JSON.stringify(message.params, null, 4)}\n\n`;
\r
796 data = 'No parameters provided.\n\n';
\r
799 tracer.log(`Received notification '${message.method}'.`, data);
\r
802 logLSPMessage('receive-notification', message);
\r
805 function traceReceivedResponse(message, responsePromise) {
\r
806 if (trace === Trace.Off || !tracer) {
\r
809 if (traceFormat === TraceFormat.Text) {
\r
810 let data = undefined;
\r
811 if (trace === Trace.Verbose) {
\r
812 if (message.error && message.error.data) {
\r
813 data = `Error data: ${JSON.stringify(message.error.data, null, 4)}\n\n`;
\r
816 if (message.result) {
\r
817 data = `Result: ${JSON.stringify(message.result, null, 4)}\n\n`;
\r
819 else if (message.error === void 0) {
\r
820 data = 'No result returned.\n\n';
\r
824 if (responsePromise) {
\r
825 let error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : '';
\r
826 tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
\r
829 tracer.log(`Received response ${message.id} without active response promise.`, data);
\r
833 logLSPMessage('receive-response', message);
\r
836 function logLSPMessage(type, message) {
\r
837 if (!tracer || trace === Trace.Off) {
\r
840 const lspMessage = {
\r
841 isLSPMessage: true,
\r
844 timestamp: Date.now()
\r
846 tracer.log(lspMessage);
\r
848 function throwIfClosedOrDisposed() {
\r
850 throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.');
\r
852 if (isDisposed()) {
\r
853 throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.');
\r
856 function throwIfListening() {
\r
857 if (isListening()) {
\r
858 throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening');
\r
861 function throwIfNotListening() {
\r
862 if (!isListening()) {
\r
863 throw new Error('Call listen() first.');
\r
866 function undefinedToNull(param) {
\r
867 if (param === void 0) {
\r
874 function computeMessageParams(type, params) {
\r
876 let numberOfParams = type.numberOfParams;
\r
877 switch (numberOfParams) {
\r
882 result = undefinedToNull(params[0]);
\r
886 for (let i = 0; i < params.length && i < numberOfParams; i++) {
\r
887 result.push(undefinedToNull(params[i]));
\r
889 if (params.length < numberOfParams) {
\r
890 for (let i = params.length; i < numberOfParams; i++) {
\r
899 sendNotification: (type, ...params) => {
\r
900 throwIfClosedOrDisposed();
\r
903 if (Is.string(type)) {
\r
905 switch (params.length) {
\r
907 messageParams = null;
\r
910 messageParams = params[0];
\r
913 messageParams = params;
\r
918 method = type.method;
\r
919 messageParams = computeMessageParams(type, params);
\r
921 let notificationMessage = {
\r
924 params: messageParams
\r
926 traceSendingNotification(notificationMessage);
\r
927 messageWriter.write(notificationMessage);
\r
929 onNotification: (type, handler) => {
\r
930 throwIfClosedOrDisposed();
\r
931 if (Is.func(type)) {
\r
932 starNotificationHandler = type;
\r
934 else if (handler) {
\r
935 if (Is.string(type)) {
\r
936 notificationHandlers[type] = { type: undefined, handler };
\r
939 notificationHandlers[type.method] = { type, handler };
\r
943 sendRequest: (type, ...params) => {
\r
944 throwIfClosedOrDisposed();
\r
945 throwIfNotListening();
\r
948 let token = undefined;
\r
949 if (Is.string(type)) {
\r
951 switch (params.length) {
\r
953 messageParams = null;
\r
956 // The cancellation token is optional so it can also be undefined.
\r
957 if (cancellation_1.CancellationToken.is(params[0])) {
\r
958 messageParams = null;
\r
962 messageParams = undefinedToNull(params[0]);
\r
966 const last = params.length - 1;
\r
967 if (cancellation_1.CancellationToken.is(params[last])) {
\r
968 token = params[last];
\r
969 if (params.length === 2) {
\r
970 messageParams = undefinedToNull(params[0]);
\r
973 messageParams = params.slice(0, last).map(value => undefinedToNull(value));
\r
977 messageParams = params.map(value => undefinedToNull(value));
\r
983 method = type.method;
\r
984 messageParams = computeMessageParams(type, params);
\r
985 let numberOfParams = type.numberOfParams;
\r
986 token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined;
\r
988 let id = sequenceNumber++;
\r
989 let result = new Promise((resolve, reject) => {
\r
990 let requestMessage = {
\r
994 params: messageParams
\r
996 let responsePromise = { method: method, timerStart: Date.now(), resolve, reject };
\r
997 traceSendingRequest(requestMessage);
\r
999 messageWriter.write(requestMessage);
\r
1002 // Writing the message failed. So we need to reject the promise.
\r
1003 responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, e.message ? e.message : 'Unknown reason'));
\r
1004 responsePromise = null;
\r
1006 if (responsePromise) {
\r
1007 responsePromises[String(id)] = responsePromise;
\r
1011 token.onCancellationRequested(() => {
\r
1012 connection.sendNotification(CancelNotification.type, { id });
\r
1017 onRequest: (type, handler) => {
\r
1018 throwIfClosedOrDisposed();
\r
1019 if (Is.func(type)) {
\r
1020 starRequestHandler = type;
\r
1022 else if (handler) {
\r
1023 if (Is.string(type)) {
\r
1024 requestHandlers[type] = { type: undefined, handler };
\r
1027 requestHandlers[type.method] = { type, handler };
\r
1031 trace: (_value, _tracer, sendNotificationOrTraceOptions) => {
\r
1032 let _sendNotification = false;
\r
1033 let _traceFormat = TraceFormat.Text;
\r
1034 if (sendNotificationOrTraceOptions !== void 0) {
\r
1035 if (Is.boolean(sendNotificationOrTraceOptions)) {
\r
1036 _sendNotification = sendNotificationOrTraceOptions;
\r
1039 _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
\r
1040 _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
\r
1044 traceFormat = _traceFormat;
\r
1045 if (trace === Trace.Off) {
\r
1046 tracer = undefined;
\r
1051 if (_sendNotification && !isClosed() && !isDisposed()) {
\r
1052 connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
\r
1055 onError: errorEmitter.event,
\r
1056 onClose: closeEmitter.event,
\r
1057 onUnhandledNotification: unhandledNotificationEmitter.event,
\r
1058 onDispose: disposeEmitter.event,
\r
1060 if (isDisposed()) {
\r
1063 state = ConnectionState.Disposed;
\r
1064 disposeEmitter.fire(undefined);
\r
1065 let error = new Error('Connection got disposed.');
\r
1066 Object.keys(responsePromises).forEach((key) => {
\r
1067 responsePromises[key].reject(error);
\r
1069 responsePromises = Object.create(null);
\r
1070 requestTokens = Object.create(null);
\r
1071 messageQueue = new linkedMap_1.LinkedMap();
\r
1072 // Test for backwards compatibility
\r
1073 if (Is.func(messageWriter.dispose)) {
\r
1074 messageWriter.dispose();
\r
1076 if (Is.func(messageReader.dispose)) {
\r
1077 messageReader.dispose();
\r
1081 throwIfClosedOrDisposed();
\r
1082 throwIfListening();
\r
1083 state = ConnectionState.Listening;
\r
1084 messageReader.listen(callback);
\r
1087 console.log("inspect");
\r
1090 connection.onNotification(LogTraceNotification.type, (params) => {
\r
1091 if (trace === Trace.Off || !tracer) {
\r
1094 tracer.log(params.message, trace === Trace.Verbose ? params.verbose : undefined);
\r
1096 return connection;
\r
1098 function isMessageReader(value) {
\r
1099 return value.listen !== void 0 && value.read === void 0;
\r
1101 function isMessageWriter(value) {
\r
1102 return value.write !== void 0 && value.end === void 0;
\r
1104 function createMessageConnection(input, output, logger, strategy) {
\r
1106 logger = exports.NullLogger;
\r
1108 let reader = isMessageReader(input) ? input : new messageReader_1.StreamMessageReader(input);
\r
1109 let writer = isMessageWriter(output) ? output : new messageWriter_1.StreamMessageWriter(output);
\r
1110 return _createMessageConnection(reader, writer, logger, strategy);
\r
1112 exports.createMessageConnection = createMessageConnection;
\r
1117 /***/ (function(module, exports, __webpack_require__) {
1120 /* --------------------------------------------------------------------------------------------
\r
1121 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1122 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1123 * ------------------------------------------------------------------------------------------ */
\r
1125 Object.defineProperty(exports, "__esModule", { value: true });
\r
1126 function boolean(value) {
\r
1127 return value === true || value === false;
\r
1129 exports.boolean = boolean;
\r
1130 function string(value) {
\r
1131 return typeof value === 'string' || value instanceof String;
\r
1133 exports.string = string;
\r
1134 function number(value) {
\r
1135 return typeof value === 'number' || value instanceof Number;
\r
1137 exports.number = number;
\r
1138 function error(value) {
\r
1139 return value instanceof Error;
\r
1141 exports.error = error;
\r
1142 function func(value) {
\r
1143 return typeof value === 'function';
\r
1145 exports.func = func;
\r
1146 function array(value) {
\r
1147 return Array.isArray(value);
\r
1149 exports.array = array;
\r
1150 function stringArray(value) {
\r
1151 return array(value) && value.every(elem => string(elem));
\r
1153 exports.stringArray = stringArray;
\r
1158 /***/ (function(module, exports, __webpack_require__) {
1161 /* --------------------------------------------------------------------------------------------
\r
1162 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1163 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1164 * ------------------------------------------------------------------------------------------ */
\r
1166 Object.defineProperty(exports, "__esModule", { value: true });
\r
1167 const is = __webpack_require__(5);
\r
1169 * Predefined error codes.
\r
1172 (function (ErrorCodes) {
\r
1173 // Defined by JSON RPC
\r
1174 ErrorCodes.ParseError = -32700;
\r
1175 ErrorCodes.InvalidRequest = -32600;
\r
1176 ErrorCodes.MethodNotFound = -32601;
\r
1177 ErrorCodes.InvalidParams = -32602;
\r
1178 ErrorCodes.InternalError = -32603;
\r
1179 ErrorCodes.serverErrorStart = -32099;
\r
1180 ErrorCodes.serverErrorEnd = -32000;
\r
1181 ErrorCodes.ServerNotInitialized = -32002;
\r
1182 ErrorCodes.UnknownErrorCode = -32001;
\r
1183 // Defined by the protocol.
\r
1184 ErrorCodes.RequestCancelled = -32800;
\r
1185 ErrorCodes.ContentModified = -32801;
\r
1186 // Defined by VSCode library.
\r
1187 ErrorCodes.MessageWriteError = 1;
\r
1188 ErrorCodes.MessageReadError = 2;
\r
1189 })(ErrorCodes = exports.ErrorCodes || (exports.ErrorCodes = {}));
\r
1191 * An error object return in a response in case a request
\r
1194 class ResponseError extends Error {
\r
1195 constructor(code, message, data) {
\r
1197 this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
\r
1199 Object.setPrototypeOf(this, ResponseError.prototype);
\r
1204 message: this.message,
\r
1209 exports.ResponseError = ResponseError;
\r
1211 * An abstract implementation of a MessageType.
\r
1213 class AbstractMessageType {
\r
1214 constructor(_method, _numberOfParams) {
\r
1215 this._method = _method;
\r
1216 this._numberOfParams = _numberOfParams;
\r
1219 return this._method;
\r
1221 get numberOfParams() {
\r
1222 return this._numberOfParams;
\r
1225 exports.AbstractMessageType = AbstractMessageType;
\r
1227 * Classes to type request response pairs
\r
1229 class RequestType0 extends AbstractMessageType {
\r
1230 constructor(method) {
\r
1232 this._ = undefined;
\r
1235 exports.RequestType0 = RequestType0;
\r
1236 class RequestType extends AbstractMessageType {
\r
1237 constructor(method) {
\r
1239 this._ = undefined;
\r
1242 exports.RequestType = RequestType;
\r
1243 class RequestType1 extends AbstractMessageType {
\r
1244 constructor(method) {
\r
1246 this._ = undefined;
\r
1249 exports.RequestType1 = RequestType1;
\r
1250 class RequestType2 extends AbstractMessageType {
\r
1251 constructor(method) {
\r
1253 this._ = undefined;
\r
1256 exports.RequestType2 = RequestType2;
\r
1257 class RequestType3 extends AbstractMessageType {
\r
1258 constructor(method) {
\r
1260 this._ = undefined;
\r
1263 exports.RequestType3 = RequestType3;
\r
1264 class RequestType4 extends AbstractMessageType {
\r
1265 constructor(method) {
\r
1267 this._ = undefined;
\r
1270 exports.RequestType4 = RequestType4;
\r
1271 class RequestType5 extends AbstractMessageType {
\r
1272 constructor(method) {
\r
1274 this._ = undefined;
\r
1277 exports.RequestType5 = RequestType5;
\r
1278 class RequestType6 extends AbstractMessageType {
\r
1279 constructor(method) {
\r
1281 this._ = undefined;
\r
1284 exports.RequestType6 = RequestType6;
\r
1285 class RequestType7 extends AbstractMessageType {
\r
1286 constructor(method) {
\r
1288 this._ = undefined;
\r
1291 exports.RequestType7 = RequestType7;
\r
1292 class RequestType8 extends AbstractMessageType {
\r
1293 constructor(method) {
\r
1295 this._ = undefined;
\r
1298 exports.RequestType8 = RequestType8;
\r
1299 class RequestType9 extends AbstractMessageType {
\r
1300 constructor(method) {
\r
1302 this._ = undefined;
\r
1305 exports.RequestType9 = RequestType9;
\r
1306 class NotificationType extends AbstractMessageType {
\r
1307 constructor(method) {
\r
1309 this._ = undefined;
\r
1312 exports.NotificationType = NotificationType;
\r
1313 class NotificationType0 extends AbstractMessageType {
\r
1314 constructor(method) {
\r
1316 this._ = undefined;
\r
1319 exports.NotificationType0 = NotificationType0;
\r
1320 class NotificationType1 extends AbstractMessageType {
\r
1321 constructor(method) {
\r
1323 this._ = undefined;
\r
1326 exports.NotificationType1 = NotificationType1;
\r
1327 class NotificationType2 extends AbstractMessageType {
\r
1328 constructor(method) {
\r
1330 this._ = undefined;
\r
1333 exports.NotificationType2 = NotificationType2;
\r
1334 class NotificationType3 extends AbstractMessageType {
\r
1335 constructor(method) {
\r
1337 this._ = undefined;
\r
1340 exports.NotificationType3 = NotificationType3;
\r
1341 class NotificationType4 extends AbstractMessageType {
\r
1342 constructor(method) {
\r
1344 this._ = undefined;
\r
1347 exports.NotificationType4 = NotificationType4;
\r
1348 class NotificationType5 extends AbstractMessageType {
\r
1349 constructor(method) {
\r
1351 this._ = undefined;
\r
1354 exports.NotificationType5 = NotificationType5;
\r
1355 class NotificationType6 extends AbstractMessageType {
\r
1356 constructor(method) {
\r
1358 this._ = undefined;
\r
1361 exports.NotificationType6 = NotificationType6;
\r
1362 class NotificationType7 extends AbstractMessageType {
\r
1363 constructor(method) {
\r
1365 this._ = undefined;
\r
1368 exports.NotificationType7 = NotificationType7;
\r
1369 class NotificationType8 extends AbstractMessageType {
\r
1370 constructor(method) {
\r
1372 this._ = undefined;
\r
1375 exports.NotificationType8 = NotificationType8;
\r
1376 class NotificationType9 extends AbstractMessageType {
\r
1377 constructor(method) {
\r
1379 this._ = undefined;
\r
1382 exports.NotificationType9 = NotificationType9;
\r
1384 * Tests if the given message is a request message
\r
1386 function isRequestMessage(message) {
\r
1387 let candidate = message;
\r
1388 return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
\r
1390 exports.isRequestMessage = isRequestMessage;
\r
1392 * Tests if the given message is a notification message
\r
1394 function isNotificationMessage(message) {
\r
1395 let candidate = message;
\r
1396 return candidate && is.string(candidate.method) && message.id === void 0;
\r
1398 exports.isNotificationMessage = isNotificationMessage;
\r
1400 * Tests if the given message is a response message
\r
1402 function isResponseMessage(message) {
\r
1403 let candidate = message;
\r
1404 return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
\r
1406 exports.isResponseMessage = isResponseMessage;
\r
1411 /***/ (function(module, exports, __webpack_require__) {
1414 /* --------------------------------------------------------------------------------------------
\r
1415 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1416 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1417 * ------------------------------------------------------------------------------------------ */
\r
1419 Object.defineProperty(exports, "__esModule", { value: true });
\r
1420 const events_1 = __webpack_require__(8);
\r
1421 const Is = __webpack_require__(5);
\r
1422 let DefaultSize = 8192;
\r
1423 let CR = Buffer.from('\r', 'ascii')[0];
\r
1424 let LF = Buffer.from('\n', 'ascii')[0];
\r
1425 let CRLF = '\r\n';
\r
1426 class MessageBuffer {
\r
1427 constructor(encoding = 'utf8') {
\r
1428 this.encoding = encoding;
\r
1430 this.buffer = Buffer.allocUnsafe(DefaultSize);
\r
1433 var toAppend = chunk;
\r
1434 if (typeof (chunk) === 'string') {
\r
1436 var bufferLen = Buffer.byteLength(str, this.encoding);
\r
1437 toAppend = Buffer.allocUnsafe(bufferLen);
\r
1438 toAppend.write(str, 0, bufferLen, this.encoding);
\r
1440 if (this.buffer.length - this.index >= toAppend.length) {
\r
1441 toAppend.copy(this.buffer, this.index, 0, toAppend.length);
\r
1444 var newSize = (Math.ceil((this.index + toAppend.length) / DefaultSize) + 1) * DefaultSize;
\r
1445 if (this.index === 0) {
\r
1446 this.buffer = Buffer.allocUnsafe(newSize);
\r
1447 toAppend.copy(this.buffer, 0, 0, toAppend.length);
\r
1450 this.buffer = Buffer.concat([this.buffer.slice(0, this.index), toAppend], newSize);
\r
1453 this.index += toAppend.length;
\r
1455 tryReadHeaders() {
\r
1456 let result = undefined;
\r
1458 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
1461 // No header / body separator found (e.g CRLFCRLF)
\r
1462 if (current + 3 >= this.index) {
\r
1465 result = Object.create(null);
\r
1466 let headers = this.buffer.toString('ascii', 0, current).split(CRLF);
\r
1467 headers.forEach((header) => {
\r
1468 let index = header.indexOf(':');
\r
1469 if (index === -1) {
\r
1470 throw new Error('Message header must separate key and value using :');
\r
1472 let key = header.substr(0, index);
\r
1473 let value = header.substr(index + 1).trim();
\r
1474 result[key] = value;
\r
1476 let nextStart = current + 4;
\r
1477 this.buffer = this.buffer.slice(nextStart);
\r
1478 this.index = this.index - nextStart;
\r
1481 tryReadContent(length) {
\r
1482 if (this.index < length) {
\r
1485 let result = this.buffer.toString(this.encoding, 0, length);
\r
1486 let nextStart = length;
\r
1487 this.buffer.copy(this.buffer, 0, nextStart);
\r
1488 this.index = this.index - nextStart;
\r
1491 get numberOfBytes() {
\r
1492 return this.index;
\r
1495 var MessageReader;
\r
1496 (function (MessageReader) {
\r
1497 function is(value) {
\r
1498 let candidate = value;
\r
1499 return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) &&
\r
1500 Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
\r
1502 MessageReader.is = is;
\r
1503 })(MessageReader = exports.MessageReader || (exports.MessageReader = {}));
\r
1504 class AbstractMessageReader {
\r
1506 this.errorEmitter = new events_1.Emitter();
\r
1507 this.closeEmitter = new events_1.Emitter();
\r
1508 this.partialMessageEmitter = new events_1.Emitter();
\r
1511 this.errorEmitter.dispose();
\r
1512 this.closeEmitter.dispose();
\r
1515 return this.errorEmitter.event;
\r
1517 fireError(error) {
\r
1518 this.errorEmitter.fire(this.asError(error));
\r
1521 return this.closeEmitter.event;
\r
1524 this.closeEmitter.fire(undefined);
\r
1526 get onPartialMessage() {
\r
1527 return this.partialMessageEmitter.event;
\r
1529 firePartialMessage(info) {
\r
1530 this.partialMessageEmitter.fire(info);
\r
1533 if (error instanceof Error) {
\r
1537 return new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
1541 exports.AbstractMessageReader = AbstractMessageReader;
\r
1542 class StreamMessageReader extends AbstractMessageReader {
\r
1543 constructor(readable, encoding = 'utf8') {
\r
1545 this.readable = readable;
\r
1546 this.buffer = new MessageBuffer(encoding);
\r
1547 this._partialMessageTimeout = 10000;
\r
1549 set partialMessageTimeout(timeout) {
\r
1550 this._partialMessageTimeout = timeout;
\r
1552 get partialMessageTimeout() {
\r
1553 return this._partialMessageTimeout;
\r
1555 listen(callback) {
\r
1556 this.nextMessageLength = -1;
\r
1557 this.messageToken = 0;
\r
1558 this.partialMessageTimer = undefined;
\r
1559 this.callback = callback;
\r
1560 this.readable.on('data', (data) => {
\r
1561 this.onData(data);
\r
1563 this.readable.on('error', (error) => this.fireError(error));
\r
1564 this.readable.on('close', () => this.fireClose());
\r
1567 this.buffer.append(data);
\r
1569 if (this.nextMessageLength === -1) {
\r
1570 let headers = this.buffer.tryReadHeaders();
\r
1574 let contentLength = headers['Content-Length'];
\r
1575 if (!contentLength) {
\r
1576 throw new Error('Header must provide a Content-Length property.');
\r
1578 let length = parseInt(contentLength);
\r
1579 if (isNaN(length)) {
\r
1580 throw new Error('Content-Length value must be a number.');
\r
1582 this.nextMessageLength = length;
\r
1583 // Take the encoding form the header. For compatibility
\r
1584 // treat both utf-8 and utf8 as node utf8
\r
1586 var msg = this.buffer.tryReadContent(this.nextMessageLength);
\r
1587 if (msg === null) {
\r
1588 /** We haven't received the full message yet. */
\r
1589 this.setPartialMessageTimer();
\r
1592 this.clearPartialMessageTimer();
\r
1593 this.nextMessageLength = -1;
\r
1594 this.messageToken++;
\r
1595 var json = JSON.parse(msg);
\r
1596 this.callback(json);
\r
1599 clearPartialMessageTimer() {
\r
1600 if (this.partialMessageTimer) {
\r
1601 clearTimeout(this.partialMessageTimer);
\r
1602 this.partialMessageTimer = undefined;
\r
1605 setPartialMessageTimer() {
\r
1606 this.clearPartialMessageTimer();
\r
1607 if (this._partialMessageTimeout <= 0) {
\r
1610 this.partialMessageTimer = setTimeout((token, timeout) => {
\r
1611 this.partialMessageTimer = undefined;
\r
1612 if (token === this.messageToken) {
\r
1613 this.firePartialMessage({ messageToken: token, waitingTime: timeout });
\r
1614 this.setPartialMessageTimer();
\r
1616 }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
\r
1619 exports.StreamMessageReader = StreamMessageReader;
\r
1620 class IPCMessageReader extends AbstractMessageReader {
\r
1621 constructor(process) {
\r
1623 this.process = process;
\r
1624 let eventEmitter = this.process;
\r
1625 eventEmitter.on('error', (error) => this.fireError(error));
\r
1626 eventEmitter.on('close', () => this.fireClose());
\r
1628 listen(callback) {
\r
1629 this.process.on('message', callback);
\r
1632 exports.IPCMessageReader = IPCMessageReader;
\r
1633 class SocketMessageReader extends StreamMessageReader {
\r
1634 constructor(socket, encoding = 'utf-8') {
\r
1635 super(socket, encoding);
\r
1638 exports.SocketMessageReader = SocketMessageReader;
\r
1643 /***/ (function(module, exports, __webpack_require__) {
1646 /* --------------------------------------------------------------------------------------------
\r
1647 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1648 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1649 * ------------------------------------------------------------------------------------------ */
\r
1651 Object.defineProperty(exports, "__esModule", { value: true });
\r
1653 (function (Disposable) {
\r
1654 function create(func) {
\r
1659 Disposable.create = create;
\r
1660 })(Disposable = exports.Disposable || (exports.Disposable = {}));
\r
1662 (function (Event) {
\r
1663 const _disposable = { dispose() { } };
\r
1664 Event.None = function () { return _disposable; };
\r
1665 })(Event = exports.Event || (exports.Event = {}));
\r
1666 class CallbackList {
\r
1667 add(callback, context = null, bucket) {
\r
1668 if (!this._callbacks) {
\r
1669 this._callbacks = [];
\r
1670 this._contexts = [];
\r
1672 this._callbacks.push(callback);
\r
1673 this._contexts.push(context);
\r
1674 if (Array.isArray(bucket)) {
\r
1675 bucket.push({ dispose: () => this.remove(callback, context) });
\r
1678 remove(callback, context = null) {
\r
1679 if (!this._callbacks) {
\r
1682 var foundCallbackWithDifferentContext = false;
\r
1683 for (var i = 0, len = this._callbacks.length; i < len; i++) {
\r
1684 if (this._callbacks[i] === callback) {
\r
1685 if (this._contexts[i] === context) {
\r
1686 // callback & context match => remove it
\r
1687 this._callbacks.splice(i, 1);
\r
1688 this._contexts.splice(i, 1);
\r
1692 foundCallbackWithDifferentContext = true;
\r
1696 if (foundCallbackWithDifferentContext) {
\r
1697 throw new Error('When adding a listener with a context, you should remove it with the same context');
\r
1701 if (!this._callbacks) {
\r
1704 var ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
\r
1705 for (var i = 0, len = callbacks.length; i < len; i++) {
\r
1707 ret.push(callbacks[i].apply(contexts[i], args));
\r
1716 return !this._callbacks || this._callbacks.length === 0;
\r
1719 this._callbacks = undefined;
\r
1720 this._contexts = undefined;
\r
1724 constructor(_options) {
\r
1725 this._options = _options;
\r
1728 * For the public to allow to subscribe
\r
1729 * to events from this Emitter
\r
1732 if (!this._event) {
\r
1733 this._event = (listener, thisArgs, disposables) => {
\r
1734 if (!this._callbacks) {
\r
1735 this._callbacks = new CallbackList();
\r
1737 if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
\r
1738 this._options.onFirstListenerAdd(this);
\r
1740 this._callbacks.add(listener, thisArgs);
\r
1744 this._callbacks.remove(listener, thisArgs);
\r
1745 result.dispose = Emitter._noop;
\r
1746 if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
\r
1747 this._options.onLastListenerRemove(this);
\r
1751 if (Array.isArray(disposables)) {
\r
1752 disposables.push(result);
\r
1757 return this._event;
\r
1760 * To be kept private to fire an event to
\r
1764 if (this._callbacks) {
\r
1765 this._callbacks.invoke.call(this._callbacks, event);
\r
1769 if (this._callbacks) {
\r
1770 this._callbacks.dispose();
\r
1771 this._callbacks = undefined;
\r
1775 Emitter._noop = function () { };
\r
1776 exports.Emitter = Emitter;
\r
1781 /***/ (function(module, exports, __webpack_require__) {
1784 /* --------------------------------------------------------------------------------------------
\r
1785 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1786 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1787 * ------------------------------------------------------------------------------------------ */
\r
1789 Object.defineProperty(exports, "__esModule", { value: true });
\r
1790 const events_1 = __webpack_require__(8);
\r
1791 const Is = __webpack_require__(5);
\r
1792 let ContentLength = 'Content-Length: ';
\r
1793 let CRLF = '\r\n';
\r
1794 var MessageWriter;
\r
1795 (function (MessageWriter) {
\r
1796 function is(value) {
\r
1797 let candidate = value;
\r
1798 return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) &&
\r
1799 Is.func(candidate.onError) && Is.func(candidate.write);
\r
1801 MessageWriter.is = is;
\r
1802 })(MessageWriter = exports.MessageWriter || (exports.MessageWriter = {}));
\r
1803 class AbstractMessageWriter {
\r
1805 this.errorEmitter = new events_1.Emitter();
\r
1806 this.closeEmitter = new events_1.Emitter();
\r
1809 this.errorEmitter.dispose();
\r
1810 this.closeEmitter.dispose();
\r
1813 return this.errorEmitter.event;
\r
1815 fireError(error, message, count) {
\r
1816 this.errorEmitter.fire([this.asError(error), message, count]);
\r
1819 return this.closeEmitter.event;
\r
1822 this.closeEmitter.fire(undefined);
\r
1825 if (error instanceof Error) {
\r
1829 return new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : 'unknown'}`);
\r
1833 exports.AbstractMessageWriter = AbstractMessageWriter;
\r
1834 class StreamMessageWriter extends AbstractMessageWriter {
\r
1835 constructor(writable, encoding = 'utf8') {
\r
1837 this.writable = writable;
\r
1838 this.encoding = encoding;
\r
1839 this.errorCount = 0;
\r
1840 this.writable.on('error', (error) => this.fireError(error));
\r
1841 this.writable.on('close', () => this.fireClose());
\r
1844 let json = JSON.stringify(msg);
\r
1845 let contentLength = Buffer.byteLength(json, this.encoding);
\r
1847 ContentLength, contentLength.toString(), CRLF,
\r
1851 // Header must be written in ASCII encoding
\r
1852 this.writable.write(headers.join(''), 'ascii');
\r
1853 // Now write the content. This can be written in any encoding
\r
1854 this.writable.write(json, this.encoding);
\r
1855 this.errorCount = 0;
\r
1858 this.errorCount++;
\r
1859 this.fireError(error, msg, this.errorCount);
\r
1863 exports.StreamMessageWriter = StreamMessageWriter;
\r
1864 class IPCMessageWriter extends AbstractMessageWriter {
\r
1865 constructor(process) {
\r
1867 this.process = process;
\r
1868 this.errorCount = 0;
\r
1870 this.sending = false;
\r
1871 let eventEmitter = this.process;
\r
1872 eventEmitter.on('error', (error) => this.fireError(error));
\r
1873 eventEmitter.on('close', () => this.fireClose);
\r
1876 if (!this.sending && this.queue.length === 0) {
\r
1877 // See https://github.com/nodejs/node/issues/7657
\r
1878 this.doWriteMessage(msg);
\r
1881 this.queue.push(msg);
\r
1884 doWriteMessage(msg) {
\r
1886 if (this.process.send) {
\r
1887 this.sending = true;
\r
1888 this.process.send(msg, undefined, undefined, (error) => {
\r
1889 this.sending = false;
\r
1891 this.errorCount++;
\r
1892 this.fireError(error, msg, this.errorCount);
\r
1895 this.errorCount = 0;
\r
1897 if (this.queue.length > 0) {
\r
1898 this.doWriteMessage(this.queue.shift());
\r
1904 this.errorCount++;
\r
1905 this.fireError(error, msg, this.errorCount);
\r
1909 exports.IPCMessageWriter = IPCMessageWriter;
\r
1910 class SocketMessageWriter extends AbstractMessageWriter {
\r
1911 constructor(socket, encoding = 'utf8') {
\r
1913 this.socket = socket;
\r
1915 this.sending = false;
\r
1916 this.encoding = encoding;
\r
1917 this.errorCount = 0;
\r
1918 this.socket.on('error', (error) => this.fireError(error));
\r
1919 this.socket.on('close', () => this.fireClose());
\r
1923 this.socket.destroy();
\r
1926 if (!this.sending && this.queue.length === 0) {
\r
1927 // See https://github.com/nodejs/node/issues/7657
\r
1928 this.doWriteMessage(msg);
\r
1931 this.queue.push(msg);
\r
1934 doWriteMessage(msg) {
\r
1935 let json = JSON.stringify(msg);
\r
1936 let contentLength = Buffer.byteLength(json, this.encoding);
\r
1938 ContentLength, contentLength.toString(), CRLF,
\r
1942 // Header must be written in ASCII encoding
\r
1943 this.sending = true;
\r
1944 this.socket.write(headers.join(''), 'ascii', (error) => {
\r
1946 this.handleError(error, msg);
\r
1949 // Now write the content. This can be written in any encoding
\r
1950 this.socket.write(json, this.encoding, (error) => {
\r
1951 this.sending = false;
\r
1953 this.handleError(error, msg);
\r
1956 this.errorCount = 0;
\r
1958 if (this.queue.length > 0) {
\r
1959 this.doWriteMessage(this.queue.shift());
\r
1964 this.handleError(error, msg);
\r
1969 this.handleError(error, msg);
\r
1972 handleError(error, msg) {
\r
1973 this.errorCount++;
\r
1974 this.fireError(error, msg, this.errorCount);
\r
1977 exports.SocketMessageWriter = SocketMessageWriter;
\r
1982 /***/ (function(module, exports, __webpack_require__) {
1985 /*---------------------------------------------------------------------------------------------
\r
1986 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
1987 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
1988 *--------------------------------------------------------------------------------------------*/
\r
1990 Object.defineProperty(exports, "__esModule", { value: true });
\r
1991 const events_1 = __webpack_require__(8);
\r
1992 const Is = __webpack_require__(5);
\r
1993 var CancellationToken;
\r
1994 (function (CancellationToken) {
\r
1995 CancellationToken.None = Object.freeze({
\r
1996 isCancellationRequested: false,
\r
1997 onCancellationRequested: events_1.Event.None
\r
1999 CancellationToken.Cancelled = Object.freeze({
\r
2000 isCancellationRequested: true,
\r
2001 onCancellationRequested: events_1.Event.None
\r
2003 function is(value) {
\r
2004 let candidate = value;
\r
2005 return candidate && (candidate === CancellationToken.None
\r
2006 || candidate === CancellationToken.Cancelled
\r
2007 || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
\r
2009 CancellationToken.is = is;
\r
2010 })(CancellationToken = exports.CancellationToken || (exports.CancellationToken = {}));
\r
2011 const shortcutEvent = Object.freeze(function (callback, context) {
\r
2012 let handle = setTimeout(callback.bind(context), 0);
\r
2013 return { dispose() { clearTimeout(handle); } };
\r
2015 class MutableToken {
\r
2017 this._isCancelled = false;
\r
2020 if (!this._isCancelled) {
\r
2021 this._isCancelled = true;
\r
2022 if (this._emitter) {
\r
2023 this._emitter.fire(undefined);
\r
2028 get isCancellationRequested() {
\r
2029 return this._isCancelled;
\r
2031 get onCancellationRequested() {
\r
2032 if (this._isCancelled) {
\r
2033 return shortcutEvent;
\r
2035 if (!this._emitter) {
\r
2036 this._emitter = new events_1.Emitter();
\r
2038 return this._emitter.event;
\r
2041 if (this._emitter) {
\r
2042 this._emitter.dispose();
\r
2043 this._emitter = undefined;
\r
2047 class CancellationTokenSource {
\r
2049 if (!this._token) {
\r
2050 // be lazy and create the token only when
\r
2051 // actually needed
\r
2052 this._token = new MutableToken();
\r
2054 return this._token;
\r
2057 if (!this._token) {
\r
2058 // save an object by returning the default
\r
2059 // cancelled token when cancellation happens
\r
2060 // before someone asks for the token
\r
2061 this._token = CancellationToken.Cancelled;
\r
2064 this._token.cancel();
\r
2068 if (!this._token) {
\r
2069 // ensure to initialize with an empty token if we had none
\r
2070 this._token = CancellationToken.None;
\r
2072 else if (this._token instanceof MutableToken) {
\r
2073 // actually dispose
\r
2074 this._token.dispose();
\r
2078 exports.CancellationTokenSource = CancellationTokenSource;
\r
2083 /***/ (function(module, exports, __webpack_require__) {
2087 /*---------------------------------------------------------------------------------------------
\r
2088 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2089 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2090 *--------------------------------------------------------------------------------------------*/
\r
2091 Object.defineProperty(exports, "__esModule", { value: true });
\r
2093 (function (Touch) {
\r
2097 })(Touch = exports.Touch || (exports.Touch = {}));
\r
2100 this._map = new Map();
\r
2101 this._head = undefined;
\r
2102 this._tail = undefined;
\r
2106 this._map.clear();
\r
2107 this._head = undefined;
\r
2108 this._tail = undefined;
\r
2112 return !this._head && !this._tail;
\r
2115 return this._size;
\r
2118 return this._map.has(key);
\r
2121 const item = this._map.get(key);
\r
2125 return item.value;
\r
2127 set(key, value, touch = Touch.None) {
\r
2128 let item = this._map.get(key);
\r
2130 item.value = value;
\r
2131 if (touch !== Touch.None) {
\r
2132 this.touch(item, touch);
\r
2136 item = { key, value, next: undefined, previous: undefined };
\r
2139 this.addItemLast(item);
\r
2142 this.addItemFirst(item);
\r
2145 this.addItemLast(item);
\r
2148 this.addItemLast(item);
\r
2151 this._map.set(key, item);
\r
2156 const item = this._map.get(key);
\r
2160 this._map.delete(key);
\r
2161 this.removeItem(item);
\r
2166 if (!this._head && !this._tail) {
\r
2169 if (!this._head || !this._tail) {
\r
2170 throw new Error('Invalid list');
\r
2172 const item = this._head;
\r
2173 this._map.delete(item.key);
\r
2174 this.removeItem(item);
\r
2176 return item.value;
\r
2178 forEach(callbackfn, thisArg) {
\r
2179 let current = this._head;
\r
2182 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2185 callbackfn(current.value, current.key, this);
\r
2187 current = current.next;
\r
2190 forEachReverse(callbackfn, thisArg) {
\r
2191 let current = this._tail;
\r
2194 callbackfn.bind(thisArg)(current.value, current.key, this);
\r
2197 callbackfn(current.value, current.key, this);
\r
2199 current = current.previous;
\r
2204 let current = this._head;
\r
2206 result.push(current.value);
\r
2207 current = current.next;
\r
2213 let current = this._head;
\r
2215 result.push(current.key);
\r
2216 current = current.next;
\r
2220 /* JSON RPC run on es5 which has no Symbol.iterator
\r
2221 public keys(): IterableIterator<K> {
\r
2222 let current = this._head;
\r
2223 let iterator: IterableIterator<K> = {
\r
2224 [Symbol.iterator]() {
\r
2227 next():IteratorResult<K> {
\r
2229 let result = { value: current.key, done: false };
\r
2230 current = current.next;
\r
2233 return { value: undefined, done: true };
\r
2240 public values(): IterableIterator<V> {
\r
2241 let current = this._head;
\r
2242 let iterator: IterableIterator<V> = {
\r
2243 [Symbol.iterator]() {
\r
2246 next():IteratorResult<V> {
\r
2248 let result = { value: current.value, done: false };
\r
2249 current = current.next;
\r
2252 return { value: undefined, done: true };
\r
2259 addItemFirst(item) {
\r
2260 // First time Insert
\r
2261 if (!this._head && !this._tail) {
\r
2262 this._tail = item;
\r
2264 else if (!this._head) {
\r
2265 throw new Error('Invalid list');
\r
2268 item.next = this._head;
\r
2269 this._head.previous = item;
\r
2271 this._head = item;
\r
2273 addItemLast(item) {
\r
2274 // First time Insert
\r
2275 if (!this._head && !this._tail) {
\r
2276 this._head = item;
\r
2278 else if (!this._tail) {
\r
2279 throw new Error('Invalid list');
\r
2282 item.previous = this._tail;
\r
2283 this._tail.next = item;
\r
2285 this._tail = item;
\r
2287 removeItem(item) {
\r
2288 if (item === this._head && item === this._tail) {
\r
2289 this._head = undefined;
\r
2290 this._tail = undefined;
\r
2292 else if (item === this._head) {
\r
2293 this._head = item.next;
\r
2295 else if (item === this._tail) {
\r
2296 this._tail = item.previous;
\r
2299 const next = item.next;
\r
2300 const previous = item.previous;
\r
2301 if (!next || !previous) {
\r
2302 throw new Error('Invalid list');
\r
2304 next.previous = previous;
\r
2305 previous.next = next;
\r
2308 touch(item, touch) {
\r
2309 if (!this._head || !this._tail) {
\r
2310 throw new Error('Invalid list');
\r
2312 if ((touch !== Touch.First && touch !== Touch.Last)) {
\r
2315 if (touch === Touch.First) {
\r
2316 if (item === this._head) {
\r
2319 const next = item.next;
\r
2320 const previous = item.previous;
\r
2321 // Unlink the item
\r
2322 if (item === this._tail) {
\r
2323 // previous must be defined since item was not head but is tail
\r
2324 // So there are more than on item in the map
\r
2325 previous.next = undefined;
\r
2326 this._tail = previous;
\r
2329 // Both next and previous are not undefined since item was neither head nor tail.
\r
2330 next.previous = previous;
\r
2331 previous.next = next;
\r
2333 // Insert the node at head
\r
2334 item.previous = undefined;
\r
2335 item.next = this._head;
\r
2336 this._head.previous = item;
\r
2337 this._head = item;
\r
2339 else if (touch === Touch.Last) {
\r
2340 if (item === this._tail) {
\r
2343 const next = item.next;
\r
2344 const previous = item.previous;
\r
2345 // Unlink the item.
\r
2346 if (item === this._head) {
\r
2347 // next must be defined since item was not tail but is head
\r
2348 // So there are more than on item in the map
\r
2349 next.previous = undefined;
\r
2350 this._head = next;
\r
2353 // Both next and previous are not undefined since item was neither head nor tail.
\r
2354 next.previous = previous;
\r
2355 previous.next = next;
\r
2357 item.next = undefined;
\r
2358 item.previous = this._tail;
\r
2359 this._tail.next = item;
\r
2360 this._tail = item;
\r
2364 exports.LinkedMap = LinkedMap;
\r
2369 /***/ (function(module, exports, __webpack_require__) {
2372 /* --------------------------------------------------------------------------------------------
\r
2373 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2374 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2375 * ------------------------------------------------------------------------------------------ */
\r
2377 Object.defineProperty(exports, "__esModule", { value: true });
\r
2378 const path_1 = __webpack_require__(1);
\r
2379 const os_1 = __webpack_require__(13);
\r
2380 const crypto_1 = __webpack_require__(14);
\r
2381 const net_1 = __webpack_require__(15);
\r
2382 const messageReader_1 = __webpack_require__(7);
\r
2383 const messageWriter_1 = __webpack_require__(9);
\r
2384 function generateRandomPipeName() {
\r
2385 const randomSuffix = crypto_1.randomBytes(21).toString('hex');
\r
2386 if (process.platform === 'win32') {
\r
2387 return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
\r
2390 // Mac/Unix: use socket file
\r
2391 return path_1.join(os_1.tmpdir(), `vscode-${randomSuffix}.sock`);
\r
2394 exports.generateRandomPipeName = generateRandomPipeName;
\r
2395 function createClientPipeTransport(pipeName, encoding = 'utf-8') {
\r
2396 let connectResolve;
\r
2397 let connected = new Promise((resolve, _reject) => {
\r
2398 connectResolve = resolve;
\r
2400 return new Promise((resolve, reject) => {
\r
2401 let server = net_1.createServer((socket) => {
\r
2404 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2405 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2408 server.on('error', reject);
\r
2409 server.listen(pipeName, () => {
\r
2410 server.removeListener('error', reject);
\r
2412 onConnected: () => { return connected; }
\r
2417 exports.createClientPipeTransport = createClientPipeTransport;
\r
2418 function createServerPipeTransport(pipeName, encoding = 'utf-8') {
\r
2419 const socket = net_1.createConnection(pipeName);
\r
2421 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2422 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2425 exports.createServerPipeTransport = createServerPipeTransport;
\r
2430 /***/ (function(module, exports) {
2432 module.exports = require("os");
2436 /***/ (function(module, exports) {
2438 module.exports = require("crypto");
2442 /***/ (function(module, exports) {
2444 module.exports = require("net");
2448 /***/ (function(module, exports, __webpack_require__) {
2451 /* --------------------------------------------------------------------------------------------
\r
2452 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2453 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2454 * ------------------------------------------------------------------------------------------ */
\r
2456 Object.defineProperty(exports, "__esModule", { value: true });
\r
2457 const net_1 = __webpack_require__(15);
\r
2458 const messageReader_1 = __webpack_require__(7);
\r
2459 const messageWriter_1 = __webpack_require__(9);
\r
2460 function createClientSocketTransport(port, encoding = 'utf-8') {
\r
2461 let connectResolve;
\r
2462 let connected = new Promise((resolve, _reject) => {
\r
2463 connectResolve = resolve;
\r
2465 return new Promise((resolve, reject) => {
\r
2466 let server = net_1.createServer((socket) => {
\r
2469 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2470 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2473 server.on('error', reject);
\r
2474 server.listen(port, '127.0.0.1', () => {
\r
2475 server.removeListener('error', reject);
\r
2477 onConnected: () => { return connected; }
\r
2482 exports.createClientSocketTransport = createClientSocketTransport;
\r
2483 function createServerSocketTransport(port, encoding = 'utf-8') {
\r
2484 const socket = net_1.createConnection(port, '127.0.0.1');
\r
2486 new messageReader_1.SocketMessageReader(socket, encoding),
\r
2487 new messageWriter_1.SocketMessageWriter(socket, encoding)
\r
2490 exports.createServerSocketTransport = createServerSocketTransport;
\r
2495 /***/ (function(module, __webpack_exports__, __webpack_require__) {
2498 __webpack_require__.r(__webpack_exports__);
2499 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
2500 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
2501 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
2502 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
2503 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
2504 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
2505 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
2506 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
2507 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
2508 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
2509 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
2510 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
2511 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
2512 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
2513 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
2514 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
2515 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
2516 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
2517 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
2518 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
2519 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
2520 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
2521 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
2522 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
2523 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
2524 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
2525 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
2526 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
2527 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
2528 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
2529 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
2530 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
2531 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
2532 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
2533 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
2534 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
2535 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
2536 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
2537 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
2538 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
2539 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
2540 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
2541 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
2542 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
2543 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
2544 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
2545 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
2546 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentSaveReason", function() { return TextDocumentSaveReason; });
2547 /* --------------------------------------------------------------------------------------------
\r
2548 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
2549 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
2550 * ------------------------------------------------------------------------------------------ */
\r
2553 * The Position namespace provides helper functions to work with
\r
2554 * [Position](#Position) literals.
\r
2557 (function (Position) {
\r
2559 * Creates a new Position literal from the given line and character.
\r
2560 * @param line The position's line.
\r
2561 * @param character The position's character.
\r
2563 function create(line, character) {
\r
2564 return { line: line, character: character };
\r
2566 Position.create = create;
\r
2568 * Checks whether the given liternal conforms to the [Position](#Position) interface.
\r
2570 function is(value) {
\r
2571 var candidate = value;
\r
2572 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
\r
2575 })(Position || (Position = {}));
\r
2577 * The Range namespace provides helper functions to work with
\r
2578 * [Range](#Range) literals.
\r
2581 (function (Range) {
\r
2582 function create(one, two, three, four) {
\r
2583 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
\r
2584 return { start: Position.create(one, two), end: Position.create(three, four) };
\r
2586 else if (Position.is(one) && Position.is(two)) {
\r
2587 return { start: one, end: two };
\r
2590 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
\r
2593 Range.create = create;
\r
2595 * Checks whether the given literal conforms to the [Range](#Range) interface.
\r
2597 function is(value) {
\r
2598 var candidate = value;
\r
2599 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
\r
2602 })(Range || (Range = {}));
\r
2604 * The Location namespace provides helper functions to work with
\r
2605 * [Location](#Location) literals.
\r
2608 (function (Location) {
\r
2610 * Creates a Location literal.
\r
2611 * @param uri The location's uri.
\r
2612 * @param range The location's range.
\r
2614 function create(uri, range) {
\r
2615 return { uri: uri, range: range };
\r
2617 Location.create = create;
\r
2619 * Checks whether the given literal conforms to the [Location](#Location) interface.
\r
2621 function is(value) {
\r
2622 var candidate = value;
\r
2623 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
\r
2626 })(Location || (Location = {}));
\r
2628 * The LocationLink namespace provides helper functions to work with
\r
2629 * [LocationLink](#LocationLink) literals.
\r
2632 (function (LocationLink) {
\r
2634 * Creates a LocationLink literal.
\r
2635 * @param targetUri The definition's uri.
\r
2636 * @param targetRange The full range of the definition.
\r
2637 * @param targetSelectionRange The span of the symbol definition at the target.
\r
2638 * @param originSelectionRange The span of the symbol being defined in the originating source file.
\r
2640 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
\r
2641 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
\r
2643 LocationLink.create = create;
\r
2645 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
\r
2647 function is(value) {
\r
2648 var candidate = value;
\r
2649 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
\r
2650 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
\r
2651 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
\r
2653 LocationLink.is = is;
\r
2654 })(LocationLink || (LocationLink = {}));
\r
2656 * The Color namespace provides helper functions to work with
\r
2657 * [Color](#Color) literals.
\r
2660 (function (Color) {
\r
2662 * Creates a new Color literal.
\r
2664 function create(red, green, blue, alpha) {
\r
2672 Color.create = create;
\r
2674 * Checks whether the given literal conforms to the [Color](#Color) interface.
\r
2676 function is(value) {
\r
2677 var candidate = value;
\r
2678 return Is.number(candidate.red)
\r
2679 && Is.number(candidate.green)
\r
2680 && Is.number(candidate.blue)
\r
2681 && Is.number(candidate.alpha);
\r
2684 })(Color || (Color = {}));
\r
2686 * The ColorInformation namespace provides helper functions to work with
\r
2687 * [ColorInformation](#ColorInformation) literals.
\r
2689 var ColorInformation;
\r
2690 (function (ColorInformation) {
\r
2692 * Creates a new ColorInformation literal.
\r
2694 function create(range, color) {
\r
2700 ColorInformation.create = create;
\r
2702 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2704 function is(value) {
\r
2705 var candidate = value;
\r
2706 return Range.is(candidate.range) && Color.is(candidate.color);
\r
2708 ColorInformation.is = is;
\r
2709 })(ColorInformation || (ColorInformation = {}));
\r
2711 * The Color namespace provides helper functions to work with
\r
2712 * [ColorPresentation](#ColorPresentation) literals.
\r
2714 var ColorPresentation;
\r
2715 (function (ColorPresentation) {
\r
2717 * Creates a new ColorInformation literal.
\r
2719 function create(label, textEdit, additionalTextEdits) {
\r
2722 textEdit: textEdit,
\r
2723 additionalTextEdits: additionalTextEdits,
\r
2726 ColorPresentation.create = create;
\r
2728 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
\r
2730 function is(value) {
\r
2731 var candidate = value;
\r
2732 return Is.string(candidate.label)
\r
2733 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
\r
2734 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
\r
2736 ColorPresentation.is = is;
\r
2737 })(ColorPresentation || (ColorPresentation = {}));
\r
2739 * Enum of known range kinds
\r
2741 var FoldingRangeKind;
\r
2742 (function (FoldingRangeKind) {
\r
2744 * Folding range for a comment
\r
2746 FoldingRangeKind["Comment"] = "comment";
\r
2748 * Folding range for a imports or includes
\r
2750 FoldingRangeKind["Imports"] = "imports";
\r
2752 * Folding range for a region (e.g. `#region`)
\r
2754 FoldingRangeKind["Region"] = "region";
\r
2755 })(FoldingRangeKind || (FoldingRangeKind = {}));
\r
2757 * The folding range namespace provides helper functions to work with
\r
2758 * [FoldingRange](#FoldingRange) literals.
\r
2761 (function (FoldingRange) {
\r
2763 * Creates a new FoldingRange literal.
\r
2765 function create(startLine, endLine, startCharacter, endCharacter, kind) {
\r
2767 startLine: startLine,
\r
2770 if (Is.defined(startCharacter)) {
\r
2771 result.startCharacter = startCharacter;
\r
2773 if (Is.defined(endCharacter)) {
\r
2774 result.endCharacter = endCharacter;
\r
2776 if (Is.defined(kind)) {
\r
2777 result.kind = kind;
\r
2781 FoldingRange.create = create;
\r
2783 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
\r
2785 function is(value) {
\r
2786 var candidate = value;
\r
2787 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
\r
2788 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
\r
2789 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
\r
2790 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
\r
2792 FoldingRange.is = is;
\r
2793 })(FoldingRange || (FoldingRange = {}));
\r
2795 * The DiagnosticRelatedInformation namespace provides helper functions to work with
\r
2796 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
\r
2798 var DiagnosticRelatedInformation;
\r
2799 (function (DiagnosticRelatedInformation) {
\r
2801 * Creates a new DiagnosticRelatedInformation literal.
\r
2803 function create(location, message) {
\r
2805 location: location,
\r
2809 DiagnosticRelatedInformation.create = create;
\r
2811 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
\r
2813 function is(value) {
\r
2814 var candidate = value;
\r
2815 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
\r
2817 DiagnosticRelatedInformation.is = is;
\r
2818 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
\r
2820 * The diagnostic's severity.
\r
2822 var DiagnosticSeverity;
\r
2823 (function (DiagnosticSeverity) {
\r
2825 * Reports an error.
\r
2827 DiagnosticSeverity.Error = 1;
\r
2829 * Reports a warning.
\r
2831 DiagnosticSeverity.Warning = 2;
\r
2833 * Reports an information.
\r
2835 DiagnosticSeverity.Information = 3;
\r
2839 DiagnosticSeverity.Hint = 4;
\r
2840 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
\r
2841 var DiagnosticTag;
\r
2842 (function (DiagnosticTag) {
\r
2844 * Unused or unnecessary code.
\r
2846 * Clients are allowed to render diagnostics with this tag faded out instead of having
\r
2847 * an error squiggle.
\r
2849 DiagnosticTag.Unnecessary = 1;
\r
2850 })(DiagnosticTag || (DiagnosticTag = {}));
\r
2852 * The Diagnostic namespace provides helper functions to work with
\r
2853 * [Diagnostic](#Diagnostic) literals.
\r
2856 (function (Diagnostic) {
\r
2858 * Creates a new Diagnostic literal.
\r
2860 function create(range, message, severity, code, source, relatedInformation) {
\r
2861 var result = { range: range, message: message };
\r
2862 if (Is.defined(severity)) {
\r
2863 result.severity = severity;
\r
2865 if (Is.defined(code)) {
\r
2866 result.code = code;
\r
2868 if (Is.defined(source)) {
\r
2869 result.source = source;
\r
2871 if (Is.defined(relatedInformation)) {
\r
2872 result.relatedInformation = relatedInformation;
\r
2876 Diagnostic.create = create;
\r
2878 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
\r
2880 function is(value) {
\r
2881 var candidate = value;
\r
2882 return Is.defined(candidate)
\r
2883 && Range.is(candidate.range)
\r
2884 && Is.string(candidate.message)
\r
2885 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
\r
2886 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
\r
2887 && (Is.string(candidate.source) || Is.undefined(candidate.source))
\r
2888 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
\r
2890 Diagnostic.is = is;
\r
2891 })(Diagnostic || (Diagnostic = {}));
\r
2893 * The Command namespace provides helper functions to work with
\r
2894 * [Command](#Command) literals.
\r
2897 (function (Command) {
\r
2899 * Creates a new Command literal.
\r
2901 function create(title, command) {
\r
2903 for (var _i = 2; _i < arguments.length; _i++) {
\r
2904 args[_i - 2] = arguments[_i];
\r
2906 var result = { title: title, command: command };
\r
2907 if (Is.defined(args) && args.length > 0) {
\r
2908 result.arguments = args;
\r
2912 Command.create = create;
\r
2914 * Checks whether the given literal conforms to the [Command](#Command) interface.
\r
2916 function is(value) {
\r
2917 var candidate = value;
\r
2918 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
\r
2921 })(Command || (Command = {}));
\r
2923 * The TextEdit namespace provides helper function to create replace,
\r
2924 * insert and delete edits more easily.
\r
2927 (function (TextEdit) {
\r
2929 * Creates a replace text edit.
\r
2930 * @param range The range of text to be replaced.
\r
2931 * @param newText The new text.
\r
2933 function replace(range, newText) {
\r
2934 return { range: range, newText: newText };
\r
2936 TextEdit.replace = replace;
\r
2938 * Creates a insert text edit.
\r
2939 * @param position The position to insert the text at.
\r
2940 * @param newText The text to be inserted.
\r
2942 function insert(position, newText) {
\r
2943 return { range: { start: position, end: position }, newText: newText };
\r
2945 TextEdit.insert = insert;
\r
2947 * Creates a delete text edit.
\r
2948 * @param range The range of text to be deleted.
\r
2950 function del(range) {
\r
2951 return { range: range, newText: '' };
\r
2953 TextEdit.del = del;
\r
2954 function is(value) {
\r
2955 var candidate = value;
\r
2956 return Is.objectLiteral(candidate)
\r
2957 && Is.string(candidate.newText)
\r
2958 && Range.is(candidate.range);
\r
2961 })(TextEdit || (TextEdit = {}));
\r
2963 * The TextDocumentEdit namespace provides helper function to create
\r
2964 * an edit that manipulates a text document.
\r
2966 var TextDocumentEdit;
\r
2967 (function (TextDocumentEdit) {
\r
2969 * Creates a new `TextDocumentEdit`
\r
2971 function create(textDocument, edits) {
\r
2972 return { textDocument: textDocument, edits: edits };
\r
2974 TextDocumentEdit.create = create;
\r
2975 function is(value) {
\r
2976 var candidate = value;
\r
2977 return Is.defined(candidate)
\r
2978 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
\r
2979 && Array.isArray(candidate.edits);
\r
2981 TextDocumentEdit.is = is;
\r
2982 })(TextDocumentEdit || (TextDocumentEdit = {}));
\r
2984 (function (CreateFile) {
\r
2985 function create(uri, options) {
\r
2990 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
2991 result.options = options;
\r
2995 CreateFile.create = create;
\r
2996 function is(value) {
\r
2997 var candidate = value;
\r
2998 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
\r
2999 (candidate.options === void 0 ||
\r
3000 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3002 CreateFile.is = is;
\r
3003 })(CreateFile || (CreateFile = {}));
\r
3005 (function (RenameFile) {
\r
3006 function create(oldUri, newUri, options) {
\r
3012 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
\r
3013 result.options = options;
\r
3017 RenameFile.create = create;
\r
3018 function is(value) {
\r
3019 var candidate = value;
\r
3020 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
\r
3021 (candidate.options === void 0 ||
\r
3022 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
\r
3024 RenameFile.is = is;
\r
3025 })(RenameFile || (RenameFile = {}));
\r
3027 (function (DeleteFile) {
\r
3028 function create(uri, options) {
\r
3033 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
\r
3034 result.options = options;
\r
3038 DeleteFile.create = create;
\r
3039 function is(value) {
\r
3040 var candidate = value;
\r
3041 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
\r
3042 (candidate.options === void 0 ||
\r
3043 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
\r
3045 DeleteFile.is = is;
\r
3046 })(DeleteFile || (DeleteFile = {}));
\r
3047 var WorkspaceEdit;
\r
3048 (function (WorkspaceEdit) {
\r
3049 function is(value) {
\r
3050 var candidate = value;
\r
3051 return candidate &&
\r
3052 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
\r
3053 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
\r
3054 if (Is.string(change.kind)) {
\r
3055 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
\r
3058 return TextDocumentEdit.is(change);
\r
3062 WorkspaceEdit.is = is;
\r
3063 })(WorkspaceEdit || (WorkspaceEdit = {}));
\r
3064 var TextEditChangeImpl = /** @class */ (function () {
\r
3065 function TextEditChangeImpl(edits) {
\r
3066 this.edits = edits;
\r
3068 TextEditChangeImpl.prototype.insert = function (position, newText) {
\r
3069 this.edits.push(TextEdit.insert(position, newText));
\r
3071 TextEditChangeImpl.prototype.replace = function (range, newText) {
\r
3072 this.edits.push(TextEdit.replace(range, newText));
\r
3074 TextEditChangeImpl.prototype.delete = function (range) {
\r
3075 this.edits.push(TextEdit.del(range));
\r
3077 TextEditChangeImpl.prototype.add = function (edit) {
\r
3078 this.edits.push(edit);
\r
3080 TextEditChangeImpl.prototype.all = function () {
\r
3081 return this.edits;
\r
3083 TextEditChangeImpl.prototype.clear = function () {
\r
3084 this.edits.splice(0, this.edits.length);
\r
3086 return TextEditChangeImpl;
\r
3089 * A workspace change helps constructing changes to a workspace.
\r
3091 var WorkspaceChange = /** @class */ (function () {
\r
3092 function WorkspaceChange(workspaceEdit) {
\r
3094 this._textEditChanges = Object.create(null);
\r
3095 if (workspaceEdit) {
\r
3096 this._workspaceEdit = workspaceEdit;
\r
3097 if (workspaceEdit.documentChanges) {
\r
3098 workspaceEdit.documentChanges.forEach(function (change) {
\r
3099 if (TextDocumentEdit.is(change)) {
\r
3100 var textEditChange = new TextEditChangeImpl(change.edits);
\r
3101 _this._textEditChanges[change.textDocument.uri] = textEditChange;
\r
3105 else if (workspaceEdit.changes) {
\r
3106 Object.keys(workspaceEdit.changes).forEach(function (key) {
\r
3107 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
\r
3108 _this._textEditChanges[key] = textEditChange;
\r
3113 Object.defineProperty(WorkspaceChange.prototype, "edit", {
\r
3115 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
\r
3116 * use to be returned from a workspace edit operation like rename.
\r
3118 get: function () {
\r
3119 return this._workspaceEdit;
\r
3122 configurable: true
\r
3124 WorkspaceChange.prototype.getTextEditChange = function (key) {
\r
3125 if (VersionedTextDocumentIdentifier.is(key)) {
\r
3126 if (!this._workspaceEdit) {
\r
3127 this._workspaceEdit = {
\r
3128 documentChanges: []
\r
3131 if (!this._workspaceEdit.documentChanges) {
\r
3132 throw new Error('Workspace edit is not configured for document changes.');
\r
3134 var textDocument = key;
\r
3135 var result = this._textEditChanges[textDocument.uri];
\r
3138 var textDocumentEdit = {
\r
3139 textDocument: textDocument,
\r
3142 this._workspaceEdit.documentChanges.push(textDocumentEdit);
\r
3143 result = new TextEditChangeImpl(edits);
\r
3144 this._textEditChanges[textDocument.uri] = result;
\r
3149 if (!this._workspaceEdit) {
\r
3150 this._workspaceEdit = {
\r
3151 changes: Object.create(null)
\r
3154 if (!this._workspaceEdit.changes) {
\r
3155 throw new Error('Workspace edit is not configured for normal text edit changes.');
\r
3157 var result = this._textEditChanges[key];
\r
3160 this._workspaceEdit.changes[key] = edits;
\r
3161 result = new TextEditChangeImpl(edits);
\r
3162 this._textEditChanges[key] = result;
\r
3167 WorkspaceChange.prototype.createFile = function (uri, options) {
\r
3168 this.checkDocumentChanges();
\r
3169 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
\r
3171 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
\r
3172 this.checkDocumentChanges();
\r
3173 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
\r
3175 WorkspaceChange.prototype.deleteFile = function (uri, options) {
\r
3176 this.checkDocumentChanges();
\r
3177 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
\r
3179 WorkspaceChange.prototype.checkDocumentChanges = function () {
\r
3180 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
\r
3181 throw new Error('Workspace edit is not configured for document changes.');
\r
3184 return WorkspaceChange;
\r
3188 * The TextDocumentIdentifier namespace provides helper functions to work with
\r
3189 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
\r
3191 var TextDocumentIdentifier;
\r
3192 (function (TextDocumentIdentifier) {
\r
3194 * Creates a new TextDocumentIdentifier literal.
\r
3195 * @param uri The document's uri.
\r
3197 function create(uri) {
\r
3198 return { uri: uri };
\r
3200 TextDocumentIdentifier.create = create;
\r
3202 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
\r
3204 function is(value) {
\r
3205 var candidate = value;
\r
3206 return Is.defined(candidate) && Is.string(candidate.uri);
\r
3208 TextDocumentIdentifier.is = is;
\r
3209 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
\r
3211 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
\r
3212 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
\r
3214 var VersionedTextDocumentIdentifier;
\r
3215 (function (VersionedTextDocumentIdentifier) {
\r
3217 * Creates a new VersionedTextDocumentIdentifier literal.
\r
3218 * @param uri The document's uri.
\r
3219 * @param uri The document's text.
\r
3221 function create(uri, version) {
\r
3222 return { uri: uri, version: version };
\r
3224 VersionedTextDocumentIdentifier.create = create;
\r
3226 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
\r
3228 function is(value) {
\r
3229 var candidate = value;
\r
3230 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
\r
3232 VersionedTextDocumentIdentifier.is = is;
\r
3233 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
\r
3235 * The TextDocumentItem namespace provides helper functions to work with
\r
3236 * [TextDocumentItem](#TextDocumentItem) literals.
\r
3238 var TextDocumentItem;
\r
3239 (function (TextDocumentItem) {
\r
3241 * Creates a new TextDocumentItem literal.
\r
3242 * @param uri The document's uri.
\r
3243 * @param languageId The document's language identifier.
\r
3244 * @param version The document's version number.
\r
3245 * @param text The document's text.
\r
3247 function create(uri, languageId, version, text) {
\r
3248 return { uri: uri, languageId: languageId, version: version, text: text };
\r
3250 TextDocumentItem.create = create;
\r
3252 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
\r
3254 function is(value) {
\r
3255 var candidate = value;
\r
3256 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
\r
3258 TextDocumentItem.is = is;
\r
3259 })(TextDocumentItem || (TextDocumentItem = {}));
\r
3261 * Describes the content type that a client supports in various
\r
3262 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
\r
3264 * Please note that `MarkupKinds` must not start with a `$`. This kinds
\r
3265 * are reserved for internal usage.
\r
3268 (function (MarkupKind) {
\r
3270 * Plain text is supported as a content format
\r
3272 MarkupKind.PlainText = 'plaintext';
\r
3274 * Markdown is supported as a content format
\r
3276 MarkupKind.Markdown = 'markdown';
\r
3277 })(MarkupKind || (MarkupKind = {}));
\r
3278 (function (MarkupKind) {
\r
3280 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
\r
3282 function is(value) {
\r
3283 var candidate = value;
\r
3284 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
\r
3286 MarkupKind.is = is;
\r
3287 })(MarkupKind || (MarkupKind = {}));
\r
3288 var MarkupContent;
\r
3289 (function (MarkupContent) {
\r
3291 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
\r
3293 function is(value) {
\r
3294 var candidate = value;
\r
3295 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
\r
3297 MarkupContent.is = is;
\r
3298 })(MarkupContent || (MarkupContent = {}));
\r
3300 * The kind of a completion entry.
\r
3302 var CompletionItemKind;
\r
3303 (function (CompletionItemKind) {
\r
3304 CompletionItemKind.Text = 1;
\r
3305 CompletionItemKind.Method = 2;
\r
3306 CompletionItemKind.Function = 3;
\r
3307 CompletionItemKind.Constructor = 4;
\r
3308 CompletionItemKind.Field = 5;
\r
3309 CompletionItemKind.Variable = 6;
\r
3310 CompletionItemKind.Class = 7;
\r
3311 CompletionItemKind.Interface = 8;
\r
3312 CompletionItemKind.Module = 9;
\r
3313 CompletionItemKind.Property = 10;
\r
3314 CompletionItemKind.Unit = 11;
\r
3315 CompletionItemKind.Value = 12;
\r
3316 CompletionItemKind.Enum = 13;
\r
3317 CompletionItemKind.Keyword = 14;
\r
3318 CompletionItemKind.Snippet = 15;
\r
3319 CompletionItemKind.Color = 16;
\r
3320 CompletionItemKind.File = 17;
\r
3321 CompletionItemKind.Reference = 18;
\r
3322 CompletionItemKind.Folder = 19;
\r
3323 CompletionItemKind.EnumMember = 20;
\r
3324 CompletionItemKind.Constant = 21;
\r
3325 CompletionItemKind.Struct = 22;
\r
3326 CompletionItemKind.Event = 23;
\r
3327 CompletionItemKind.Operator = 24;
\r
3328 CompletionItemKind.TypeParameter = 25;
\r
3329 })(CompletionItemKind || (CompletionItemKind = {}));
\r
3331 * Defines whether the insert text in a completion item should be interpreted as
\r
3332 * plain text or a snippet.
\r
3334 var InsertTextFormat;
\r
3335 (function (InsertTextFormat) {
\r
3337 * The primary text to be inserted is treated as a plain string.
\r
3339 InsertTextFormat.PlainText = 1;
\r
3341 * The primary text to be inserted is treated as a snippet.
\r
3343 * A snippet can define tab stops and placeholders with `$1`, `$2`
\r
3344 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
\r
3345 * the end of the snippet. Placeholders with equal identifiers are linked,
\r
3346 * that is typing in one will update others too.
\r
3348 * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
\r
3350 InsertTextFormat.Snippet = 2;
\r
3351 })(InsertTextFormat || (InsertTextFormat = {}));
\r
3353 * The CompletionItem namespace provides functions to deal with
\r
3354 * completion items.
\r
3356 var CompletionItem;
\r
3357 (function (CompletionItem) {
\r
3359 * Create a completion item and seed it with a label.
\r
3360 * @param label The completion item's label
\r
3362 function create(label) {
\r
3363 return { label: label };
\r
3365 CompletionItem.create = create;
\r
3366 })(CompletionItem || (CompletionItem = {}));
\r
3368 * The CompletionList namespace provides functions to deal with
\r
3369 * completion lists.
\r
3371 var CompletionList;
\r
3372 (function (CompletionList) {
\r
3374 * Creates a new completion list.
\r
3376 * @param items The completion items.
\r
3377 * @param isIncomplete The list is not complete.
\r
3379 function create(items, isIncomplete) {
\r
3380 return { items: items ? items : [], isIncomplete: !!isIncomplete };
\r
3382 CompletionList.create = create;
\r
3383 })(CompletionList || (CompletionList = {}));
\r
3385 (function (MarkedString) {
\r
3387 * Creates a marked string from plain text.
\r
3389 * @param plainText The plain text.
\r
3391 function fromPlainText(plainText) {
\r
3392 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
\r
3394 MarkedString.fromPlainText = fromPlainText;
\r
3396 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
\r
3398 function is(value) {
\r
3399 var candidate = value;
\r
3400 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
\r
3402 MarkedString.is = is;
\r
3403 })(MarkedString || (MarkedString = {}));
\r
3405 (function (Hover) {
\r
3407 * Checks whether the given value conforms to the [Hover](#Hover) interface.
\r
3409 function is(value) {
\r
3410 var candidate = value;
\r
3411 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
\r
3412 MarkedString.is(candidate.contents) ||
\r
3413 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
\r
3416 })(Hover || (Hover = {}));
\r
3418 * The ParameterInformation namespace provides helper functions to work with
\r
3419 * [ParameterInformation](#ParameterInformation) literals.
\r
3421 var ParameterInformation;
\r
3422 (function (ParameterInformation) {
\r
3424 * Creates a new parameter information literal.
\r
3426 * @param label A label string.
\r
3427 * @param documentation A doc string.
\r
3429 function create(label, documentation) {
\r
3430 return documentation ? { label: label, documentation: documentation } : { label: label };
\r
3432 ParameterInformation.create = create;
\r
3434 })(ParameterInformation || (ParameterInformation = {}));
\r
3436 * The SignatureInformation namespace provides helper functions to work with
\r
3437 * [SignatureInformation](#SignatureInformation) literals.
\r
3439 var SignatureInformation;
\r
3440 (function (SignatureInformation) {
\r
3441 function create(label, documentation) {
\r
3442 var parameters = [];
\r
3443 for (var _i = 2; _i < arguments.length; _i++) {
\r
3444 parameters[_i - 2] = arguments[_i];
\r
3446 var result = { label: label };
\r
3447 if (Is.defined(documentation)) {
\r
3448 result.documentation = documentation;
\r
3450 if (Is.defined(parameters)) {
\r
3451 result.parameters = parameters;
\r
3454 result.parameters = [];
\r
3458 SignatureInformation.create = create;
\r
3459 })(SignatureInformation || (SignatureInformation = {}));
\r
3461 * A document highlight kind.
\r
3463 var DocumentHighlightKind;
\r
3464 (function (DocumentHighlightKind) {
\r
3466 * A textual occurrence.
\r
3468 DocumentHighlightKind.Text = 1;
\r
3470 * Read-access of a symbol, like reading a variable.
\r
3472 DocumentHighlightKind.Read = 2;
\r
3474 * Write-access of a symbol, like writing to a variable.
\r
3476 DocumentHighlightKind.Write = 3;
\r
3477 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
\r
3479 * DocumentHighlight namespace to provide helper functions to work with
\r
3480 * [DocumentHighlight](#DocumentHighlight) literals.
\r
3482 var DocumentHighlight;
\r
3483 (function (DocumentHighlight) {
\r
3485 * Create a DocumentHighlight object.
\r
3486 * @param range The range the highlight applies to.
\r
3488 function create(range, kind) {
\r
3489 var result = { range: range };
\r
3490 if (Is.number(kind)) {
\r
3491 result.kind = kind;
\r
3495 DocumentHighlight.create = create;
\r
3496 })(DocumentHighlight || (DocumentHighlight = {}));
\r
3501 (function (SymbolKind) {
\r
3502 SymbolKind.File = 1;
\r
3503 SymbolKind.Module = 2;
\r
3504 SymbolKind.Namespace = 3;
\r
3505 SymbolKind.Package = 4;
\r
3506 SymbolKind.Class = 5;
\r
3507 SymbolKind.Method = 6;
\r
3508 SymbolKind.Property = 7;
\r
3509 SymbolKind.Field = 8;
\r
3510 SymbolKind.Constructor = 9;
\r
3511 SymbolKind.Enum = 10;
\r
3512 SymbolKind.Interface = 11;
\r
3513 SymbolKind.Function = 12;
\r
3514 SymbolKind.Variable = 13;
\r
3515 SymbolKind.Constant = 14;
\r
3516 SymbolKind.String = 15;
\r
3517 SymbolKind.Number = 16;
\r
3518 SymbolKind.Boolean = 17;
\r
3519 SymbolKind.Array = 18;
\r
3520 SymbolKind.Object = 19;
\r
3521 SymbolKind.Key = 20;
\r
3522 SymbolKind.Null = 21;
\r
3523 SymbolKind.EnumMember = 22;
\r
3524 SymbolKind.Struct = 23;
\r
3525 SymbolKind.Event = 24;
\r
3526 SymbolKind.Operator = 25;
\r
3527 SymbolKind.TypeParameter = 26;
\r
3528 })(SymbolKind || (SymbolKind = {}));
\r
3529 var SymbolInformation;
\r
3530 (function (SymbolInformation) {
\r
3532 * Creates a new symbol information literal.
\r
3534 * @param name The name of the symbol.
\r
3535 * @param kind The kind of the symbol.
\r
3536 * @param range The range of the location of the symbol.
\r
3537 * @param uri The resource of the location of symbol, defaults to the current document.
\r
3538 * @param containerName The name of the symbol containing the symbol.
\r
3540 function create(name, kind, range, uri, containerName) {
\r
3544 location: { uri: uri, range: range }
\r
3546 if (containerName) {
\r
3547 result.containerName = containerName;
\r
3551 SymbolInformation.create = create;
\r
3552 })(SymbolInformation || (SymbolInformation = {}));
\r
3554 * Represents programming constructs like variables, classes, interfaces etc.
\r
3555 * that appear in a document. Document symbols can be hierarchical and they
\r
3556 * have two ranges: one that encloses its definition and one that points to
\r
3557 * its most interesting range, e.g. the range of an identifier.
\r
3559 var DocumentSymbol = /** @class */ (function () {
\r
3560 function DocumentSymbol() {
\r
3562 return DocumentSymbol;
\r
3565 (function (DocumentSymbol) {
\r
3567 * Creates a new symbol information literal.
\r
3569 * @param name The name of the symbol.
\r
3570 * @param detail The detail of the symbol.
\r
3571 * @param kind The kind of the symbol.
\r
3572 * @param range The range of the symbol.
\r
3573 * @param selectionRange The selectionRange of the symbol.
\r
3574 * @param children Children of the symbol.
\r
3576 function create(name, detail, kind, range, selectionRange, children) {
\r
3582 selectionRange: selectionRange
\r
3584 if (children !== void 0) {
\r
3585 result.children = children;
\r
3589 DocumentSymbol.create = create;
\r
3591 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
\r
3593 function is(value) {
\r
3594 var candidate = value;
\r
3595 return candidate &&
\r
3596 Is.string(candidate.name) && Is.number(candidate.kind) &&
\r
3597 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
\r
3598 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
\r
3599 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
\r
3600 (candidate.children === void 0 || Array.isArray(candidate.children));
\r
3602 DocumentSymbol.is = is;
\r
3603 })(DocumentSymbol || (DocumentSymbol = {}));
\r
3605 * A set of predefined code action kinds
\r
3607 var CodeActionKind;
\r
3608 (function (CodeActionKind) {
\r
3610 * Base kind for quickfix actions: 'quickfix'
\r
3612 CodeActionKind.QuickFix = 'quickfix';
\r
3614 * Base kind for refactoring actions: 'refactor'
\r
3616 CodeActionKind.Refactor = 'refactor';
\r
3618 * Base kind for refactoring extraction actions: 'refactor.extract'
\r
3620 * Example extract actions:
\r
3622 * - Extract method
\r
3623 * - Extract function
\r
3624 * - Extract variable
\r
3625 * - Extract interface from class
\r
3628 CodeActionKind.RefactorExtract = 'refactor.extract';
\r
3630 * Base kind for refactoring inline actions: 'refactor.inline'
\r
3632 * Example inline actions:
\r
3634 * - Inline function
\r
3635 * - Inline variable
\r
3636 * - Inline constant
\r
3639 CodeActionKind.RefactorInline = 'refactor.inline';
\r
3641 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
\r
3643 * Example rewrite actions:
\r
3645 * - Convert JavaScript function to class
\r
3646 * - Add or remove parameter
\r
3647 * - Encapsulate field
\r
3648 * - Make method static
\r
3649 * - Move method to base class
\r
3652 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
\r
3654 * Base kind for source actions: `source`
\r
3656 * Source code actions apply to the entire file.
\r
3658 CodeActionKind.Source = 'source';
\r
3660 * Base kind for an organize imports source action: `source.organizeImports`
\r
3662 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
\r
3663 })(CodeActionKind || (CodeActionKind = {}));
\r
3665 * The CodeActionContext namespace provides helper functions to work with
\r
3666 * [CodeActionContext](#CodeActionContext) literals.
\r
3668 var CodeActionContext;
\r
3669 (function (CodeActionContext) {
\r
3671 * Creates a new CodeActionContext literal.
\r
3673 function create(diagnostics, only) {
\r
3674 var result = { diagnostics: diagnostics };
\r
3675 if (only !== void 0 && only !== null) {
\r
3676 result.only = only;
\r
3680 CodeActionContext.create = create;
\r
3682 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
\r
3684 function is(value) {
\r
3685 var candidate = value;
\r
3686 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
\r
3688 CodeActionContext.is = is;
\r
3689 })(CodeActionContext || (CodeActionContext = {}));
\r
3691 (function (CodeAction) {
\r
3692 function create(title, commandOrEdit, kind) {
\r
3693 var result = { title: title };
\r
3694 if (Command.is(commandOrEdit)) {
\r
3695 result.command = commandOrEdit;
\r
3698 result.edit = commandOrEdit;
\r
3700 if (kind !== void null) {
\r
3701 result.kind = kind;
\r
3705 CodeAction.create = create;
\r
3706 function is(value) {
\r
3707 var candidate = value;
\r
3708 return candidate && Is.string(candidate.title) &&
\r
3709 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
\r
3710 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
\r
3711 (candidate.edit !== void 0 || candidate.command !== void 0) &&
\r
3712 (candidate.command === void 0 || Command.is(candidate.command)) &&
\r
3713 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
\r
3715 CodeAction.is = is;
\r
3716 })(CodeAction || (CodeAction = {}));
\r
3718 * The CodeLens namespace provides helper functions to work with
\r
3719 * [CodeLens](#CodeLens) literals.
\r
3722 (function (CodeLens) {
\r
3724 * Creates a new CodeLens literal.
\r
3726 function create(range, data) {
\r
3727 var result = { range: range };
\r
3728 if (Is.defined(data))
\r
3729 result.data = data;
\r
3732 CodeLens.create = create;
\r
3734 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
\r
3736 function is(value) {
\r
3737 var candidate = value;
\r
3738 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
\r
3741 })(CodeLens || (CodeLens = {}));
\r
3743 * The FormattingOptions namespace provides helper functions to work with
\r
3744 * [FormattingOptions](#FormattingOptions) literals.
\r
3746 var FormattingOptions;
\r
3747 (function (FormattingOptions) {
\r
3749 * Creates a new FormattingOptions literal.
\r
3751 function create(tabSize, insertSpaces) {
\r
3752 return { tabSize: tabSize, insertSpaces: insertSpaces };
\r
3754 FormattingOptions.create = create;
\r
3756 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
\r
3758 function is(value) {
\r
3759 var candidate = value;
\r
3760 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
\r
3762 FormattingOptions.is = is;
\r
3763 })(FormattingOptions || (FormattingOptions = {}));
\r
3765 * A document link is a range in a text document that links to an internal or external resource, like another
\r
3766 * text document or a web site.
\r
3768 var DocumentLink = /** @class */ (function () {
\r
3769 function DocumentLink() {
\r
3771 return DocumentLink;
\r
3775 * The DocumentLink namespace provides helper functions to work with
\r
3776 * [DocumentLink](#DocumentLink) literals.
\r
3778 (function (DocumentLink) {
\r
3780 * Creates a new DocumentLink literal.
\r
3782 function create(range, target, data) {
\r
3783 return { range: range, target: target, data: data };
\r
3785 DocumentLink.create = create;
\r
3787 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
\r
3789 function is(value) {
\r
3790 var candidate = value;
\r
3791 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
\r
3793 DocumentLink.is = is;
\r
3794 })(DocumentLink || (DocumentLink = {}));
\r
3795 var EOL = ['\n', '\r\n', '\r'];
\r
3797 (function (TextDocument) {
\r
3799 * Creates a new ITextDocument literal from the given uri and content.
\r
3800 * @param uri The document's uri.
\r
3801 * @param languageId The document's language Id.
\r
3802 * @param content The document's content.
\r
3804 function create(uri, languageId, version, content) {
\r
3805 return new FullTextDocument(uri, languageId, version, content);
\r
3807 TextDocument.create = create;
\r
3809 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
\r
3811 function is(value) {
\r
3812 var candidate = value;
\r
3813 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
\r
3814 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
\r
3816 TextDocument.is = is;
\r
3817 function applyEdits(document, edits) {
\r
3818 var text = document.getText();
\r
3819 var sortedEdits = mergeSort(edits, function (a, b) {
\r
3820 var diff = a.range.start.line - b.range.start.line;
\r
3822 return a.range.start.character - b.range.start.character;
\r
3826 var lastModifiedOffset = text.length;
\r
3827 for (var i = sortedEdits.length - 1; i >= 0; i--) {
\r
3828 var e = sortedEdits[i];
\r
3829 var startOffset = document.offsetAt(e.range.start);
\r
3830 var endOffset = document.offsetAt(e.range.end);
\r
3831 if (endOffset <= lastModifiedOffset) {
\r
3832 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
\r
3835 throw new Error('Overlapping edit');
\r
3837 lastModifiedOffset = startOffset;
\r
3841 TextDocument.applyEdits = applyEdits;
\r
3842 function mergeSort(data, compare) {
\r
3843 if (data.length <= 1) {
\r
3847 var p = (data.length / 2) | 0;
\r
3848 var left = data.slice(0, p);
\r
3849 var right = data.slice(p);
\r
3850 mergeSort(left, compare);
\r
3851 mergeSort(right, compare);
\r
3855 while (leftIdx < left.length && rightIdx < right.length) {
\r
3856 var ret = compare(left[leftIdx], right[rightIdx]);
\r
3858 // smaller_equal -> take left to preserve order
\r
3859 data[i++] = left[leftIdx++];
\r
3862 // greater -> take right
\r
3863 data[i++] = right[rightIdx++];
\r
3866 while (leftIdx < left.length) {
\r
3867 data[i++] = left[leftIdx++];
\r
3869 while (rightIdx < right.length) {
\r
3870 data[i++] = right[rightIdx++];
\r
3874 })(TextDocument || (TextDocument = {}));
\r
3876 * Represents reasons why a text document is saved.
\r
3878 var TextDocumentSaveReason;
\r
3879 (function (TextDocumentSaveReason) {
\r
3881 * Manually triggered, e.g. by the user pressing save, by starting debugging,
\r
3882 * or by an API call.
\r
3884 TextDocumentSaveReason.Manual = 1;
\r
3886 * Automatic after a delay.
\r
3888 TextDocumentSaveReason.AfterDelay = 2;
\r
3890 * When the editor lost focus.
\r
3892 TextDocumentSaveReason.FocusOut = 3;
\r
3893 })(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
\r
3894 var FullTextDocument = /** @class */ (function () {
\r
3895 function FullTextDocument(uri, languageId, version, content) {
\r
3897 this._languageId = languageId;
\r
3898 this._version = version;
\r
3899 this._content = content;
\r
3900 this._lineOffsets = null;
\r
3902 Object.defineProperty(FullTextDocument.prototype, "uri", {
\r
3903 get: function () {
\r
3907 configurable: true
\r
3909 Object.defineProperty(FullTextDocument.prototype, "languageId", {
\r
3910 get: function () {
\r
3911 return this._languageId;
\r
3914 configurable: true
\r
3916 Object.defineProperty(FullTextDocument.prototype, "version", {
\r
3917 get: function () {
\r
3918 return this._version;
\r
3921 configurable: true
\r
3923 FullTextDocument.prototype.getText = function (range) {
\r
3925 var start = this.offsetAt(range.start);
\r
3926 var end = this.offsetAt(range.end);
\r
3927 return this._content.substring(start, end);
\r
3929 return this._content;
\r
3931 FullTextDocument.prototype.update = function (event, version) {
\r
3932 this._content = event.text;
\r
3933 this._version = version;
\r
3934 this._lineOffsets = null;
\r
3936 FullTextDocument.prototype.getLineOffsets = function () {
\r
3937 if (this._lineOffsets === null) {
\r
3938 var lineOffsets = [];
\r
3939 var text = this._content;
\r
3940 var isLineStart = true;
\r
3941 for (var i = 0; i < text.length; i++) {
\r
3942 if (isLineStart) {
\r
3943 lineOffsets.push(i);
\r
3944 isLineStart = false;
\r
3946 var ch = text.charAt(i);
\r
3947 isLineStart = (ch === '\r' || ch === '\n');
\r
3948 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
\r
3952 if (isLineStart && text.length > 0) {
\r
3953 lineOffsets.push(text.length);
\r
3955 this._lineOffsets = lineOffsets;
\r
3957 return this._lineOffsets;
\r
3959 FullTextDocument.prototype.positionAt = function (offset) {
\r
3960 offset = Math.max(Math.min(offset, this._content.length), 0);
\r
3961 var lineOffsets = this.getLineOffsets();
\r
3962 var low = 0, high = lineOffsets.length;
\r
3964 return Position.create(0, offset);
\r
3966 while (low < high) {
\r
3967 var mid = Math.floor((low + high) / 2);
\r
3968 if (lineOffsets[mid] > offset) {
\r
3975 // low is the least x for which the line offset is larger than the current offset
\r
3976 // or array.length if no line offset is larger than the current offset
\r
3977 var line = low - 1;
\r
3978 return Position.create(line, offset - lineOffsets[line]);
\r
3980 FullTextDocument.prototype.offsetAt = function (position) {
\r
3981 var lineOffsets = this.getLineOffsets();
\r
3982 if (position.line >= lineOffsets.length) {
\r
3983 return this._content.length;
\r
3985 else if (position.line < 0) {
\r
3988 var lineOffset = lineOffsets[position.line];
\r
3989 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
\r
3990 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
\r
3992 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
\r
3993 get: function () {
\r
3994 return this.getLineOffsets().length;
\r
3997 configurable: true
\r
3999 return FullTextDocument;
\r
4003 var toString = Object.prototype.toString;
\r
4004 function defined(value) {
\r
4005 return typeof value !== 'undefined';
\r
4007 Is.defined = defined;
\r
4008 function undefined(value) {
\r
4009 return typeof value === 'undefined';
\r
4011 Is.undefined = undefined;
\r
4012 function boolean(value) {
\r
4013 return value === true || value === false;
\r
4015 Is.boolean = boolean;
\r
4016 function string(value) {
\r
4017 return toString.call(value) === '[object String]';
\r
4019 Is.string = string;
\r
4020 function number(value) {
\r
4021 return toString.call(value) === '[object Number]';
\r
4023 Is.number = number;
\r
4024 function func(value) {
\r
4025 return toString.call(value) === '[object Function]';
\r
4028 function objectLiteral(value) {
\r
4029 // Strictly speaking class instances pass this check as well. Since the LSP
\r
4030 // doesn't use classes we ignore this for now. If we do we need to add something
\r
4031 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
\r
4032 return value !== null && typeof value === 'object';
\r
4034 Is.objectLiteral = objectLiteral;
\r
4035 function typedArray(value, check) {
\r
4036 return Array.isArray(value) && value.every(check);
\r
4038 Is.typedArray = typedArray;
\r
4039 })(Is || (Is = {}));
\r
4044 /***/ (function(module, exports, __webpack_require__) {
4047 /* --------------------------------------------------------------------------------------------
\r
4048 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4049 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4050 * ------------------------------------------------------------------------------------------ */
\r
4052 Object.defineProperty(exports, "__esModule", { value: true });
\r
4053 const Is = __webpack_require__(19);
\r
4054 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4055 const protocol_implementation_1 = __webpack_require__(20);
\r
4056 exports.ImplementationRequest = protocol_implementation_1.ImplementationRequest;
\r
4057 const protocol_typeDefinition_1 = __webpack_require__(21);
\r
4058 exports.TypeDefinitionRequest = protocol_typeDefinition_1.TypeDefinitionRequest;
\r
4059 const protocol_workspaceFolders_1 = __webpack_require__(22);
\r
4060 exports.WorkspaceFoldersRequest = protocol_workspaceFolders_1.WorkspaceFoldersRequest;
\r
4061 exports.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolders_1.DidChangeWorkspaceFoldersNotification;
\r
4062 const protocol_configuration_1 = __webpack_require__(23);
\r
4063 exports.ConfigurationRequest = protocol_configuration_1.ConfigurationRequest;
\r
4064 const protocol_colorProvider_1 = __webpack_require__(24);
\r
4065 exports.DocumentColorRequest = protocol_colorProvider_1.DocumentColorRequest;
\r
4066 exports.ColorPresentationRequest = protocol_colorProvider_1.ColorPresentationRequest;
\r
4067 const protocol_foldingRange_1 = __webpack_require__(25);
\r
4068 exports.FoldingRangeRequest = protocol_foldingRange_1.FoldingRangeRequest;
\r
4069 const protocol_declaration_1 = __webpack_require__(26);
\r
4070 exports.DeclarationRequest = protocol_declaration_1.DeclarationRequest;
\r
4071 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4072 let __noDynamicImport;
\r
4073 var DocumentFilter;
\r
4074 (function (DocumentFilter) {
\r
4075 function is(value) {
\r
4076 let candidate = value;
\r
4077 return Is.string(candidate.language) || Is.string(candidate.scheme) || Is.string(candidate.pattern);
\r
4079 DocumentFilter.is = is;
\r
4080 })(DocumentFilter = exports.DocumentFilter || (exports.DocumentFilter = {}));
\r
4082 * The `client/registerCapability` request is sent from the server to the client to register a new capability
\r
4083 * handler on the client side.
\r
4085 var RegistrationRequest;
\r
4086 (function (RegistrationRequest) {
\r
4087 RegistrationRequest.type = new vscode_jsonrpc_1.RequestType('client/registerCapability');
\r
4088 })(RegistrationRequest = exports.RegistrationRequest || (exports.RegistrationRequest = {}));
\r
4090 * The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability
\r
4091 * handler on the client side.
\r
4093 var UnregistrationRequest;
\r
4094 (function (UnregistrationRequest) {
\r
4095 UnregistrationRequest.type = new vscode_jsonrpc_1.RequestType('client/unregisterCapability');
\r
4096 })(UnregistrationRequest = exports.UnregistrationRequest || (exports.UnregistrationRequest = {}));
\r
4097 var ResourceOperationKind;
\r
4098 (function (ResourceOperationKind) {
\r
4100 * Supports creating new files and folders.
\r
4102 ResourceOperationKind.Create = 'create';
\r
4104 * Supports renaming existing files and folders.
\r
4106 ResourceOperationKind.Rename = 'rename';
\r
4108 * Supports deleting existing files and folders.
\r
4110 ResourceOperationKind.Delete = 'delete';
\r
4111 })(ResourceOperationKind = exports.ResourceOperationKind || (exports.ResourceOperationKind = {}));
\r
4112 var FailureHandlingKind;
\r
4113 (function (FailureHandlingKind) {
\r
4115 * Applying the workspace change is simply aborted if one of the changes provided
\r
4116 * fails. All operations executed before the failing operation stay executed.
\r
4118 FailureHandlingKind.Abort = 'abort';
\r
4120 * All operations are executed transactional. That means they either all
\r
4121 * succeed or no changes at all are applied to the workspace.
\r
4123 FailureHandlingKind.Transactional = 'transactional';
\r
4125 * If the workspace edit contains only textual file changes they are executed transactional.
\r
4126 * If resource changes (create, rename or delete file) are part of the change the failure
\r
4127 * handling startegy is abort.
\r
4129 FailureHandlingKind.TextOnlyTransactional = 'textOnlyTransactional';
\r
4131 * The client tries to undo the operations already executed. But there is no
\r
4132 * guaruntee that this is succeeding.
\r
4134 FailureHandlingKind.Undo = 'undo';
\r
4135 })(FailureHandlingKind = exports.FailureHandlingKind || (exports.FailureHandlingKind = {}));
\r
4137 * Defines how the host (editor) should sync
\r
4138 * document changes to the language server.
\r
4140 var TextDocumentSyncKind;
\r
4141 (function (TextDocumentSyncKind) {
\r
4143 * Documents should not be synced at all.
\r
4145 TextDocumentSyncKind.None = 0;
\r
4147 * Documents are synced by always sending the full content
\r
4148 * of the document.
\r
4150 TextDocumentSyncKind.Full = 1;
\r
4152 * Documents are synced by sending the full content on open.
\r
4153 * After that only incremental updates to the document are
\r
4156 TextDocumentSyncKind.Incremental = 2;
\r
4157 })(TextDocumentSyncKind = exports.TextDocumentSyncKind || (exports.TextDocumentSyncKind = {}));
\r
4159 * The initialize request is sent from the client to the server.
\r
4160 * It is sent once as the request after starting up the server.
\r
4161 * The requests parameter is of type [InitializeParams](#InitializeParams)
\r
4162 * the response if of type [InitializeResult](#InitializeResult) of a Thenable that
\r
4163 * resolves to such.
\r
4165 var InitializeRequest;
\r
4166 (function (InitializeRequest) {
\r
4167 InitializeRequest.type = new vscode_jsonrpc_1.RequestType('initialize');
\r
4168 })(InitializeRequest = exports.InitializeRequest || (exports.InitializeRequest = {}));
\r
4170 * Known error codes for an `InitializeError`;
\r
4172 var InitializeError;
\r
4173 (function (InitializeError) {
\r
4175 * If the protocol version provided by the client can't be handled by the server.
\r
4176 * @deprecated This initialize error got replaced by client capabilities. There is
\r
4177 * no version handshake in version 3.0x
\r
4179 InitializeError.unknownProtocolVersion = 1;
\r
4180 })(InitializeError = exports.InitializeError || (exports.InitializeError = {}));
\r
4182 * The intialized notification is sent from the client to the
\r
4183 * server after the client is fully initialized and the server
\r
4184 * is allowed to send requests from the server to the client.
\r
4186 var InitializedNotification;
\r
4187 (function (InitializedNotification) {
\r
4188 InitializedNotification.type = new vscode_jsonrpc_1.NotificationType('initialized');
\r
4189 })(InitializedNotification = exports.InitializedNotification || (exports.InitializedNotification = {}));
\r
4190 //---- Shutdown Method ----
\r
4192 * A shutdown request is sent from the client to the server.
\r
4193 * It is sent once when the client decides to shutdown the
\r
4194 * server. The only notification that is sent after a shutdown request
\r
4195 * is the exit event.
\r
4197 var ShutdownRequest;
\r
4198 (function (ShutdownRequest) {
\r
4199 ShutdownRequest.type = new vscode_jsonrpc_1.RequestType0('shutdown');
\r
4200 })(ShutdownRequest = exports.ShutdownRequest || (exports.ShutdownRequest = {}));
\r
4201 //---- Exit Notification ----
\r
4203 * The exit event is sent from the client to the server to
\r
4204 * ask the server to exit its process.
\r
4206 var ExitNotification;
\r
4207 (function (ExitNotification) {
\r
4208 ExitNotification.type = new vscode_jsonrpc_1.NotificationType0('exit');
\r
4209 })(ExitNotification = exports.ExitNotification || (exports.ExitNotification = {}));
\r
4210 //---- Configuration notification ----
\r
4212 * The configuration change notification is sent from the client to the server
\r
4213 * when the client's configuration has changed. The notification contains
\r
4214 * the changed configuration as defined by the language client.
\r
4216 var DidChangeConfigurationNotification;
\r
4217 (function (DidChangeConfigurationNotification) {
\r
4218 DidChangeConfigurationNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeConfiguration');
\r
4219 })(DidChangeConfigurationNotification = exports.DidChangeConfigurationNotification || (exports.DidChangeConfigurationNotification = {}));
\r
4220 //---- Message show and log notifications ----
\r
4222 * The message type
\r
4225 (function (MessageType) {
\r
4227 * An error message.
\r
4229 MessageType.Error = 1;
\r
4231 * A warning message.
\r
4233 MessageType.Warning = 2;
\r
4235 * An information message.
\r
4237 MessageType.Info = 3;
\r
4241 MessageType.Log = 4;
\r
4242 })(MessageType = exports.MessageType || (exports.MessageType = {}));
\r
4244 * The show message notification is sent from a server to a client to ask
\r
4245 * the client to display a particular message in the user interface.
\r
4247 var ShowMessageNotification;
\r
4248 (function (ShowMessageNotification) {
\r
4249 ShowMessageNotification.type = new vscode_jsonrpc_1.NotificationType('window/showMessage');
\r
4250 })(ShowMessageNotification = exports.ShowMessageNotification || (exports.ShowMessageNotification = {}));
\r
4252 * The show message request is sent from the server to the client to show a message
\r
4253 * and a set of options actions to the user.
\r
4255 var ShowMessageRequest;
\r
4256 (function (ShowMessageRequest) {
\r
4257 ShowMessageRequest.type = new vscode_jsonrpc_1.RequestType('window/showMessageRequest');
\r
4258 })(ShowMessageRequest = exports.ShowMessageRequest || (exports.ShowMessageRequest = {}));
\r
4260 * The log message notification is sent from the server to the client to ask
\r
4261 * the client to log a particular message.
\r
4263 var LogMessageNotification;
\r
4264 (function (LogMessageNotification) {
\r
4265 LogMessageNotification.type = new vscode_jsonrpc_1.NotificationType('window/logMessage');
\r
4266 })(LogMessageNotification = exports.LogMessageNotification || (exports.LogMessageNotification = {}));
\r
4267 //---- Telemetry notification
\r
4269 * The telemetry event notification is sent from the server to the client to ask
\r
4270 * the client to log telemetry data.
\r
4272 var TelemetryEventNotification;
\r
4273 (function (TelemetryEventNotification) {
\r
4274 TelemetryEventNotification.type = new vscode_jsonrpc_1.NotificationType('telemetry/event');
\r
4275 })(TelemetryEventNotification = exports.TelemetryEventNotification || (exports.TelemetryEventNotification = {}));
\r
4277 * The document open notification is sent from the client to the server to signal
\r
4278 * newly opened text documents. The document's truth is now managed by the client
\r
4279 * and the server must not try to read the document's truth using the document's
\r
4280 * uri. Open in this sense means it is managed by the client. It doesn't necessarily
\r
4281 * mean that its content is presented in an editor. An open notification must not
\r
4282 * be sent more than once without a corresponding close notification send before.
\r
4283 * This means open and close notification must be balanced and the max open count
\r
4286 var DidOpenTextDocumentNotification;
\r
4287 (function (DidOpenTextDocumentNotification) {
\r
4288 DidOpenTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didOpen');
\r
4289 })(DidOpenTextDocumentNotification = exports.DidOpenTextDocumentNotification || (exports.DidOpenTextDocumentNotification = {}));
\r
4291 * The document change notification is sent from the client to the server to signal
\r
4292 * changes to a text document.
\r
4294 var DidChangeTextDocumentNotification;
\r
4295 (function (DidChangeTextDocumentNotification) {
\r
4296 DidChangeTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didChange');
\r
4297 })(DidChangeTextDocumentNotification = exports.DidChangeTextDocumentNotification || (exports.DidChangeTextDocumentNotification = {}));
\r
4299 * The document close notification is sent from the client to the server when
\r
4300 * the document got closed in the client. The document's truth now exists where
\r
4301 * the document's uri points to (e.g. if the document's uri is a file uri the
\r
4302 * truth now exists on disk). As with the open notification the close notification
\r
4303 * is about managing the document's content. Receiving a close notification
\r
4304 * doesn't mean that the document was open in an editor before. A close
\r
4305 * notification requires a previous open notification to be sent.
\r
4307 var DidCloseTextDocumentNotification;
\r
4308 (function (DidCloseTextDocumentNotification) {
\r
4309 DidCloseTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didClose');
\r
4310 })(DidCloseTextDocumentNotification = exports.DidCloseTextDocumentNotification || (exports.DidCloseTextDocumentNotification = {}));
\r
4312 * The document save notification is sent from the client to the server when
\r
4313 * the document got saved in the client.
\r
4315 var DidSaveTextDocumentNotification;
\r
4316 (function (DidSaveTextDocumentNotification) {
\r
4317 DidSaveTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/didSave');
\r
4318 })(DidSaveTextDocumentNotification = exports.DidSaveTextDocumentNotification || (exports.DidSaveTextDocumentNotification = {}));
\r
4320 * A document will save notification is sent from the client to the server before
\r
4321 * the document is actually saved.
\r
4323 var WillSaveTextDocumentNotification;
\r
4324 (function (WillSaveTextDocumentNotification) {
\r
4325 WillSaveTextDocumentNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/willSave');
\r
4326 })(WillSaveTextDocumentNotification = exports.WillSaveTextDocumentNotification || (exports.WillSaveTextDocumentNotification = {}));
\r
4328 * A document will save request is sent from the client to the server before
\r
4329 * the document is actually saved. The request can return an array of TextEdits
\r
4330 * which will be applied to the text document before it is saved. Please note that
\r
4331 * clients might drop results if computing the text edits took too long or if a
\r
4332 * server constantly fails on this request. This is done to keep the save fast and
\r
4335 var WillSaveTextDocumentWaitUntilRequest;
\r
4336 (function (WillSaveTextDocumentWaitUntilRequest) {
\r
4337 WillSaveTextDocumentWaitUntilRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/willSaveWaitUntil');
\r
4338 })(WillSaveTextDocumentWaitUntilRequest = exports.WillSaveTextDocumentWaitUntilRequest || (exports.WillSaveTextDocumentWaitUntilRequest = {}));
\r
4339 //---- File eventing ----
\r
4341 * The watched files notification is sent from the client to the server when
\r
4342 * the client detects changes to file watched by the language client.
\r
4344 var DidChangeWatchedFilesNotification;
\r
4345 (function (DidChangeWatchedFilesNotification) {
\r
4346 DidChangeWatchedFilesNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeWatchedFiles');
\r
4347 })(DidChangeWatchedFilesNotification = exports.DidChangeWatchedFilesNotification || (exports.DidChangeWatchedFilesNotification = {}));
\r
4349 * The file event type
\r
4351 var FileChangeType;
\r
4352 (function (FileChangeType) {
\r
4354 * The file got created.
\r
4356 FileChangeType.Created = 1;
\r
4358 * The file got changed.
\r
4360 FileChangeType.Changed = 2;
\r
4362 * The file got deleted.
\r
4364 FileChangeType.Deleted = 3;
\r
4365 })(FileChangeType = exports.FileChangeType || (exports.FileChangeType = {}));
\r
4367 (function (WatchKind) {
\r
4369 * Interested in create events.
\r
4371 WatchKind.Create = 1;
\r
4373 * Interested in change events
\r
4375 WatchKind.Change = 2;
\r
4377 * Interested in delete events
\r
4379 WatchKind.Delete = 4;
\r
4380 })(WatchKind = exports.WatchKind || (exports.WatchKind = {}));
\r
4381 //---- Diagnostic notification ----
\r
4383 * Diagnostics notification are sent from the server to the client to signal
\r
4384 * results of validation runs.
\r
4386 var PublishDiagnosticsNotification;
\r
4387 (function (PublishDiagnosticsNotification) {
\r
4388 PublishDiagnosticsNotification.type = new vscode_jsonrpc_1.NotificationType('textDocument/publishDiagnostics');
\r
4389 })(PublishDiagnosticsNotification = exports.PublishDiagnosticsNotification || (exports.PublishDiagnosticsNotification = {}));
\r
4391 * How a completion was triggered
\r
4393 var CompletionTriggerKind;
\r
4394 (function (CompletionTriggerKind) {
\r
4396 * Completion was triggered by typing an identifier (24x7 code
\r
4397 * complete), manual invocation (e.g Ctrl+Space) or via API.
\r
4399 CompletionTriggerKind.Invoked = 1;
\r
4401 * Completion was triggered by a trigger character specified by
\r
4402 * the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
\r
4404 CompletionTriggerKind.TriggerCharacter = 2;
\r
4406 * Completion was re-triggered as current completion list is incomplete
\r
4408 CompletionTriggerKind.TriggerForIncompleteCompletions = 3;
\r
4409 })(CompletionTriggerKind = exports.CompletionTriggerKind || (exports.CompletionTriggerKind = {}));
\r
4411 * Request to request completion at a given text document position. The request's
\r
4412 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response
\r
4413 * is of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)
\r
4414 * or a Thenable that resolves to such.
\r
4416 * The request can delay the computation of the [`detail`](#CompletionItem.detail)
\r
4417 * and [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`
\r
4418 * request. However, properties that are needed for the initial sorting and filtering, like `sortText`,
\r
4419 * `filterText`, `insertText`, and `textEdit`, must not be changed during resolve.
\r
4421 var CompletionRequest;
\r
4422 (function (CompletionRequest) {
\r
4423 CompletionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/completion');
\r
4424 })(CompletionRequest = exports.CompletionRequest || (exports.CompletionRequest = {}));
\r
4426 * Request to resolve additional information for a given completion item.The request's
\r
4427 * parameter is of type [CompletionItem](#CompletionItem) the response
\r
4428 * is of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such.
\r
4430 var CompletionResolveRequest;
\r
4431 (function (CompletionResolveRequest) {
\r
4432 CompletionResolveRequest.type = new vscode_jsonrpc_1.RequestType('completionItem/resolve');
\r
4433 })(CompletionResolveRequest = exports.CompletionResolveRequest || (exports.CompletionResolveRequest = {}));
\r
4434 //---- Hover Support -------------------------------
\r
4436 * Request to request hover information at a given text document position. The request's
\r
4437 * parameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of
\r
4438 * type [Hover](#Hover) or a Thenable that resolves to such.
\r
4441 (function (HoverRequest) {
\r
4442 HoverRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/hover');
\r
4443 })(HoverRequest = exports.HoverRequest || (exports.HoverRequest = {}));
\r
4444 var SignatureHelpRequest;
\r
4445 (function (SignatureHelpRequest) {
\r
4446 SignatureHelpRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/signatureHelp');
\r
4447 })(SignatureHelpRequest = exports.SignatureHelpRequest || (exports.SignatureHelpRequest = {}));
\r
4448 //---- Goto Definition -------------------------------------
\r
4450 * A request to resolve the definition location of a symbol at a given text
\r
4451 * document position. The request's parameter is of type [TextDocumentPosition]
\r
4452 * (#TextDocumentPosition) the response is of either type [Definition](#Definition)
\r
4453 * or a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves
\r
4456 var DefinitionRequest;
\r
4457 (function (DefinitionRequest) {
\r
4458 DefinitionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/definition');
\r
4459 })(DefinitionRequest = exports.DefinitionRequest || (exports.DefinitionRequest = {}));
\r
4461 * A request to resolve project-wide references for the symbol denoted
\r
4462 * by the given text document position. The request's parameter is of
\r
4463 * type [ReferenceParams](#ReferenceParams) the response is of type
\r
4464 * [Location[]](#Location) or a Thenable that resolves to such.
\r
4466 var ReferencesRequest;
\r
4467 (function (ReferencesRequest) {
\r
4468 ReferencesRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/references');
\r
4469 })(ReferencesRequest = exports.ReferencesRequest || (exports.ReferencesRequest = {}));
\r
4470 //---- Document Highlight ----------------------------------
\r
4472 * Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given
\r
4473 * text document position. The request's parameter is of type [TextDocumentPosition]
\r
4474 * (#TextDocumentPosition) the request response is of type [DocumentHighlight[]]
\r
4475 * (#DocumentHighlight) or a Thenable that resolves to such.
\r
4477 var DocumentHighlightRequest;
\r
4478 (function (DocumentHighlightRequest) {
\r
4479 DocumentHighlightRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentHighlight');
\r
4480 })(DocumentHighlightRequest = exports.DocumentHighlightRequest || (exports.DocumentHighlightRequest = {}));
\r
4481 //---- Document Symbol Provider ---------------------------
\r
4483 * A request to list all symbols found in a given text document. The request's
\r
4484 * parameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the
\r
4485 * response is of type [SymbolInformation[]](#SymbolInformation) or a Thenable
\r
4486 * that resolves to such.
\r
4488 var DocumentSymbolRequest;
\r
4489 (function (DocumentSymbolRequest) {
\r
4490 DocumentSymbolRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentSymbol');
\r
4491 })(DocumentSymbolRequest = exports.DocumentSymbolRequest || (exports.DocumentSymbolRequest = {}));
\r
4492 //---- Workspace Symbol Provider ---------------------------
\r
4494 * A request to list project-wide symbols matching the query string given
\r
4495 * by the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is
\r
4496 * of type [SymbolInformation[]](#SymbolInformation) or a Thenable that
\r
4497 * resolves to such.
\r
4499 var WorkspaceSymbolRequest;
\r
4500 (function (WorkspaceSymbolRequest) {
\r
4501 WorkspaceSymbolRequest.type = new vscode_jsonrpc_1.RequestType('workspace/symbol');
\r
4502 })(WorkspaceSymbolRequest = exports.WorkspaceSymbolRequest || (exports.WorkspaceSymbolRequest = {}));
\r
4504 * A request to provide commands for the given text document and range.
\r
4506 var CodeActionRequest;
\r
4507 (function (CodeActionRequest) {
\r
4508 CodeActionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeAction');
\r
4509 })(CodeActionRequest = exports.CodeActionRequest || (exports.CodeActionRequest = {}));
\r
4511 * A request to provide code lens for the given text document.
\r
4513 var CodeLensRequest;
\r
4514 (function (CodeLensRequest) {
\r
4515 CodeLensRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/codeLens');
\r
4516 })(CodeLensRequest = exports.CodeLensRequest || (exports.CodeLensRequest = {}));
\r
4518 * A request to resolve a command for a given code lens.
\r
4520 var CodeLensResolveRequest;
\r
4521 (function (CodeLensResolveRequest) {
\r
4522 CodeLensResolveRequest.type = new vscode_jsonrpc_1.RequestType('codeLens/resolve');
\r
4523 })(CodeLensResolveRequest = exports.CodeLensResolveRequest || (exports.CodeLensResolveRequest = {}));
\r
4525 * A request to to format a whole document.
\r
4527 var DocumentFormattingRequest;
\r
4528 (function (DocumentFormattingRequest) {
\r
4529 DocumentFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/formatting');
\r
4530 })(DocumentFormattingRequest = exports.DocumentFormattingRequest || (exports.DocumentFormattingRequest = {}));
\r
4532 * A request to to format a range in a document.
\r
4534 var DocumentRangeFormattingRequest;
\r
4535 (function (DocumentRangeFormattingRequest) {
\r
4536 DocumentRangeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rangeFormatting');
\r
4537 })(DocumentRangeFormattingRequest = exports.DocumentRangeFormattingRequest || (exports.DocumentRangeFormattingRequest = {}));
\r
4539 * A request to format a document on type.
\r
4541 var DocumentOnTypeFormattingRequest;
\r
4542 (function (DocumentOnTypeFormattingRequest) {
\r
4543 DocumentOnTypeFormattingRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/onTypeFormatting');
\r
4544 })(DocumentOnTypeFormattingRequest = exports.DocumentOnTypeFormattingRequest || (exports.DocumentOnTypeFormattingRequest = {}));
\r
4546 * A request to rename a symbol.
\r
4548 var RenameRequest;
\r
4549 (function (RenameRequest) {
\r
4550 RenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/rename');
\r
4551 })(RenameRequest = exports.RenameRequest || (exports.RenameRequest = {}));
\r
4553 * A request to test and perform the setup necessary for a rename.
\r
4555 var PrepareRenameRequest;
\r
4556 (function (PrepareRenameRequest) {
\r
4557 PrepareRenameRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/prepareRename');
\r
4558 })(PrepareRenameRequest = exports.PrepareRenameRequest || (exports.PrepareRenameRequest = {}));
\r
4560 * A request to provide document links
\r
4562 var DocumentLinkRequest;
\r
4563 (function (DocumentLinkRequest) {
\r
4564 DocumentLinkRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentLink');
\r
4565 })(DocumentLinkRequest = exports.DocumentLinkRequest || (exports.DocumentLinkRequest = {}));
\r
4567 * Request to resolve additional information for a given document link. The request's
\r
4568 * parameter is of type [DocumentLink](#DocumentLink) the response
\r
4569 * is of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such.
\r
4571 var DocumentLinkResolveRequest;
\r
4572 (function (DocumentLinkResolveRequest) {
\r
4573 DocumentLinkResolveRequest.type = new vscode_jsonrpc_1.RequestType('documentLink/resolve');
\r
4574 })(DocumentLinkResolveRequest = exports.DocumentLinkResolveRequest || (exports.DocumentLinkResolveRequest = {}));
\r
4576 * A request send from the client to the server to execute a command. The request might return
\r
4577 * a workspace edit which the client will apply to the workspace.
\r
4579 var ExecuteCommandRequest;
\r
4580 (function (ExecuteCommandRequest) {
\r
4581 ExecuteCommandRequest.type = new vscode_jsonrpc_1.RequestType('workspace/executeCommand');
\r
4582 })(ExecuteCommandRequest = exports.ExecuteCommandRequest || (exports.ExecuteCommandRequest = {}));
\r
4584 * A request sent from the server to the client to modified certain resources.
\r
4586 var ApplyWorkspaceEditRequest;
\r
4587 (function (ApplyWorkspaceEditRequest) {
\r
4588 ApplyWorkspaceEditRequest.type = new vscode_jsonrpc_1.RequestType('workspace/applyEdit');
\r
4589 })(ApplyWorkspaceEditRequest = exports.ApplyWorkspaceEditRequest || (exports.ApplyWorkspaceEditRequest = {}));
\r
4594 /***/ (function(module, exports, __webpack_require__) {
4597 /* --------------------------------------------------------------------------------------------
\r
4598 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4599 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4600 * ------------------------------------------------------------------------------------------ */
\r
4602 Object.defineProperty(exports, "__esModule", { value: true });
\r
4603 function boolean(value) {
\r
4604 return value === true || value === false;
\r
4606 exports.boolean = boolean;
\r
4607 function string(value) {
\r
4608 return typeof value === 'string' || value instanceof String;
\r
4610 exports.string = string;
\r
4611 function number(value) {
\r
4612 return typeof value === 'number' || value instanceof Number;
\r
4614 exports.number = number;
\r
4615 function error(value) {
\r
4616 return value instanceof Error;
\r
4618 exports.error = error;
\r
4619 function func(value) {
\r
4620 return typeof value === 'function';
\r
4622 exports.func = func;
\r
4623 function array(value) {
\r
4624 return Array.isArray(value);
\r
4626 exports.array = array;
\r
4627 function stringArray(value) {
\r
4628 return array(value) && value.every(elem => string(elem));
\r
4630 exports.stringArray = stringArray;
\r
4631 function typedArray(value, check) {
\r
4632 return Array.isArray(value) && value.every(check);
\r
4634 exports.typedArray = typedArray;
\r
4635 function thenable(value) {
\r
4636 return value && func(value.then);
\r
4638 exports.thenable = thenable;
\r
4643 /***/ (function(module, exports, __webpack_require__) {
4646 /* --------------------------------------------------------------------------------------------
\r
4647 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4648 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4649 * ------------------------------------------------------------------------------------------ */
\r
4651 Object.defineProperty(exports, "__esModule", { value: true });
\r
4652 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4653 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4654 let __noDynamicImport;
\r
4656 * A request to resolve the implementation locations of a symbol at a given text
\r
4657 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
4658 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
4659 * Thenable that resolves to such.
\r
4661 var ImplementationRequest;
\r
4662 (function (ImplementationRequest) {
\r
4663 ImplementationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/implementation');
\r
4664 })(ImplementationRequest = exports.ImplementationRequest || (exports.ImplementationRequest = {}));
\r
4669 /***/ (function(module, exports, __webpack_require__) {
4672 /* --------------------------------------------------------------------------------------------
\r
4673 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4674 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4675 * ------------------------------------------------------------------------------------------ */
\r
4677 Object.defineProperty(exports, "__esModule", { value: true });
\r
4678 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4679 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4680 let __noDynamicImport;
\r
4682 * A request to resolve the type definition locations of a symbol at a given text
\r
4683 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
4684 * (#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a
\r
4685 * Thenable that resolves to such.
\r
4687 var TypeDefinitionRequest;
\r
4688 (function (TypeDefinitionRequest) {
\r
4689 TypeDefinitionRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/typeDefinition');
\r
4690 })(TypeDefinitionRequest = exports.TypeDefinitionRequest || (exports.TypeDefinitionRequest = {}));
\r
4695 /***/ (function(module, exports, __webpack_require__) {
4698 /* --------------------------------------------------------------------------------------------
\r
4699 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4700 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4701 * ------------------------------------------------------------------------------------------ */
\r
4703 Object.defineProperty(exports, "__esModule", { value: true });
\r
4704 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4706 * The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders.
\r
4708 var WorkspaceFoldersRequest;
\r
4709 (function (WorkspaceFoldersRequest) {
\r
4710 WorkspaceFoldersRequest.type = new vscode_jsonrpc_1.RequestType0('workspace/workspaceFolders');
\r
4711 })(WorkspaceFoldersRequest = exports.WorkspaceFoldersRequest || (exports.WorkspaceFoldersRequest = {}));
\r
4713 * The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace
\r
4714 * folder configuration changes.
\r
4716 var DidChangeWorkspaceFoldersNotification;
\r
4717 (function (DidChangeWorkspaceFoldersNotification) {
\r
4718 DidChangeWorkspaceFoldersNotification.type = new vscode_jsonrpc_1.NotificationType('workspace/didChangeWorkspaceFolders');
\r
4719 })(DidChangeWorkspaceFoldersNotification = exports.DidChangeWorkspaceFoldersNotification || (exports.DidChangeWorkspaceFoldersNotification = {}));
\r
4724 /***/ (function(module, exports, __webpack_require__) {
4727 /* --------------------------------------------------------------------------------------------
\r
4728 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4729 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4730 * ------------------------------------------------------------------------------------------ */
\r
4732 Object.defineProperty(exports, "__esModule", { value: true });
\r
4733 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4735 * The 'workspace/configuration' request is sent from the server to the client to fetch a certain
\r
4736 * configuration setting.
\r
4738 * This pull model replaces the old push model were the client signaled configuration change via an
\r
4739 * event. If the server still needs to react to configuration changes (since the server caches the
\r
4740 * result of `workspace/configuration` requests) the server should register for an empty configuration
\r
4741 * change event and empty the cache if such an event is received.
\r
4743 var ConfigurationRequest;
\r
4744 (function (ConfigurationRequest) {
\r
4745 ConfigurationRequest.type = new vscode_jsonrpc_1.RequestType('workspace/configuration');
\r
4746 })(ConfigurationRequest = exports.ConfigurationRequest || (exports.ConfigurationRequest = {}));
\r
4751 /***/ (function(module, exports, __webpack_require__) {
4754 /* --------------------------------------------------------------------------------------------
\r
4755 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4756 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4757 * ------------------------------------------------------------------------------------------ */
\r
4759 Object.defineProperty(exports, "__esModule", { value: true });
\r
4760 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4762 * A request to list all color symbols found in a given text document. The request's
\r
4763 * parameter is of type [DocumentColorParams](#DocumentColorParams) the
\r
4764 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
4765 * that resolves to such.
\r
4767 var DocumentColorRequest;
\r
4768 (function (DocumentColorRequest) {
\r
4769 DocumentColorRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/documentColor');
\r
4770 })(DocumentColorRequest = exports.DocumentColorRequest || (exports.DocumentColorRequest = {}));
\r
4772 * A request to list all presentation for a color. The request's
\r
4773 * parameter is of type [ColorPresentationParams](#ColorPresentationParams) the
\r
4774 * response is of type [ColorInformation[]](#ColorInformation) or a Thenable
\r
4775 * that resolves to such.
\r
4777 var ColorPresentationRequest;
\r
4778 (function (ColorPresentationRequest) {
\r
4779 ColorPresentationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/colorPresentation');
\r
4780 })(ColorPresentationRequest = exports.ColorPresentationRequest || (exports.ColorPresentationRequest = {}));
\r
4785 /***/ (function(module, exports, __webpack_require__) {
4789 /*---------------------------------------------------------------------------------------------
\r
4790 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4791 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4792 *--------------------------------------------------------------------------------------------*/
\r
4793 Object.defineProperty(exports, "__esModule", { value: true });
\r
4794 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4796 * Enum of known range kinds
\r
4798 var FoldingRangeKind;
\r
4799 (function (FoldingRangeKind) {
\r
4801 * Folding range for a comment
\r
4803 FoldingRangeKind["Comment"] = "comment";
\r
4805 * Folding range for a imports or includes
\r
4807 FoldingRangeKind["Imports"] = "imports";
\r
4809 * Folding range for a region (e.g. `#region`)
\r
4811 FoldingRangeKind["Region"] = "region";
\r
4812 })(FoldingRangeKind = exports.FoldingRangeKind || (exports.FoldingRangeKind = {}));
\r
4814 * A request to provide folding ranges in a document. The request's
\r
4815 * parameter is of type [FoldingRangeParams](#FoldingRangeParams), the
\r
4816 * response is of type [FoldingRangeList](#FoldingRangeList) or a Thenable
\r
4817 * that resolves to such.
\r
4819 var FoldingRangeRequest;
\r
4820 (function (FoldingRangeRequest) {
\r
4821 FoldingRangeRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/foldingRange');
\r
4822 })(FoldingRangeRequest = exports.FoldingRangeRequest || (exports.FoldingRangeRequest = {}));
\r
4827 /***/ (function(module, exports, __webpack_require__) {
4830 /* --------------------------------------------------------------------------------------------
\r
4831 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4832 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4833 * ------------------------------------------------------------------------------------------ */
\r
4835 Object.defineProperty(exports, "__esModule", { value: true });
\r
4836 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4837 // @ts-ignore: to avoid inlining LocatioLink as dynamic import
\r
4838 let __noDynamicImport;
\r
4840 * A request to resolve the type definition locations of a symbol at a given text
\r
4841 * document position. The request's parameter is of type [TextDocumentPositioParams]
\r
4842 * (#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)
\r
4843 * or a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves
\r
4846 var DeclarationRequest;
\r
4847 (function (DeclarationRequest) {
\r
4848 DeclarationRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/declaration');
\r
4849 })(DeclarationRequest = exports.DeclarationRequest || (exports.DeclarationRequest = {}));
\r
4854 /***/ (function(module, exports, __webpack_require__) {
4857 /* --------------------------------------------------------------------------------------------
\r
4858 * Copyright (c) TypeFox and others. All rights reserved.
\r
4859 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4860 * ------------------------------------------------------------------------------------------ */
\r
4862 Object.defineProperty(exports, "__esModule", { value: true });
\r
4863 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4865 * The direction of a call hierarchy request.
\r
4867 var CallHierarchyDirection;
\r
4868 (function (CallHierarchyDirection) {
\r
4872 CallHierarchyDirection.CallsFrom = 1;
\r
4876 CallHierarchyDirection.CallsTo = 2;
\r
4877 })(CallHierarchyDirection = exports.CallHierarchyDirection || (exports.CallHierarchyDirection = {}));
\r
4879 * Request to provide the call hierarchy at a given text document position.
\r
4881 * The request's parameter is of type [CallHierarchyParams](#CallHierarchyParams). The response
\r
4882 * is of type [CallHierarchyCall[]](#CallHierarchyCall) or a Thenable that resolves to such.
\r
4884 * Evaluates the symbol defined (or referenced) at the given position, and returns all incoming or outgoing calls to the symbol(s).
\r
4886 var CallHierarchyRequest;
\r
4887 (function (CallHierarchyRequest) {
\r
4888 CallHierarchyRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/callHierarchy');
\r
4889 })(CallHierarchyRequest = exports.CallHierarchyRequest || (exports.CallHierarchyRequest = {}));
\r
4894 /***/ (function(module, exports, __webpack_require__) {
4897 /* --------------------------------------------------------------------------------------------
\r
4898 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4899 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4900 * ------------------------------------------------------------------------------------------ */
\r
4902 Object.defineProperty(exports, "__esModule", { value: true });
\r
4903 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4905 * The `window/progress/start` notification is sent from the server to the client
\r
4906 * to initiate a progress.
\r
4908 var ProgressStartNotification;
\r
4909 (function (ProgressStartNotification) {
\r
4910 ProgressStartNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/start');
\r
4911 })(ProgressStartNotification = exports.ProgressStartNotification || (exports.ProgressStartNotification = {}));
\r
4913 * The `window/progress/report` notification is sent from the server to the client
\r
4914 * to initiate a progress.
\r
4916 var ProgressReportNotification;
\r
4917 (function (ProgressReportNotification) {
\r
4918 ProgressReportNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/report');
\r
4919 })(ProgressReportNotification = exports.ProgressReportNotification || (exports.ProgressReportNotification = {}));
\r
4921 * The `window/progress/done` notification is sent from the server to the client
\r
4922 * to initiate a progress.
\r
4924 var ProgressDoneNotification;
\r
4925 (function (ProgressDoneNotification) {
\r
4926 ProgressDoneNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/done');
\r
4927 })(ProgressDoneNotification = exports.ProgressDoneNotification || (exports.ProgressDoneNotification = {}));
\r
4929 * The `window/progress/cancel` notification is sent client to the server to cancel a progress
\r
4930 * initiated on the server side.
\r
4932 var ProgressCancelNotification;
\r
4933 (function (ProgressCancelNotification) {
\r
4934 ProgressCancelNotification.type = new vscode_jsonrpc_1.NotificationType('window/progress/cancel');
\r
4935 })(ProgressCancelNotification = exports.ProgressCancelNotification || (exports.ProgressCancelNotification = {}));
\r
4940 /***/ (function(module, exports, __webpack_require__) {
4944 /*---------------------------------------------------------------------------------------------
\r
4945 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
4946 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
4947 *--------------------------------------------------------------------------------------------*/
\r
4948 Object.defineProperty(exports, "__esModule", { value: true });
\r
4949 const vscode_jsonrpc_1 = __webpack_require__(4);
\r
4950 const vscode_languageserver_types_1 = __webpack_require__(17);
\r
4952 * The SelectionRange namespace provides helper function to work with
\r
4953 * SelectionRange literals.
\r
4955 var SelectionRange;
\r
4956 (function (SelectionRange) {
\r
4958 * Creates a new SelectionRange
\r
4959 * @param range the range.
\r
4960 * @param parent an optional parent.
\r
4962 function create(range, parent) {
\r
4963 return { range, parent };
\r
4965 SelectionRange.create = create;
\r
4966 function is(value) {
\r
4967 let candidate = value;
\r
4968 return candidate !== undefined && vscode_languageserver_types_1.Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
\r
4970 SelectionRange.is = is;
\r
4971 })(SelectionRange = exports.SelectionRange || (exports.SelectionRange = {}));
\r
4973 * A request to provide selection ranges in a document. The request's
\r
4974 * parameter is of type [SelectionRangeParams](#SelectionRangeParams), the
\r
4975 * response is of type [SelectionRange[]](#SelectionRange[]) or a Thenable
\r
4976 * that resolves to such.
\r
4978 var SelectionRangeRequest;
\r
4979 (function (SelectionRangeRequest) {
\r
4980 SelectionRangeRequest.type = new vscode_jsonrpc_1.RequestType('textDocument/selectionRange');
\r
4981 })(SelectionRangeRequest = exports.SelectionRangeRequest || (exports.SelectionRangeRequest = {}));
\r
4989 /***/ (function(module, exports, __webpack_require__) {
4993 /*---------------------------------------------------------------------------------------------
4994 * Copyright (c) Microsoft Corporation. All rights reserved.
4995 * Licensed under the MIT License. See License.txt in the project root for license information.
4996 *--------------------------------------------------------------------------------------------*/
4997 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4998 return new (P || (P = Promise))(function (resolve, reject) {
4999 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5000 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5001 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
5002 step((generator = generator.apply(thisArg, _arguments || [])).next());
5005 var __importStar = (this && this.__importStar) || function (mod) {
5006 if (mod && mod.__esModule) return mod;
5008 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
5009 result["default"] = mod;
5012 Object.defineProperty(exports, "__esModule", { value: true });
5013 const vscode_languageserver_1 = __webpack_require__(34);
5014 const request_light_1 = __webpack_require__(49);
5015 const fs = __importStar(__webpack_require__(2));
5016 const vscode_uri_1 = __webpack_require__(77);
5017 const URL = __importStar(__webpack_require__(40));
5018 const runner_1 = __webpack_require__(78);
5019 const vscode_json_languageservice_1 = __webpack_require__(79);
5020 const languageModelCache_1 = __webpack_require__(101);
5021 var SchemaAssociationNotification;
5022 (function (SchemaAssociationNotification) {
5023 SchemaAssociationNotification.type = new vscode_languageserver_1.NotificationType('json/schemaAssociations');
5024 })(SchemaAssociationNotification || (SchemaAssociationNotification = {}));
5025 var VSCodeContentRequest;
5026 (function (VSCodeContentRequest) {
5027 VSCodeContentRequest.type = new vscode_languageserver_1.RequestType('vscode/content');
5028 })(VSCodeContentRequest || (VSCodeContentRequest = {}));
5029 var SchemaContentChangeNotification;
5030 (function (SchemaContentChangeNotification) {
5031 SchemaContentChangeNotification.type = new vscode_languageserver_1.NotificationType('json/schemaContent');
5032 })(SchemaContentChangeNotification || (SchemaContentChangeNotification = {}));
5033 var ForceValidateRequest;
5034 (function (ForceValidateRequest) {
5035 ForceValidateRequest.type = new vscode_languageserver_1.RequestType('json/validate');
5036 })(ForceValidateRequest || (ForceValidateRequest = {}));
5037 // Create a connection for the server
5038 const connection = vscode_languageserver_1.createConnection();
5039 process.on('unhandledRejection', (e) => {
5040 console.error(runner_1.formatError(`Unhandled exception`, e));
5042 process.on('uncaughtException', (e) => {
5043 console.error(runner_1.formatError(`Unhandled exception`, e));
5045 console.log = connection.console.log.bind(connection.console);
5046 console.error = connection.console.error.bind(connection.console);
5047 const workspaceContext = {
5048 resolveRelativePath: (relativePath, resource) => {
5049 return URL.resolve(resource, relativePath);
5052 function getSchemaRequestService(handledSchemas) {
5054 const protocol = uri.substr(0, uri.indexOf(':'));
5055 if (!handledSchemas || handledSchemas[protocol]) {
5056 if (protocol === 'file') {
5057 const fsPath = vscode_uri_1.URI.parse(uri).fsPath;
5058 return new Promise((c, e) => {
5059 fs.readFile(fsPath, 'UTF-8', (err, result) => {
5060 err ? e(err.message || err.toString()) : c(result.toString());
5064 else if (protocol === 'http' || protocol === 'https') {
5065 if (uri.indexOf('//schema.management.azure.com/') !== -1) {
5068 "schemaURL" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
5071 connection.telemetry.logEvent({
5078 const headers = { 'Accept-Encoding': 'gzip, deflate' };
5079 return request_light_1.xhr({ url: uri, followRedirects: 5, headers }).then(response => {
5080 return response.responseText;
5082 return Promise.reject(error.responseText || request_light_1.getErrorStatusDescription(error.status) || error.toString());
5086 return connection.sendRequest(VSCodeContentRequest.type, uri).then(responseText => {
5087 return responseText;
5089 return Promise.reject(error.message);
5093 // create the JSON language service
5094 let languageService = vscode_json_languageservice_1.getLanguageService({
5098 // Create a simple text document manager. The text document manager
5099 // supports full document sync only
5100 const documents = new vscode_languageserver_1.TextDocuments();
5101 // Make the text document manager listen on the connection
5102 // for open, change and close text document events
5103 documents.listen(connection);
5104 let clientSnippetSupport = false;
5105 let clientDynamicRegisterSupport = false;
5106 let foldingRangeLimit = Number.MAX_VALUE;
5107 let hierarchicalDocumentSymbolSupport = false;
5108 // After the server has started the client sends an initialize request. The server receives
5109 // in the passed params the rootPath of the workspace plus the client capabilities.
5110 connection.onInitialize((params) => {
5111 const handledProtocols = params.initializationOptions && params.initializationOptions['handledSchemaProtocols'];
5112 languageService = vscode_json_languageservice_1.getLanguageService({
5113 schemaRequestService: getSchemaRequestService(handledProtocols),
5116 clientCapabilities: params.capabilities
5118 function getClientCapability(name, def) {
5119 const keys = name.split('.');
5120 let c = params.capabilities;
5121 for (let i = 0; c && i < keys.length; i++) {
5122 if (!c.hasOwnProperty(keys[i])) {
5129 clientSnippetSupport = getClientCapability('textDocument.completion.completionItem.snippetSupport', false);
5130 clientDynamicRegisterSupport = getClientCapability('workspace.symbol.dynamicRegistration', false);
5131 foldingRangeLimit = getClientCapability('textDocument.foldingRange.rangeLimit', Number.MAX_VALUE);
5132 hierarchicalDocumentSymbolSupport = getClientCapability('textDocument.documentSymbol.hierarchicalDocumentSymbolSupport', false);
5133 const capabilities = {
5134 // Tell the client that the server works in FULL text document sync mode
5135 textDocumentSync: documents.syncKind,
5136 completionProvider: clientSnippetSupport ? { resolveProvider: true, triggerCharacters: ['"', ':'] } : undefined,
5137 hoverProvider: true,
5138 documentSymbolProvider: true,
5139 documentRangeFormattingProvider: false,
5141 foldingRangeProvider: true
5143 return { capabilities };
5145 let jsonConfigurationSettings = undefined;
5146 let schemaAssociations = undefined;
5147 let formatterRegistration = null;
5148 // The settings have changed. Is send on server activation as well.
5149 connection.onDidChangeConfiguration((change) => {
5150 let settings = change.settings;
5151 request_light_1.configure(settings.http && settings.http.proxy, settings.http && settings.http.proxyStrictSSL);
5152 jsonConfigurationSettings = settings.json && settings.json.schemas;
5153 updateConfiguration();
5154 // dynamically enable & disable the formatter
5155 if (clientDynamicRegisterSupport) {
5156 const enableFormatter = settings && settings.json && settings.json.format && settings.json.format.enable;
5157 if (enableFormatter) {
5158 if (!formatterRegistration) {
5159 formatterRegistration = connection.client.register(vscode_languageserver_1.DocumentRangeFormattingRequest.type, { documentSelector: [{ language: 'json' }, { language: 'jsonc' }] });
5162 else if (formatterRegistration) {
5163 formatterRegistration.then(r => r.dispose());
5164 formatterRegistration = null;
5168 // The jsonValidation extension configuration has changed
5169 connection.onNotification(SchemaAssociationNotification.type, associations => {
5170 schemaAssociations = associations;
5171 updateConfiguration();
5173 // A schema has changed
5174 connection.onNotification(SchemaContentChangeNotification.type, uri => {
5175 languageService.resetSchema(uri);
5177 // Retry schema validation on all open documents
5178 connection.onRequest(ForceValidateRequest.type, uri => {
5179 return new Promise(resolve => {
5180 const document = documents.get(uri);
5182 updateConfiguration();
5183 validateTextDocument(document, diagnostics => {
5184 resolve(diagnostics);
5192 function updateConfiguration() {
5193 const languageSettings = {
5195 allowComments: true,
5196 schemas: new Array()
5198 if (schemaAssociations) {
5199 for (const pattern in schemaAssociations) {
5200 const association = schemaAssociations[pattern];
5201 if (Array.isArray(association)) {
5202 association.forEach(uri => {
5203 languageSettings.schemas.push({ uri, fileMatch: [pattern] });
5208 if (jsonConfigurationSettings) {
5209 jsonConfigurationSettings.forEach((schema, index) => {
5210 let uri = schema.url;
5211 if (!uri && schema.schema) {
5212 uri = schema.schema.id || `vscode://schemas/custom/${index}`;
5215 languageSettings.schemas.push({ uri, fileMatch: schema.fileMatch, schema: schema.schema });
5219 languageService.configure(languageSettings);
5220 // Revalidate any open text documents
5221 documents.all().forEach(triggerValidation);
5223 // The content of a text document has changed. This event is emitted
5224 // when the text document first opened or when its content has changed.
5225 documents.onDidChangeContent((change) => {
5226 triggerValidation(change.document);
5228 // a document has closed: clear all diagnostics
5229 documents.onDidClose(event => {
5230 cleanPendingValidation(event.document);
5231 connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
5233 const pendingValidationRequests = {};
5234 const validationDelayMs = 500;
5235 function cleanPendingValidation(textDocument) {
5236 const request = pendingValidationRequests[textDocument.uri];
5238 clearTimeout(request);
5239 delete pendingValidationRequests[textDocument.uri];
5242 function triggerValidation(textDocument) {
5243 cleanPendingValidation(textDocument);
5244 pendingValidationRequests[textDocument.uri] = setTimeout(() => {
5245 delete pendingValidationRequests[textDocument.uri];
5246 validateTextDocument(textDocument);
5247 }, validationDelayMs);
5249 function validateTextDocument(textDocument, callback) {
5250 const respond = (diagnostics) => {
5251 connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
5253 callback(diagnostics);
5256 if (textDocument.getText().length === 0) {
5257 respond([]); // ignore empty documents
5260 const jsonDocument = getJSONDocument(textDocument);
5261 const version = textDocument.version;
5262 const documentSettings = textDocument.languageId === 'jsonc' ? { comments: 'ignore', trailingCommas: 'ignore' } : { comments: 'error', trailingCommas: 'error' };
5263 languageService.doValidation(textDocument, jsonDocument, documentSettings).then(diagnostics => {
5265 const currDocument = documents.get(textDocument.uri);
5266 if (currDocument && currDocument.version === version) {
5267 respond(diagnostics); // Send the computed diagnostics to VSCode.
5271 connection.console.error(runner_1.formatError(`Error while validating ${textDocument.uri}`, error));
5274 connection.onDidChangeWatchedFiles((change) => {
5275 // Monitored files have changed in VSCode
5276 let hasChanges = false;
5277 change.changes.forEach(c => {
5278 if (languageService.resetSchema(c.uri)) {
5283 documents.all().forEach(triggerValidation);
5286 const jsonDocuments = languageModelCache_1.getLanguageModelCache(10, 60, document => languageService.parseJSONDocument(document));
5287 documents.onDidClose(e => {
5288 jsonDocuments.onDocumentRemoved(e.document);
5290 connection.onShutdown(() => {
5291 jsonDocuments.dispose();
5293 function getJSONDocument(document) {
5294 return jsonDocuments.get(document);
5296 connection.onCompletion((textDocumentPosition, token) => {
5297 return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
5298 const document = documents.get(textDocumentPosition.textDocument.uri);
5300 const jsonDocument = getJSONDocument(document);
5301 return languageService.doComplete(document, textDocumentPosition.position, jsonDocument);
5304 }), null, `Error while computing completions for ${textDocumentPosition.textDocument.uri}`, token);
5306 connection.onCompletionResolve((completionItem, token) => {
5307 return runner_1.runSafeAsync(() => {
5308 return languageService.doResolve(completionItem);
5309 }, completionItem, `Error while resolving completion proposal`, token);
5311 connection.onHover((textDocumentPositionParams, token) => {
5312 return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
5313 const document = documents.get(textDocumentPositionParams.textDocument.uri);
5315 const jsonDocument = getJSONDocument(document);
5316 return languageService.doHover(document, textDocumentPositionParams.position, jsonDocument);
5319 }), null, `Error while computing hover for ${textDocumentPositionParams.textDocument.uri}`, token);
5321 connection.onDocumentSymbol((documentSymbolParams, token) => {
5322 return runner_1.runSafe(() => {
5323 const document = documents.get(documentSymbolParams.textDocument.uri);
5325 const jsonDocument = getJSONDocument(document);
5326 if (hierarchicalDocumentSymbolSupport) {
5327 return languageService.findDocumentSymbols2(document, jsonDocument);
5330 return languageService.findDocumentSymbols(document, jsonDocument);
5334 }, [], `Error while computing document symbols for ${documentSymbolParams.textDocument.uri}`, token);
5336 connection.onDocumentRangeFormatting((formatParams, token) => {
5337 return runner_1.runSafe(() => {
5338 const document = documents.get(formatParams.textDocument.uri);
5340 return languageService.format(document, formatParams.range, formatParams.options);
5343 }, [], `Error while formatting range for ${formatParams.textDocument.uri}`, token);
5345 connection.onDocumentColor((params, token) => {
5346 return runner_1.runSafeAsync(() => __awaiter(this, void 0, void 0, function* () {
5347 const document = documents.get(params.textDocument.uri);
5349 const jsonDocument = getJSONDocument(document);
5350 return languageService.findDocumentColors(document, jsonDocument);
5353 }), [], `Error while computing document colors for ${params.textDocument.uri}`, token);
5355 connection.onColorPresentation((params, token) => {
5356 return runner_1.runSafe(() => {
5357 const document = documents.get(params.textDocument.uri);
5359 const jsonDocument = getJSONDocument(document);
5360 return languageService.getColorPresentations(document, jsonDocument, params.color, params.range);
5363 }, [], `Error while computing color presentations for ${params.textDocument.uri}`, token);
5365 connection.onFoldingRanges((params, token) => {
5366 return runner_1.runSafe(() => {
5367 const document = documents.get(params.textDocument.uri);
5369 return languageService.getFoldingRanges(document, { rangeLimit: foldingRangeLimit });
5372 }, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
5374 connection.onRequest('$/textDocument/selectionRanges', (params, token) => __awaiter(this, void 0, void 0, function* () {
5375 return runner_1.runSafe(() => {
5376 const document = documents.get(params.textDocument.uri);
5378 const jsonDocument = getJSONDocument(document);
5379 return languageService.getSelectionRanges(document, params.positions, jsonDocument);
5382 }, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
5384 // Listen on the connection
5385 connection.listen();
5390 /***/ (function(module, exports, __webpack_require__) {
5393 /* --------------------------------------------------------------------------------------------
\r
5394 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5395 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
5396 * ------------------------------------------------------------------------------------------ */
\r
5397 /// <reference path="./thenable.ts" />
\r
5399 function __export(m) {
\r
5400 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
\r
5402 Object.defineProperty(exports, "__esModule", { value: true });
\r
5403 const vscode_languageserver_protocol_1 = __webpack_require__(3);
\r
5404 exports.Event = vscode_languageserver_protocol_1.Event;
\r
5405 const configuration_1 = __webpack_require__(35);
\r
5406 const workspaceFolders_1 = __webpack_require__(37);
\r
5407 const Is = __webpack_require__(36);
\r
5408 const UUID = __webpack_require__(38);
\r
5409 // ------------- Reexport the API surface of the language worker API ----------------------
\r
5410 __export(__webpack_require__(3));
\r
5411 const fm = __webpack_require__(39);
\r
5412 const vscode_textbuffer_1 = __webpack_require__(42);
\r
5413 const range_1 = __webpack_require__(47);
\r
5415 (function (Files) {
\r
5416 Files.uriToFilePath = fm.uriToFilePath;
\r
5417 Files.resolveGlobalNodePath = fm.resolveGlobalNodePath;
\r
5418 Files.resolveGlobalYarnPath = fm.resolveGlobalYarnPath;
\r
5419 Files.resolve = fm.resolve;
\r
5420 Files.resolveModulePath = fm.resolveModulePath;
\r
5421 })(Files = exports.Files || (exports.Files = {}));
\r
5422 let shutdownReceived = false;
\r
5423 let exitTimer = undefined;
\r
5424 function setupExitTimer() {
\r
5425 const argName = '--clientProcessId';
\r
5426 function runTimer(value) {
\r
5428 let processId = parseInt(value);
\r
5429 if (!isNaN(processId)) {
\r
5430 exitTimer = setInterval(() => {
\r
5432 process.kill(processId, 0);
\r
5435 // Parent process doesn't exist anymore. Exit the server.
\r
5436 process.exit(shutdownReceived ? 0 : 1);
\r
5445 for (let i = 2; i < process.argv.length; i++) {
\r
5446 let arg = process.argv[i];
\r
5447 if (arg === argName && i + 1 < process.argv.length) {
\r
5448 runTimer(process.argv[i + 1]);
\r
5452 let args = arg.split('=');
\r
5453 if (args[0] === argName) {
\r
5454 runTimer(args[1]);
\r
5460 function null2Undefined(value) {
\r
5461 if (value === null) {
\r
5467 * Incrementally-synchronized Text Document implementation that leverages a
\r
5468 * "Piece Tree" as text buffer. See the following for details:
\r
5469 * - https://github.com/microsoft/vscode-textbuffer
\r
5470 * - https://code.visualstudio.com/blogs/2018/03/23/text-buffer-reimplementation
\r
5472 * This text document implementation only supports "Incremental" text document
\r
5473 * sync. If you wish to use "Full" text document sync, use FullTextDocument, as it
\r
5474 * uses a simple JS string as an underlying text buffer, since the full text gets
\r
5475 * swapped out on every update.
\r
5477 class IncrementalTextDocument {
\r
5478 constructor(uri, languageId, version, content) {
\r
5480 this._languageId = languageId;
\r
5481 this._version = version;
\r
5482 // Prepare Piece Tree
\r
5483 const ptBuilder = new vscode_textbuffer_1.PieceTreeTextBufferBuilder();
\r
5484 ptBuilder.acceptChunk(content);
\r
5485 const ptFactory = ptBuilder.finish(true);
\r
5486 this._tree = ptFactory.create(1 /* LF */);
\r
5491 get languageId() {
\r
5492 return this._languageId;
\r
5495 return this._version;
\r
5499 const { start, end } = range;
\r
5500 // Clamp last line and last character appropriately when
\r
5501 // given range is beyond the document's end
\r
5502 const [clampedEndLine, clampedEndChar] = end.line + 1 > this.lineCount
\r
5503 ? [this.lineCount, this._tree.getLineLength(this.lineCount) + 1]
\r
5504 : [end.line + 1, end.character + 1];
\r
5505 const ptRange = new range_1.Range(start.line + 1, start.character + 1, clampedEndLine, clampedEndChar);
\r
5506 return this._tree.getValueInRange(ptRange);
\r
5508 return this._tree.getLinesRawContent();
\r
5510 update(event, version) {
\r
5511 const { text, range } = event;
\r
5512 if (range == null) {
\r
5513 throw new Error(`FullPieceTreeTextDocument#update called with invalid event range ${range}`);
\r
5515 const startOffset = this.offsetAt(range.start);
\r
5516 const endOffset = this.offsetAt(range.end);
\r
5517 // Delete previous text at range and insert new text at appropriate offset
\r
5518 this._tree.delete(startOffset, endOffset - startOffset);
\r
5519 this._tree.insert(startOffset, text);
\r
5520 this._version = version;
\r
5522 positionAt(offset) {
\r
5523 const clampedOffset = Math.min(offset, this._tree.getLength());
\r
5524 const ptPosition = this._tree.getPositionAt(clampedOffset);
\r
5525 return vscode_languageserver_protocol_1.Position.create(ptPosition.lineNumber - 1, ptPosition.column - 1);
\r
5527 offsetAt(position) {
\r
5528 if (position.line < 0) {
\r
5531 const clampedChar = Math.max(1, position.character + 1);
\r
5532 return Math.min(this._tree.getOffsetAt(position.line + 1, clampedChar), this._tree.getLength());
\r
5535 return this._tree.getLineCount();
\r
5539 * A manager for simple text documents
\r
5541 class TextDocuments {
\r
5543 * Create a new text document manager.
\r
5545 constructor(syncKind = vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) {
\r
5546 this._documents = Object.create(null);
\r
5547 this._syncKind = syncKind;
\r
5548 this._onDidChangeContent = new vscode_languageserver_protocol_1.Emitter();
\r
5549 this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();
\r
5550 this._onDidClose = new vscode_languageserver_protocol_1.Emitter();
\r
5551 this._onDidSave = new vscode_languageserver_protocol_1.Emitter();
\r
5552 this._onWillSave = new vscode_languageserver_protocol_1.Emitter();
\r
5555 * Returns the [TextDocumentSyncKind](#TextDocumentSyncKind) used by
\r
5556 * this text document manager.
\r
5559 return this._syncKind;
\r
5562 * An event that fires when a text document managed by this manager
\r
5563 * has been opened or the content changes.
\r
5565 get onDidChangeContent() {
\r
5566 return this._onDidChangeContent.event;
\r
5569 * An event that fires when a text document managed by this manager
\r
5570 * has been opened.
\r
5573 return this._onDidOpen.event;
\r
5576 * An event that fires when a text document managed by this manager
\r
5579 get onWillSave() {
\r
5580 return this._onWillSave.event;
\r
5583 * Sets a handler that will be called if a participant wants to provide
\r
5584 * edits during a text document save.
\r
5586 onWillSaveWaitUntil(handler) {
\r
5587 this._willSaveWaitUntil = handler;
\r
5590 * An event that fires when a text document managed by this manager
\r
5594 return this._onDidSave.event;
\r
5597 * An event that fires when a text document managed by this manager
\r
5598 * has been closed.
\r
5600 get onDidClose() {
\r
5601 return this._onDidClose.event;
\r
5604 * Returns the document for the given URI. Returns undefined if
\r
5605 * the document is not mananged by this instance.
\r
5607 * @param uri The text document's URI to retrieve.
\r
5608 * @return the text document or `undefined`.
\r
5611 return this._documents[uri];
\r
5614 * Returns all text documents managed by this instance.
\r
5616 * @return all text documents.
\r
5619 return Object.keys(this._documents).map(key => this._documents[key]);
\r
5622 * Returns the URIs of all text documents managed by this instance.
\r
5624 * @return the URI's of all text documents.
\r
5627 return Object.keys(this._documents);
\r
5630 * Listens for `low level` notification on the given connection to
\r
5631 * update the text documents managed by this instance.
\r
5633 * @param connection The connection to listen on.
\r
5635 listen(connection) {
\r
5636 function isUpdateableDocument(value) {
\r
5637 return Is.func(value.update);
\r
5639 connection.__textDocumentSync = vscode_languageserver_protocol_1.TextDocumentSyncKind.Full;
\r
5640 connection.onDidOpenTextDocument((event) => {
\r
5641 let td = event.textDocument;
\r
5643 switch (this.syncKind) {
\r
5644 case vscode_languageserver_protocol_1.TextDocumentSyncKind.Full:
\r
5645 document = vscode_languageserver_protocol_1.TextDocument.create(td.uri, td.languageId, td.version, td.text);
\r
5647 case vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental:
\r
5648 document = new IncrementalTextDocument(td.uri, td.languageId, td.version, td.text);
\r
5651 throw new Error(`Invalid TextDocumentSyncKind: ${this.syncKind}`);
\r
5653 this._documents[td.uri] = document;
\r
5654 let toFire = Object.freeze({ document });
\r
5655 this._onDidOpen.fire(toFire);
\r
5656 this._onDidChangeContent.fire(toFire);
\r
5658 connection.onDidChangeTextDocument((event) => {
\r
5659 let td = event.textDocument;
\r
5660 let changes = event.contentChanges;
\r
5661 if (changes.length === 0) {
\r
5664 let document = this._documents[td.uri];
\r
5665 if (!document || !isUpdateableDocument(document)) {
\r
5668 const { version } = td;
\r
5669 if (version == null || version === void 0) {
\r
5670 throw new Error(`Received document change event for ${td.uri} without valid version identifier`);
\r
5672 switch (this.syncKind) {
\r
5673 case vscode_languageserver_protocol_1.TextDocumentSyncKind.Full:
\r
5674 let last = changes[changes.length - 1];
\r
5675 document.update(last, version);
\r
5676 this._onDidChangeContent.fire(Object.freeze({ document }));
\r
5678 case vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental:
\r
5679 let updatedDoc = changes.reduce((workingTextDoc, change) => {
\r
5680 workingTextDoc.update(change, version);
\r
5681 return workingTextDoc;
\r
5683 this._onDidChangeContent.fire(Object.freeze({ document: updatedDoc }));
\r
5685 case vscode_languageserver_protocol_1.TextDocumentSyncKind.None:
\r
5689 connection.onDidCloseTextDocument((event) => {
\r
5690 let document = this._documents[event.textDocument.uri];
\r
5692 delete this._documents[event.textDocument.uri];
\r
5693 this._onDidClose.fire(Object.freeze({ document }));
\r
5696 connection.onWillSaveTextDocument((event) => {
\r
5697 let document = this._documents[event.textDocument.uri];
\r
5699 this._onWillSave.fire(Object.freeze({ document, reason: event.reason }));
\r
5702 connection.onWillSaveTextDocumentWaitUntil((event, token) => {
\r
5703 let document = this._documents[event.textDocument.uri];
\r
5704 if (document && this._willSaveWaitUntil) {
\r
5705 return this._willSaveWaitUntil(Object.freeze({ document, reason: event.reason }), token);
\r
5711 connection.onDidSaveTextDocument((event) => {
\r
5712 let document = this._documents[event.textDocument.uri];
\r
5714 this._onDidSave.fire(Object.freeze({ document }));
\r
5719 exports.TextDocuments = TextDocuments;
\r
5721 * Helps tracking error message. Equal occurences of the same
\r
5722 * message are only stored once. This class is for example
\r
5723 * useful if text documents are validated in a loop and equal
\r
5724 * error message should be folded into one.
\r
5726 class ErrorMessageTracker {
\r
5728 this._messages = Object.create(null);
\r
5731 * Add a message to the tracker.
\r
5733 * @param message The message to add.
\r
5736 let count = this._messages[message];
\r
5741 this._messages[message] = count;
\r
5744 * Send all tracked messages to the connection's window.
\r
5746 * @param connection The connection established between client and server.
\r
5748 sendErrors(connection) {
\r
5749 Object.keys(this._messages).forEach(message => {
\r
5750 connection.window.showErrorMessage(message);
\r
5754 exports.ErrorMessageTracker = ErrorMessageTracker;
\r
5755 var BulkRegistration;
\r
5756 (function (BulkRegistration) {
\r
5758 * Creates a new bulk registration.
\r
5759 * @return an empty bulk registration.
\r
5761 function create() {
\r
5762 return new BulkRegistrationImpl();
\r
5764 BulkRegistration.create = create;
\r
5765 })(BulkRegistration = exports.BulkRegistration || (exports.BulkRegistration = {}));
\r
5766 class BulkRegistrationImpl {
\r
5768 this._registrations = [];
\r
5769 this._registered = new Set();
\r
5771 add(type, registerOptions) {
\r
5772 const method = Is.string(type) ? type : type.method;
\r
5773 if (this._registered.has(method)) {
\r
5774 throw new Error(`${method} is already added to this registration`);
\r
5776 const id = UUID.generateUuid();
\r
5777 this._registrations.push({
\r
5780 registerOptions: registerOptions || {}
\r
5782 this._registered.add(method);
\r
5784 asRegistrationParams() {
\r
5786 registrations: this._registrations
\r
5790 var BulkUnregistration;
\r
5791 (function (BulkUnregistration) {
\r
5792 function create() {
\r
5793 return new BulkUnregistrationImpl(undefined, []);
\r
5795 BulkUnregistration.create = create;
\r
5796 })(BulkUnregistration = exports.BulkUnregistration || (exports.BulkUnregistration = {}));
\r
5797 class BulkUnregistrationImpl {
\r
5798 constructor(_connection, unregistrations) {
\r
5799 this._connection = _connection;
\r
5800 this._unregistrations = new Map();
\r
5801 unregistrations.forEach(unregistration => {
\r
5802 this._unregistrations.set(unregistration.method, unregistration);
\r
5805 get isAttached() {
\r
5806 return !!this._connection;
\r
5808 attach(connection) {
\r
5809 this._connection = connection;
\r
5811 add(unregistration) {
\r
5812 this._unregistrations.set(unregistration.method, unregistration);
\r
5815 let unregistrations = [];
\r
5816 for (let unregistration of this._unregistrations.values()) {
\r
5817 unregistrations.push(unregistration);
\r
5820 unregisterations: unregistrations
\r
5822 this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {
\r
5823 this._connection.console.info(`Bulk unregistration failed.`);
\r
5826 disposeSingle(arg) {
\r
5827 const method = Is.string(arg) ? arg : arg.method;
\r
5828 const unregistration = this._unregistrations.get(method);
\r
5829 if (!unregistration) {
\r
5833 unregisterations: [unregistration]
\r
5835 this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => {
\r
5836 this._unregistrations.delete(method);
\r
5838 this._connection.console.info(`Unregistering request handler for ${unregistration.id} failed.`);
\r
5843 class ConnectionLogger {
\r
5846 rawAttach(connection) {
\r
5847 this._rawConnection = connection;
\r
5849 attach(connection) {
\r
5850 this._connection = connection;
\r
5852 get connection() {
\r
5853 if (!this._connection) {
\r
5854 throw new Error('Remote is not attached to a connection yet.');
\r
5856 return this._connection;
\r
5858 fillServerCapabilities(_capabilities) {
\r
5860 initialize(_capabilities) {
\r
5863 this.send(vscode_languageserver_protocol_1.MessageType.Error, message);
\r
5866 this.send(vscode_languageserver_protocol_1.MessageType.Warning, message);
\r
5869 this.send(vscode_languageserver_protocol_1.MessageType.Info, message);
\r
5872 this.send(vscode_languageserver_protocol_1.MessageType.Log, message);
\r
5874 send(type, message) {
\r
5875 if (this._rawConnection) {
\r
5876 this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message });
\r
5880 class RemoteWindowImpl {
\r
5883 attach(connection) {
\r
5884 this._connection = connection;
\r
5886 get connection() {
\r
5887 if (!this._connection) {
\r
5888 throw new Error('Remote is not attached to a connection yet.');
\r
5890 return this._connection;
\r
5892 initialize(_capabilities) {
\r
5894 fillServerCapabilities(_capabilities) {
\r
5896 showErrorMessage(message, ...actions) {
\r
5897 let params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions };
\r
5898 return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
\r
5900 showWarningMessage(message, ...actions) {
\r
5901 let params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions };
\r
5902 return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
\r
5904 showInformationMessage(message, ...actions) {
\r
5905 let params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions };
\r
5906 return this._connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
\r
5909 class RemoteClientImpl {
\r
5910 attach(connection) {
\r
5911 this._connection = connection;
\r
5913 get connection() {
\r
5914 if (!this._connection) {
\r
5915 throw new Error('Remote is not attached to a connection yet.');
\r
5917 return this._connection;
\r
5919 initialize(_capabilities) {
\r
5921 fillServerCapabilities(_capabilities) {
\r
5923 register(typeOrRegistrations, registerOptionsOrType, registerOptions) {
\r
5924 if (typeOrRegistrations instanceof BulkRegistrationImpl) {
\r
5925 return this.registerMany(typeOrRegistrations);
\r
5927 else if (typeOrRegistrations instanceof BulkUnregistrationImpl) {
\r
5928 return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions);
\r
5931 return this.registerSingle2(typeOrRegistrations, registerOptionsOrType);
\r
5934 registerSingle1(unregistration, type, registerOptions) {
\r
5935 const method = Is.string(type) ? type : type.method;
\r
5936 const id = UUID.generateUuid();
\r
5938 registrations: [{ id, method, registerOptions: registerOptions || {} }]
\r
5940 if (!unregistration.isAttached) {
\r
5941 unregistration.attach(this._connection);
\r
5943 return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
\r
5944 unregistration.add({ id: id, method: method });
\r
5945 return unregistration;
\r
5947 this.connection.console.info(`Registering request handler for ${method} failed.`);
\r
5948 return Promise.reject(_error);
\r
5951 registerSingle2(type, registerOptions) {
\r
5952 const method = Is.string(type) ? type : type.method;
\r
5953 const id = UUID.generateUuid();
\r
5955 registrations: [{ id, method, registerOptions: registerOptions || {} }]
\r
5957 return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
\r
5958 return vscode_languageserver_protocol_1.Disposable.create(() => {
\r
5959 this.unregisterSingle(id, method);
\r
5962 this.connection.console.info(`Registering request handler for ${method} failed.`);
\r
5963 return Promise.reject(_error);
\r
5966 unregisterSingle(id, method) {
\r
5968 unregisterations: [{ id, method }]
\r
5970 return this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(undefined, (_error) => {
\r
5971 this.connection.console.info(`Unregistering request handler for ${id} failed.`);
\r
5974 registerMany(registrations) {
\r
5975 let params = registrations.asRegistrationParams();
\r
5976 return this._connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => {
\r
5977 return new BulkUnregistrationImpl(this._connection, params.registrations.map(registration => { return { id: registration.id, method: registration.method }; }));
\r
5979 this.connection.console.info(`Bulk registration failed.`);
\r
5980 return Promise.reject(_error);
\r
5984 class _RemoteWorkspaceImpl {
\r
5987 attach(connection) {
\r
5988 this._connection = connection;
\r
5990 get connection() {
\r
5991 if (!this._connection) {
\r
5992 throw new Error('Remote is not attached to a connection yet.');
\r
5994 return this._connection;
\r
5996 initialize(_capabilities) {
\r
5998 fillServerCapabilities(_capabilities) {
\r
6000 applyEdit(paramOrEdit) {
\r
6001 function isApplyWorkspaceEditParams(value) {
\r
6002 return value && !!value.edit;
\r
6004 let params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit };
\r
6005 return this._connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params);
\r
6008 const RemoteWorkspaceImpl = workspaceFolders_1.WorkspaceFoldersFeature(configuration_1.ConfigurationFeature(_RemoteWorkspaceImpl));
\r
6009 class TracerImpl {
\r
6011 this._trace = vscode_languageserver_protocol_1.Trace.Off;
\r
6013 attach(connection) {
\r
6014 this._connection = connection;
\r
6016 get connection() {
\r
6017 if (!this._connection) {
\r
6018 throw new Error('Remote is not attached to a connection yet.');
\r
6020 return this._connection;
\r
6022 initialize(_capabilities) {
\r
6024 fillServerCapabilities(_capabilities) {
\r
6026 set trace(value) {
\r
6027 this._trace = value;
\r
6029 log(message, verbose) {
\r
6030 if (this._trace === vscode_languageserver_protocol_1.Trace.Off) {
\r
6033 this._connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, {
\r
6035 verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : undefined
\r
6039 class TelemetryImpl {
\r
6042 attach(connection) {
\r
6043 this._connection = connection;
\r
6045 get connection() {
\r
6046 if (!this._connection) {
\r
6047 throw new Error('Remote is not attached to a connection yet.');
\r
6049 return this._connection;
\r
6051 initialize(_capabilities) {
\r
6053 fillServerCapabilities(_capabilities) {
\r
6056 this._connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data);
\r
6059 function combineConsoleFeatures(one, two) {
\r
6060 return function (Base) {
\r
6061 return two(one(Base));
\r
6064 exports.combineConsoleFeatures = combineConsoleFeatures;
\r
6065 function combineTelemetryFeatures(one, two) {
\r
6066 return function (Base) {
\r
6067 return two(one(Base));
\r
6070 exports.combineTelemetryFeatures = combineTelemetryFeatures;
\r
6071 function combineTracerFeatures(one, two) {
\r
6072 return function (Base) {
\r
6073 return two(one(Base));
\r
6076 exports.combineTracerFeatures = combineTracerFeatures;
\r
6077 function combineClientFeatures(one, two) {
\r
6078 return function (Base) {
\r
6079 return two(one(Base));
\r
6082 exports.combineClientFeatures = combineClientFeatures;
\r
6083 function combineWindowFeatures(one, two) {
\r
6084 return function (Base) {
\r
6085 return two(one(Base));
\r
6088 exports.combineWindowFeatures = combineWindowFeatures;
\r
6089 function combineWorkspaceFeatures(one, two) {
\r
6090 return function (Base) {
\r
6091 return two(one(Base));
\r
6094 exports.combineWorkspaceFeatures = combineWorkspaceFeatures;
\r
6095 function combineFeatures(one, two) {
\r
6096 function combine(one, two, func) {
\r
6098 return func(one, two);
\r
6108 __brand: 'features',
\r
6109 console: combine(one.console, two.console, combineConsoleFeatures),
\r
6110 tracer: combine(one.tracer, two.tracer, combineTracerFeatures),
\r
6111 telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures),
\r
6112 client: combine(one.client, two.client, combineClientFeatures),
\r
6113 window: combine(one.window, two.window, combineWindowFeatures),
\r
6114 workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures)
\r
6118 exports.combineFeatures = combineFeatures;
\r
6119 function createConnection(arg1, arg2, arg3, arg4) {
\r
6124 if (arg1 !== void 0 && arg1.__brand === 'features') {
\r
6130 if (vscode_languageserver_protocol_1.ConnectionStrategy.is(arg1)) {
\r
6138 return _createConnection(input, output, strategy, factories);
\r
6140 exports.createConnection = createConnection;
\r
6141 function _createConnection(input, output, strategy, factories) {
\r
6142 if (!input && !output && process.argv.length > 2) {
\r
6143 let port = void 0;
\r
6144 let pipeName = void 0;
\r
6145 let argv = process.argv.slice(2);
\r
6146 for (let i = 0; i < argv.length; i++) {
\r
6147 let arg = argv[i];
\r
6148 if (arg === '--node-ipc') {
\r
6149 input = new vscode_languageserver_protocol_1.IPCMessageReader(process);
\r
6150 output = new vscode_languageserver_protocol_1.IPCMessageWriter(process);
\r
6153 else if (arg === '--stdio') {
\r
6154 input = process.stdin;
\r
6155 output = process.stdout;
\r
6158 else if (arg === '--socket') {
\r
6159 port = parseInt(argv[i + 1]);
\r
6162 else if (arg === '--pipe') {
\r
6163 pipeName = argv[i + 1];
\r
6167 var args = arg.split('=');
\r
6168 if (args[0] === '--socket') {
\r
6169 port = parseInt(args[1]);
\r
6172 else if (args[0] === '--pipe') {
\r
6173 pipeName = args[1];
\r
6179 let transport = vscode_languageserver_protocol_1.createServerSocketTransport(port);
\r
6180 input = transport[0];
\r
6181 output = transport[1];
\r
6183 else if (pipeName) {
\r
6184 let transport = vscode_languageserver_protocol_1.createServerPipeTransport(pipeName);
\r
6185 input = transport[0];
\r
6186 output = transport[1];
\r
6189 var commandLineMessage = "Use arguments of createConnection or set command line parameters: '--node-ipc', '--stdio' or '--socket={number}'";
\r
6191 throw new Error("Connection input stream is not set. " + commandLineMessage);
\r
6194 throw new Error("Connection output stream is not set. " + commandLineMessage);
\r
6196 // Backwards compatibility
\r
6197 if (Is.func(input.read) && Is.func(input.on)) {
\r
6198 let inputStream = input;
\r
6199 inputStream.on('end', () => {
\r
6200 process.exit(shutdownReceived ? 0 : 1);
\r
6202 inputStream.on('close', () => {
\r
6203 process.exit(shutdownReceived ? 0 : 1);
\r
6206 const logger = (factories && factories.console ? new (factories.console(ConnectionLogger))() : new ConnectionLogger());
\r
6207 const connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger, strategy);
\r
6208 logger.rawAttach(connection);
\r
6209 const tracer = (factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl());
\r
6210 const telemetry = (factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl());
\r
6211 const client = (factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl());
\r
6212 const remoteWindow = (factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl());
\r
6213 const workspace = (factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl());
\r
6214 const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace];
\r
6215 function asThenable(value) {
\r
6216 if (Is.thenable(value)) {
\r
6220 return Promise.resolve(value);
\r
6223 let shutdownHandler = undefined;
\r
6224 let initializeHandler = undefined;
\r
6225 let exitHandler = undefined;
\r
6226 let protocolConnection = {
\r
6227 listen: () => connection.listen(),
\r
6228 sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params),
\r
6229 onRequest: (type, handler) => connection.onRequest(type, handler),
\r
6230 sendNotification: (type, param) => {
\r
6231 const method = Is.string(type) ? type : type.method;
\r
6232 if (arguments.length === 1) {
\r
6233 connection.sendNotification(method);
\r
6236 connection.sendNotification(method, param);
\r
6239 onNotification: (type, handler) => connection.onNotification(type, handler),
\r
6240 onInitialize: (handler) => initializeHandler = handler,
\r
6241 onInitialized: (handler) => connection.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler),
\r
6242 onShutdown: (handler) => shutdownHandler = handler,
\r
6243 onExit: (handler) => exitHandler = handler,
\r
6244 get console() { return logger; },
\r
6245 get telemetry() { return telemetry; },
\r
6246 get tracer() { return tracer; },
\r
6247 get client() { return client; },
\r
6248 get window() { return remoteWindow; },
\r
6249 get workspace() { return workspace; },
\r
6250 onDidChangeConfiguration: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler),
\r
6251 onDidChangeWatchedFiles: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler),
\r
6252 __textDocumentSync: undefined,
\r
6253 onDidOpenTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler),
\r
6254 onDidChangeTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler),
\r
6255 onDidCloseTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler),
\r
6256 onWillSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler),
\r
6257 onWillSaveTextDocumentWaitUntil: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler),
\r
6258 onDidSaveTextDocument: (handler) => connection.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler),
\r
6259 sendDiagnostics: (params) => connection.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params),
\r
6260 onHover: (handler) => connection.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, handler),
\r
6261 onCompletion: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, handler),
\r
6262 onCompletionResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler),
\r
6263 onSignatureHelp: (handler) => connection.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, handler),
\r
6264 onDeclaration: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, handler),
\r
6265 onDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, handler),
\r
6266 onTypeDefinition: (handler) => connection.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, handler),
\r
6267 onImplementation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, handler),
\r
6268 onReferences: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, handler),
\r
6269 onDocumentHighlight: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, handler),
\r
6270 onDocumentSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, handler),
\r
6271 onWorkspaceSymbol: (handler) => connection.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, handler),
\r
6272 onCodeAction: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, handler),
\r
6273 onCodeLens: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, handler),
\r
6274 onCodeLensResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, handler),
\r
6275 onDocumentFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, handler),
\r
6276 onDocumentRangeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, handler),
\r
6277 onDocumentOnTypeFormatting: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, handler),
\r
6278 onRenameRequest: (handler) => connection.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, handler),
\r
6279 onPrepareRename: (handler) => connection.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, handler),
\r
6280 onDocumentLinks: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, handler),
\r
6281 onDocumentLinkResolve: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, handler),
\r
6282 onDocumentColor: (handler) => connection.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, handler),
\r
6283 onColorPresentation: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, handler),
\r
6284 onFoldingRanges: (handler) => connection.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, handler),
\r
6285 onExecuteCommand: (handler) => connection.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, handler),
\r
6286 dispose: () => connection.dispose()
\r
6288 for (let remote of allRemotes) {
\r
6289 remote.attach(protocolConnection);
\r
6291 connection.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => {
\r
6292 const processId = params.processId;
\r
6293 if (Is.number(processId) && exitTimer === void 0) {
\r
6294 // We received a parent process id. Set up a timer to periodically check
\r
6295 // if the parent is still alive.
\r
6296 setInterval(() => {
\r
6298 process.kill(processId, 0);
\r
6301 // Parent process doesn't exist anymore. Exit the server.
\r
6302 process.exit(shutdownReceived ? 0 : 1);
\r
6306 if (Is.string(params.trace)) {
\r
6307 tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace);
\r
6309 for (let remote of allRemotes) {
\r
6310 remote.initialize(params.capabilities);
\r
6312 if (initializeHandler) {
\r
6313 let result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token);
\r
6314 return asThenable(result).then((value) => {
\r
6315 if (value instanceof vscode_languageserver_protocol_1.ResponseError) {
\r
6318 let result = value;
\r
6320 result = { capabilities: {} };
\r
6322 let capabilities = result.capabilities;
\r
6323 if (!capabilities) {
\r
6324 capabilities = {};
\r
6325 result.capabilities = capabilities;
\r
6327 if (capabilities.textDocumentSync === void 0 || capabilities.textDocumentSync === null) {
\r
6328 capabilities.textDocumentSync = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
\r
6330 else if (!Is.number(capabilities.textDocumentSync) && !Is.number(capabilities.textDocumentSync.change)) {
\r
6331 capabilities.textDocumentSync.change = Is.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
\r
6333 for (let remote of allRemotes) {
\r
6334 remote.fillServerCapabilities(capabilities);
\r
6340 let result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } };
\r
6341 for (let remote of allRemotes) {
\r
6342 remote.fillServerCapabilities(result.capabilities);
\r
6347 connection.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => {
\r
6348 shutdownReceived = true;
\r
6349 if (shutdownHandler) {
\r
6350 return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token);
\r
6356 connection.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => {
\r
6358 if (exitHandler) {
\r
6363 if (shutdownReceived) {
\r
6371 connection.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => {
\r
6372 tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value);
\r
6374 return protocolConnection;
\r
6376 // Export the protocol currently in proposed state.
\r
6377 const proposed_progress_1 = __webpack_require__(48);
\r
6378 var ProposedFeatures;
\r
6379 (function (ProposedFeatures) {
\r
6380 ProposedFeatures.all = {
\r
6381 __brand: 'features',
\r
6382 window: proposed_progress_1.ProgressFeature
\r
6384 })(ProposedFeatures = exports.ProposedFeatures || (exports.ProposedFeatures = {}));
\r
6389 /***/ (function(module, exports, __webpack_require__) {
6392 /* --------------------------------------------------------------------------------------------
\r
6393 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
6394 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
6395 * ------------------------------------------------------------------------------------------ */
\r
6397 Object.defineProperty(exports, "__esModule", { value: true });
\r
6398 const vscode_languageserver_protocol_1 = __webpack_require__(3);
\r
6399 const Is = __webpack_require__(36);
\r
6400 exports.ConfigurationFeature = (Base) => {
\r
6401 return class extends Base {
\r
6402 getConfiguration(arg) {
\r
6404 return this._getConfiguration({});
\r
6406 else if (Is.string(arg)) {
\r
6407 return this._getConfiguration({ section: arg });
\r
6410 return this._getConfiguration(arg);
\r
6413 _getConfiguration(arg) {
\r
6415 items: Array.isArray(arg) ? arg : [arg]
\r
6417 return this.connection.sendRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, params).then((result) => {
\r
6418 return Array.isArray(arg) ? result : result[0];
\r
6427 /***/ (function(module, exports, __webpack_require__) {
6430 /* --------------------------------------------------------------------------------------------
\r
6431 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
6432 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
6433 * ------------------------------------------------------------------------------------------ */
\r
6435 Object.defineProperty(exports, "__esModule", { value: true });
\r
6436 function boolean(value) {
\r
6437 return value === true || value === false;
\r
6439 exports.boolean = boolean;
\r
6440 function string(value) {
\r
6441 return typeof value === 'string' || value instanceof String;
\r
6443 exports.string = string;
\r
6444 function number(value) {
\r
6445 return typeof value === 'number' || value instanceof Number;
\r
6447 exports.number = number;
\r
6448 function error(value) {
\r
6449 return value instanceof Error;
\r
6451 exports.error = error;
\r
6452 function func(value) {
\r
6453 return typeof value === 'function';
\r
6455 exports.func = func;
\r
6456 function array(value) {
\r
6457 return Array.isArray(value);
\r
6459 exports.array = array;
\r
6460 function stringArray(value) {
\r
6461 return array(value) && value.every(elem => string(elem));
\r
6463 exports.stringArray = stringArray;
\r
6464 function typedArray(value, check) {
\r
6465 return Array.isArray(value) && value.every(check);
\r
6467 exports.typedArray = typedArray;
\r
6468 function thenable(value) {
\r
6469 return value && func(value.then);
\r
6471 exports.thenable = thenable;
\r
6476 /***/ (function(module, exports, __webpack_require__) {
6479 /* --------------------------------------------------------------------------------------------
\r
6480 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
6481 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
6482 * ------------------------------------------------------------------------------------------ */
\r
6484 Object.defineProperty(exports, "__esModule", { value: true });
\r
6485 const vscode_languageserver_protocol_1 = __webpack_require__(3);
\r
6486 exports.WorkspaceFoldersFeature = (Base) => {
\r
6487 return class extends Base {
\r
6488 initialize(capabilities) {
\r
6489 let workspaceCapabilities = capabilities.workspace;
\r
6490 if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) {
\r
6491 this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter();
\r
6492 this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, (params) => {
\r
6493 this._onDidChangeWorkspaceFolders.fire(params.event);
\r
6497 getWorkspaceFolders() {
\r
6498 return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type);
\r
6500 get onDidChangeWorkspaceFolders() {
\r
6501 if (!this._onDidChangeWorkspaceFolders) {
\r
6502 throw new Error('Client doesn\'t support sending workspace folder change events.');
\r
6504 if (!this._unregistration) {
\r
6505 this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type);
\r
6507 return this._onDidChangeWorkspaceFolders.event;
\r
6515 /***/ (function(module, exports, __webpack_require__) {
6518 /*---------------------------------------------------------------------------------------------
\r
6519 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
6520 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
6521 *--------------------------------------------------------------------------------------------*/
\r
6523 Object.defineProperty(exports, "__esModule", { value: true });
\r
6525 constructor(_value) {
\r
6526 this._value = _value;
\r
6530 return this._value;
\r
6533 return this.asHex() === other.asHex();
\r
6536 class V4UUID extends ValueUUID {
\r
6539 V4UUID._randomHex(),
\r
6540 V4UUID._randomHex(),
\r
6541 V4UUID._randomHex(),
\r
6542 V4UUID._randomHex(),
\r
6543 V4UUID._randomHex(),
\r
6544 V4UUID._randomHex(),
\r
6545 V4UUID._randomHex(),
\r
6546 V4UUID._randomHex(),
\r
6548 V4UUID._randomHex(),
\r
6549 V4UUID._randomHex(),
\r
6550 V4UUID._randomHex(),
\r
6551 V4UUID._randomHex(),
\r
6554 V4UUID._randomHex(),
\r
6555 V4UUID._randomHex(),
\r
6556 V4UUID._randomHex(),
\r
6558 V4UUID._oneOf(V4UUID._timeHighBits),
\r
6559 V4UUID._randomHex(),
\r
6560 V4UUID._randomHex(),
\r
6561 V4UUID._randomHex(),
\r
6563 V4UUID._randomHex(),
\r
6564 V4UUID._randomHex(),
\r
6565 V4UUID._randomHex(),
\r
6566 V4UUID._randomHex(),
\r
6567 V4UUID._randomHex(),
\r
6568 V4UUID._randomHex(),
\r
6569 V4UUID._randomHex(),
\r
6570 V4UUID._randomHex(),
\r
6571 V4UUID._randomHex(),
\r
6572 V4UUID._randomHex(),
\r
6573 V4UUID._randomHex(),
\r
6574 V4UUID._randomHex(),
\r
6577 static _oneOf(array) {
\r
6578 return array[Math.floor(array.length * Math.random())];
\r
6580 static _randomHex() {
\r
6581 return V4UUID._oneOf(V4UUID._chars);
\r
6584 V4UUID._chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
\r
6585 V4UUID._timeHighBits = ['8', '9', 'a', 'b'];
\r
6587 * An empty UUID that contains only zeros.
\r
6589 exports.empty = new ValueUUID('00000000-0000-0000-0000-000000000000');
\r
6591 return new V4UUID();
\r
6594 const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
\r
6595 function isUUID(value) {
\r
6596 return _UUIDPattern.test(value);
\r
6598 exports.isUUID = isUUID;
\r
6600 * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
\r
6601 * @param value A uuid string.
\r
6603 function parse(value) {
\r
6604 if (!isUUID(value)) {
\r
6605 throw new Error('invalid uuid');
\r
6607 return new ValueUUID(value);
\r
6609 exports.parse = parse;
\r
6610 function generateUuid() {
\r
6611 return v4().asHex();
\r
6613 exports.generateUuid = generateUuid;
\r
6618 /***/ (function(module, exports, __webpack_require__) {
6621 /* WEBPACK VAR INJECTION */(function(__filename) {/* --------------------------------------------------------------------------------------------
\r
6622 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
6623 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
6624 * ------------------------------------------------------------------------------------------ */
\r
6626 Object.defineProperty(exports, "__esModule", { value: true });
\r
6627 const url = __webpack_require__(40);
\r
6628 const path = __webpack_require__(1);
\r
6629 const fs = __webpack_require__(2);
\r
6630 const child_process_1 = __webpack_require__(41);
\r
6632 * @deprecated Use the `vscode-uri` npm module which provides a more
\r
6633 * complete implementation of handling VS Code URIs.
\r
6635 function uriToFilePath(uri) {
\r
6636 let parsed = url.parse(uri);
\r
6637 if (parsed.protocol !== 'file:' || !parsed.path) {
\r
6640 let segments = parsed.path.split('/');
\r
6641 for (var i = 0, len = segments.length; i < len; i++) {
\r
6642 segments[i] = decodeURIComponent(segments[i]);
\r
6644 if (process.platform === 'win32' && segments.length > 1) {
\r
6645 let first = segments[0];
\r
6646 let second = segments[1];
\r
6647 // Do we have a drive letter and we started with a / which is the
\r
6648 // case if the first segement is empty (see split above)
\r
6649 if (first.length === 0 && second.length > 1 && second[1] === ':') {
\r
6650 // Remove first slash
\r
6654 return path.normalize(segments.join('/'));
\r
6656 exports.uriToFilePath = uriToFilePath;
\r
6657 function isWindows() {
\r
6658 return process.platform === 'win32';
\r
6660 function resolve(moduleName, nodePath, cwd, tracer) {
\r
6661 const nodePathKey = 'NODE_PATH';
\r
6663 "var p = process;",
\r
6664 "p.on('message',function(m){",
\r
6668 "else if(m.c==='rs'){",
\r
6670 "var r=require.resolve(m.a);",
\r
6671 "p.send({c:'r',s:true,r:r});",
\r
6674 "p.send({c:'r',s:false});",
\r
6679 return new Promise((resolve, reject) => {
\r
6680 let env = process.env;
\r
6681 let newEnv = Object.create(null);
\r
6682 Object.keys(env).forEach(key => newEnv[key] = env[key]);
\r
6684 if (newEnv[nodePathKey]) {
\r
6685 newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];
\r
6688 newEnv[nodePathKey] = nodePath;
\r
6691 tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);
\r
6694 newEnv['ELECTRON_RUN_AS_NODE'] = '1';
\r
6696 let cp = child_process_1.fork('', [], {
\r
6699 execArgv: ['-e', app]
\r
6701 if (cp.pid === void 0) {
\r
6702 reject(new Error(`Starting process to resolve node module ${moduleName} failed`));
\r
6705 cp.on('error', (error) => {
\r
6708 cp.on('message', (message) => {
\r
6709 if (message.c === 'r') {
\r
6710 cp.send({ c: 'e' });
\r
6712 resolve(message.r);
\r
6715 reject(new Error(`Failed to resolve module: ${moduleName}`));
\r
6730 exports.resolve = resolve;
\r
6731 function resolveGlobalNodePath(tracer) {
\r
6732 let npmCommand = 'npm';
\r
6736 if (isWindows()) {
\r
6737 npmCommand = 'npm.cmd';
\r
6738 options.shell = true;
\r
6740 let handler = () => { };
\r
6742 process.on('SIGPIPE', handler);
\r
6743 let stdout = child_process_1.spawnSync(npmCommand, ['config', 'get', 'prefix'], options).stdout;
\r
6746 tracer(`'npm config get prefix' didn't return a value.`);
\r
6750 let prefix = stdout.trim();
\r
6752 tracer(`'npm config get prefix' value is: ${prefix}`);
\r
6754 if (prefix.length > 0) {
\r
6755 if (isWindows()) {
\r
6756 return path.join(prefix, 'node_modules');
\r
6759 return path.join(prefix, 'lib', 'node_modules');
\r
6768 process.removeListener('SIGPIPE', handler);
\r
6771 exports.resolveGlobalNodePath = resolveGlobalNodePath;
\r
6772 function resolveGlobalYarnPath(tracer) {
\r
6773 let yarnCommand = 'yarn';
\r
6777 if (isWindows()) {
\r
6778 yarnCommand = 'yarn.cmd';
\r
6779 options.shell = true;
\r
6781 let handler = () => { };
\r
6783 process.on('SIGPIPE', handler);
\r
6784 let results = child_process_1.spawnSync(yarnCommand, ['global', 'dir', '--json'], options);
\r
6785 let stdout = results.stdout;
\r
6788 tracer(`'yarn global dir' didn't return a value.`);
\r
6789 if (results.stderr) {
\r
6790 tracer(results.stderr);
\r
6795 let lines = stdout.trim().split(/\r?\n/);
\r
6796 for (let line of lines) {
\r
6798 let yarn = JSON.parse(line);
\r
6799 if (yarn.type === 'log') {
\r
6800 return path.join(yarn.data, 'node_modules');
\r
6804 // Do nothing. Ignore the line
\r
6813 process.removeListener('SIGPIPE', handler);
\r
6816 exports.resolveGlobalYarnPath = resolveGlobalYarnPath;
\r
6818 (function (FileSystem) {
\r
6819 let _isCaseSensitive = undefined;
\r
6820 function isCaseSensitive() {
\r
6821 if (_isCaseSensitive !== void 0) {
\r
6822 return _isCaseSensitive;
\r
6824 if (process.platform === 'win32') {
\r
6825 _isCaseSensitive = false;
\r
6828 // convert current file name to upper case / lower case and check if file exists
\r
6829 // (guards against cases when name is already all uppercase or lowercase)
\r
6830 _isCaseSensitive = !fs.existsSync(__filename.toUpperCase()) || !fs.existsSync(__filename.toLowerCase());
\r
6832 return _isCaseSensitive;
\r
6834 FileSystem.isCaseSensitive = isCaseSensitive;
\r
6835 function isParent(parent, child) {
\r
6836 if (isCaseSensitive()) {
\r
6837 return path.normalize(child).indexOf(path.normalize(parent)) === 0;
\r
6840 return path.normalize(child).toLowerCase().indexOf(path.normalize(parent).toLowerCase()) == 0;
\r
6843 FileSystem.isParent = isParent;
\r
6844 })(FileSystem = exports.FileSystem || (exports.FileSystem = {}));
\r
6845 function resolveModulePath(workspaceRoot, moduleName, nodePath, tracer) {
\r
6847 if (!path.isAbsolute(nodePath)) {
\r
6848 nodePath = path.join(workspaceRoot, nodePath);
\r
6850 return resolve(moduleName, nodePath, nodePath, tracer).then((value) => {
\r
6851 if (FileSystem.isParent(nodePath, value)) {
\r
6855 return Promise.reject(new Error(`Failed to load ${moduleName} from node path location.`));
\r
6857 }).then(undefined, (_error) => {
\r
6858 return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
\r
6862 return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
\r
6865 exports.resolveModulePath = resolveModulePath;
\r
6867 /* WEBPACK VAR INJECTION */}.call(this, "/index.js"))
6871 /***/ (function(module, exports) {
6873 module.exports = require("url");
6877 /***/ (function(module, exports) {
6879 module.exports = require("child_process");
6883 /***/ (function(module, exports, __webpack_require__) {
6887 function __export(m) {
6888 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
6890 Object.defineProperty(exports, "__esModule", { value: true });
6891 __export(__webpack_require__(43));
6892 __export(__webpack_require__(46));
6897 /***/ (function(module, exports, __webpack_require__) {
6901 /*---------------------------------------------------------------------------------------------
6902 * Copyright (c) Microsoft Corporation. All rights reserved.
6903 * Licensed under the MIT License. See License.txt in the project root for license information.
6904 *--------------------------------------------------------------------------------------------*/
6905 Object.defineProperty(exports, "__esModule", { value: true });
6906 const position_1 = __webpack_require__(44);
6907 const rbTreeBase_1 = __webpack_require__(45);
6908 // const lfRegex = new RegExp(/\r\n|\r|\n/g);
6909 exports.AverageBufferSize = 65535;
6910 function createUintArray(arr) {
6912 if (arr[arr.length - 1] < 65536) {
6913 r = new Uint16Array(arr.length);
6916 r = new Uint32Array(arr.length);
6921 exports.createUintArray = createUintArray;
6923 constructor(lineStarts, cr, lf, crlf, isBasicASCII) {
6924 this.lineStarts = lineStarts;
6928 this.isBasicASCII = isBasicASCII;
6931 exports.LineStarts = LineStarts;
6932 function createLineStartsFast(str, readonly = true) {
6933 let r = [0], rLength = 1;
6934 for (let i = 0, len = str.length; i < len; i++) {
6935 const chr = str.charCodeAt(i);
6936 if (chr === 13 /* CarriageReturn */) {
6937 if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
6939 r[rLength++] = i + 2;
6944 r[rLength++] = i + 1;
6947 else if (chr === 10 /* LineFeed */) {
6948 r[rLength++] = i + 1;
6952 return createUintArray(r);
6958 exports.createLineStartsFast = createLineStartsFast;
6959 function createLineStarts(r, str) {
6963 let cr = 0, lf = 0, crlf = 0;
6964 let isBasicASCII = true;
6965 for (let i = 0, len = str.length; i < len; i++) {
6966 const chr = str.charCodeAt(i);
6967 if (chr === 13 /* CarriageReturn */) {
6968 if (i + 1 < len && str.charCodeAt(i + 1) === 10 /* LineFeed */) {
6971 r[rLength++] = i + 2;
6977 r[rLength++] = i + 1;
6980 else if (chr === 10 /* LineFeed */) {
6982 r[rLength++] = i + 1;
6986 if (chr !== 9 /* Tab */ && (chr < 32 || chr > 126)) {
6987 isBasicASCII = false;
6992 const result = new LineStarts(createUintArray(r), cr, lf, crlf, isBasicASCII);
6996 exports.createLineStarts = createLineStarts;
6998 constructor(bufferIndex, start, end, lineFeedCnt, length) {
6999 this.bufferIndex = bufferIndex;
7002 this.lineFeedCnt = lineFeedCnt;
7003 this.length = length;
7006 exports.Piece = Piece;
7007 class StringBuffer {
7008 constructor(buffer, lineStarts) {
7009 this.buffer = buffer;
7010 this.lineStarts = lineStarts;
7013 exports.StringBuffer = StringBuffer;
7015 * Readonly snapshot for piece tree.
7016 * In a real multiple thread environment, to make snapshot reading always work correctly, we need to
7017 * 1. Make TreeNode.piece immutable, then reading and writing can run in parallel.
7018 * 2. TreeNode/Buffers normalization should not happen during snapshot reading.
7020 class PieceTreeSnapshot {
7021 constructor(tree, BOM) {
7026 if (tree.root !== rbTreeBase_1.SENTINEL) {
7027 tree.iterate(tree.root, node => {
7028 if (node !== rbTreeBase_1.SENTINEL) {
7029 this._pieces.push(node.piece);
7036 if (this._pieces.length === 0) {
7037 if (this._index === 0) {
7045 if (this._index > this._pieces.length - 1) {
7048 if (this._index === 0) {
7049 return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
7051 return this._tree.getPieceContent(this._pieces[this._index++]);
7054 class PieceTreeSearchCache {
7055 constructor(limit) {
7056 this._limit = limit;
7060 for (let i = this._cache.length - 1; i >= 0; i--) {
7061 let nodePos = this._cache[i];
7062 if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
7069 for (let i = this._cache.length - 1; i >= 0; i--) {
7070 let nodePos = this._cache[i];
7071 if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
7078 if (this._cache.length >= this._limit) {
7079 this._cache.shift();
7081 this._cache.push(nodePosition);
7084 let hasInvalidVal = false;
7085 let tmp = this._cache;
7086 for (let i = 0; i < tmp.length; i++) {
7087 let nodePos = tmp[i];
7088 if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
7090 hasInvalidVal = true;
7094 if (hasInvalidVal) {
7096 for (const entry of tmp) {
7097 if (entry !== null) {
7101 this._cache = newArr;
7105 class PieceTreeBase {
7106 constructor(chunks, eol, eolNormalized) {
7107 this.create(chunks, eol, eolNormalized);
7109 create(chunks, eol, eolNormalized) {
7111 new StringBuffer('', [0])
7113 this._lastChangeBufferPos = { line: 0, column: 0 };
7114 this.root = rbTreeBase_1.SENTINEL;
7118 this._EOLLength = eol.length;
7119 this._EOLNormalized = eolNormalized;
7120 let lastNode = null;
7121 for (let i = 0, len = chunks.length; i < len; i++) {
7122 if (chunks[i].buffer.length > 0) {
7123 if (!chunks[i].lineStarts) {
7124 chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);
7126 let piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length);
7127 this._buffers.push(chunks[i]);
7128 lastNode = this.rbInsertRight(lastNode, piece);
7131 this._searchCache = new PieceTreeSearchCache(1);
7132 this._lastVisitedLine = { lineNumber: 0, value: '' };
7133 this.computeBufferMetadata();
7136 let averageBufferSize = exports.AverageBufferSize;
7137 let min = averageBufferSize - Math.floor(averageBufferSize / 3);
7140 let tempChunkLen = 0;
7142 this.iterate(this.root, node => {
7143 let str = this.getNodeContent(node);
7144 let len = str.length;
7145 if (tempChunkLen <= min || tempChunkLen + len < max) {
7147 tempChunkLen += len;
7151 let text = tempChunk.replace(/\r\n|\r|\n/g, eol);
7152 chunks.push(new StringBuffer(text, createLineStartsFast(text)));
7157 if (tempChunkLen > 0) {
7158 let text = tempChunk.replace(/\r\n|\r|\n/g, eol);
7159 chunks.push(new StringBuffer(text, createLineStartsFast(text)));
7161 this.create(chunks, eol, true);
7163 // #region Buffer API
7169 this._EOLLength = this._EOL.length;
7170 this.normalizeEOL(newEOL);
7172 createSnapshot(BOM) {
7173 return new PieceTreeSnapshot(this, BOM);
7176 if (this.getLength() !== other.getLength()) {
7179 if (this.getLineCount() !== other.getLineCount()) {
7183 let ret = this.iterate(this.root, node => {
7184 if (node === rbTreeBase_1.SENTINEL) {
7187 let str = this.getNodeContent(node);
7188 let len = str.length;
7189 let startPosition = other.nodeAt(offset);
7190 let endPosition = other.nodeAt(offset + len);
7191 let val = other.getValueInRange2(startPosition, endPosition);
7196 getOffsetAt(lineNumber, column) {
7197 let leftLen = 0; // inorder
7199 while (x !== rbTreeBase_1.SENTINEL) {
7200 if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left + 1 >= lineNumber) {
7203 else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
7204 leftLen += x.size_left;
7206 let accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
7207 return leftLen += accumualtedValInCurrentIndex + column - 1;
7210 lineNumber -= x.lf_left + x.piece.lineFeedCnt;
7211 leftLen += x.size_left + x.piece.length;
7217 getPositionAt(offset) {
7218 offset = Math.floor(offset);
7219 offset = Math.max(0, offset);
7222 let originalOffset = offset;
7223 while (x !== rbTreeBase_1.SENTINEL) {
7224 if (x.size_left !== 0 && x.size_left >= offset) {
7227 else if (x.size_left + x.piece.length >= offset) {
7228 let out = this.getIndexOf(x, offset - x.size_left);
7229 lfCnt += x.lf_left + out.index;
7230 if (out.index === 0) {
7231 let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
7232 let column = originalOffset - lineStartOffset;
7233 return new position_1.Position(lfCnt + 1, column + 1);
7235 return new position_1.Position(lfCnt + 1, out.remainder + 1);
7238 offset -= x.size_left + x.piece.length;
7239 lfCnt += x.lf_left + x.piece.lineFeedCnt;
7240 if (x.right === rbTreeBase_1.SENTINEL) {
7242 let lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
7243 let column = originalOffset - offset - lineStartOffset;
7244 return new position_1.Position(lfCnt + 1, column + 1);
7251 return new position_1.Position(1, 1);
7253 getValueInRange(range, eol) {
7254 if (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn) {
7257 let startPosition = this.nodeAt2(range.startLineNumber, range.startColumn);
7258 let endPosition = this.nodeAt2(range.endLineNumber, range.endColumn);
7259 let value = this.getValueInRange2(startPosition, endPosition);
7261 if (eol !== this._EOL || !this._EOLNormalized) {
7262 return value.replace(/\r\n|\r|\n/g, eol);
7264 if (eol === this.getEOL() && this._EOLNormalized) {
7265 if (eol === '\r\n') {
7269 return value.replace(/\r\n|\r|\n/g, eol);
7273 getValueInRange2(startPosition, endPosition) {
7274 if (startPosition.node === endPosition.node) {
7275 let node = startPosition.node;
7276 let buffer = this._buffers[node.piece.bufferIndex].buffer;
7277 let startOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start);
7278 return buffer.substring(startOffset + startPosition.remainder, startOffset + endPosition.remainder);
7280 let x = startPosition.node;
7281 let buffer = this._buffers[x.piece.bufferIndex].buffer;
7282 let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
7283 let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
7285 while (x !== rbTreeBase_1.SENTINEL) {
7286 let buffer = this._buffers[x.piece.bufferIndex].buffer;
7287 let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
7288 if (x === endPosition.node) {
7289 ret += buffer.substring(startOffset, startOffset + endPosition.remainder);
7293 ret += buffer.substr(startOffset, x.piece.length);
7300 return this.getContentOfSubTree(this.root).split(/\r\n|\r|\n/);
7303 return this._length;
7306 return this._lineCnt;
7309 * @param lineNumber 1 based
7311 getLineContent(lineNumber) {
7312 if (this._lastVisitedLine.lineNumber === lineNumber) {
7313 return this._lastVisitedLine.value;
7315 this._lastVisitedLine.lineNumber = lineNumber;
7316 if (lineNumber === this._lineCnt) {
7317 this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
7319 else if (this._EOLNormalized) {
7320 this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
7323 this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, '');
7325 return this._lastVisitedLine.value;
7327 getLineCharCode(lineNumber, index) {
7328 let nodePos = this.nodeAt2(lineNumber, index + 1);
7329 if (nodePos.remainder === nodePos.node.piece.length) {
7330 // the char we want to fetch is at the head of next node.
7331 let matchingNode = nodePos.node.next();
7332 if (!matchingNode) {
7335 let buffer = this._buffers[matchingNode.piece.bufferIndex];
7336 let startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
7337 return buffer.buffer.charCodeAt(startOffset);
7340 let buffer = this._buffers[nodePos.node.piece.bufferIndex];
7341 let startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
7342 let targetOffset = startOffset + nodePos.remainder;
7343 return buffer.buffer.charCodeAt(targetOffset);
7346 getLineLength(lineNumber) {
7347 if (lineNumber === this.getLineCount()) {
7348 let startOffset = this.getOffsetAt(lineNumber, 1);
7349 return this.getLength() - startOffset;
7351 return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
7354 // #region Piece Table
7355 insert(offset, value, eolNormalized = false) {
7356 this._EOLNormalized = this._EOLNormalized && eolNormalized;
7357 this._lastVisitedLine.lineNumber = 0;
7358 this._lastVisitedLine.value = '';
7359 if (this.root !== rbTreeBase_1.SENTINEL) {
7360 let { node, remainder, nodeStartOffset } = this.nodeAt(offset);
7361 let piece = node.piece;
7362 let bufferIndex = piece.bufferIndex;
7363 let insertPosInBuffer = this.positionInBuffer(node, remainder);
7364 if (node.piece.bufferIndex === 0 &&
7365 piece.end.line === this._lastChangeBufferPos.line &&
7366 piece.end.column === this._lastChangeBufferPos.column &&
7367 (nodeStartOffset + piece.length === offset) &&
7368 value.length < exports.AverageBufferSize) {
7370 this.appendToNode(node, value);
7371 this.computeBufferMetadata();
7374 if (nodeStartOffset === offset) {
7375 this.insertContentToNodeLeft(value, node);
7376 this._searchCache.valdiate(offset);
7378 else if (nodeStartOffset + node.piece.length > offset) {
7379 // we are inserting into the middle of a node.
7380 let nodesToDel = [];
7381 let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
7382 if (this.shouldCheckCRLF() && this.endWithCR(value)) {
7383 let headOfRight = this.nodeCharCodeAt(node, remainder);
7384 if (headOfRight === 10 /** \n */) {
7385 let newStart = { line: newRightPiece.start.line + 1, column: 0 };
7386 newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
7390 // reuse node for content before insertion point.
7391 if (this.shouldCheckCRLF() && this.startWithLF(value)) {
7392 let tailOfLeft = this.nodeCharCodeAt(node, remainder - 1);
7393 if (tailOfLeft === 13 /** \r */) {
7394 let previousPos = this.positionInBuffer(node, remainder - 1);
7395 this.deleteNodeTail(node, previousPos);
7396 value = '\r' + value;
7397 if (node.piece.length === 0) {
7398 nodesToDel.push(node);
7402 this.deleteNodeTail(node, insertPosInBuffer);
7406 this.deleteNodeTail(node, insertPosInBuffer);
7408 let newPieces = this.createNewPieces(value);
7409 if (newRightPiece.length > 0) {
7410 this.rbInsertRight(node, newRightPiece);
7413 for (let k = 0; k < newPieces.length; k++) {
7414 tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
7416 this.deleteNodes(nodesToDel);
7419 this.insertContentToNodeRight(value, node);
7424 let pieces = this.createNewPieces(value);
7425 let node = this.rbInsertLeft(null, pieces[0]);
7426 for (let k = 1; k < pieces.length; k++) {
7427 node = this.rbInsertRight(node, pieces[k]);
7430 // todo, this is too brutal. Total line feed count should be updated the same way as lf_left.
7431 this.computeBufferMetadata();
7433 delete(offset, cnt) {
7434 this._lastVisitedLine.lineNumber = 0;
7435 this._lastVisitedLine.value = '';
7436 if (cnt <= 0 || this.root === rbTreeBase_1.SENTINEL) {
7439 let startPosition = this.nodeAt(offset);
7440 let endPosition = this.nodeAt(offset + cnt);
7441 let startNode = startPosition.node;
7442 let endNode = endPosition.node;
7443 if (startNode === endNode) {
7444 let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
7445 let endSplitPosInBuffer = this.positionInBuffer(startNode, endPosition.remainder);
7446 if (startPosition.nodeStartOffset === offset) {
7447 if (cnt === startNode.piece.length) { // delete node
7448 let next = startNode.next();
7449 rbTreeBase_1.rbDelete(this, startNode);
7450 this.validateCRLFWithPrevNode(next);
7451 this.computeBufferMetadata();
7454 this.deleteNodeHead(startNode, endSplitPosInBuffer);
7455 this._searchCache.valdiate(offset);
7456 this.validateCRLFWithPrevNode(startNode);
7457 this.computeBufferMetadata();
7460 if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
7461 this.deleteNodeTail(startNode, startSplitPosInBuffer);
7462 this.validateCRLFWithNextNode(startNode);
7463 this.computeBufferMetadata();
7466 // delete content in the middle, this node will be splitted to nodes
7467 this.shrinkNode(startNode, startSplitPosInBuffer, endSplitPosInBuffer);
7468 this.computeBufferMetadata();
7471 let nodesToDel = [];
7472 let startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
7473 this.deleteNodeTail(startNode, startSplitPosInBuffer);
7474 this._searchCache.valdiate(offset);
7475 if (startNode.piece.length === 0) {
7476 nodesToDel.push(startNode);
7478 // update last touched node
7479 let endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
7480 this.deleteNodeHead(endNode, endSplitPosInBuffer);
7481 if (endNode.piece.length === 0) {
7482 nodesToDel.push(endNode);
7484 // delete nodes in between
7485 let secondNode = startNode.next();
7486 for (let node = secondNode; node !== rbTreeBase_1.SENTINEL && node !== endNode; node = node.next()) {
7487 nodesToDel.push(node);
7489 let prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
7490 this.deleteNodes(nodesToDel);
7491 this.validateCRLFWithNextNode(prev);
7492 this.computeBufferMetadata();
7494 insertContentToNodeLeft(value, node) {
7495 // we are inserting content to the beginning of node
7496 let nodesToDel = [];
7497 if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node)) {
7498 // move `\n` to new node.
7499 let piece = node.piece;
7500 let newStart = { line: piece.start.line + 1, column: 0 };
7501 let nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
7502 node.piece = nPiece;
7504 rbTreeBase_1.updateTreeMetadata(this, node, -1, -1);
7505 if (node.piece.length === 0) {
7506 nodesToDel.push(node);
7509 let newPieces = this.createNewPieces(value);
7510 let newNode = this.rbInsertLeft(node, newPieces[newPieces.length - 1]);
7511 for (let k = newPieces.length - 2; k >= 0; k--) {
7512 newNode = this.rbInsertLeft(newNode, newPieces[k]);
7514 this.validateCRLFWithPrevNode(newNode);
7515 this.deleteNodes(nodesToDel);
7517 insertContentToNodeRight(value, node) {
7518 // we are inserting to the right of this node.
7519 if (this.adjustCarriageReturnFromNext(value, node)) {
7520 // move \n to the new node.
7523 let newPieces = this.createNewPieces(value);
7524 let newNode = this.rbInsertRight(node, newPieces[0]);
7525 let tmpNode = newNode;
7526 for (let k = 1; k < newPieces.length; k++) {
7527 tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
7529 this.validateCRLFWithPrevNode(newNode);
7531 positionInBuffer(node, remainder, ret) {
7532 let piece = node.piece;
7533 let bufferIndex = node.piece.bufferIndex;
7534 let lineStarts = this._buffers[bufferIndex].lineStarts;
7535 let startOffset = lineStarts[piece.start.line] + piece.start.column;
7536 let offset = startOffset + remainder;
7537 // binary search offset between startOffset and endOffset
7538 let low = piece.start.line;
7539 let high = piece.end.line;
7543 while (low <= high) {
7544 mid = low + ((high - low) / 2) | 0;
7545 midStart = lineStarts[mid];
7549 midStop = lineStarts[mid + 1];
7550 if (offset < midStart) {
7553 else if (offset >= midStop) {
7562 ret.column = offset - midStart;
7567 column: offset - midStart
7570 getLineFeedCnt(bufferIndex, start, end) {
7571 // we don't need to worry about start: abc\r|\n, or abc|\r, or abc|\n, or abc|\r\n doesn't change the fact that, there is one line break after start.
7572 // now let's take care of end: abc\r|\n, if end is in between \r and \n, we need to add line feed count by 1
7573 if (end.column === 0) {
7574 return end.line - start.line;
7576 let lineStarts = this._buffers[bufferIndex].lineStarts;
7577 if (end.line === lineStarts.length - 1) { // it means, there is no \n after end, otherwise, there will be one more lineStart.
7578 return end.line - start.line;
7580 let nextLineStartOffset = lineStarts[end.line + 1];
7581 let endOffset = lineStarts[end.line] + end.column;
7582 if (nextLineStartOffset > endOffset + 1) { // there are more than 1 character after end, which means it can't be \n
7583 return end.line - start.line;
7585 // endOffset + 1 === nextLineStartOffset
7586 // character at endOffset is \n, so we check the character before first
7587 // if character at endOffset is \r, end.column is 0 and we can't get here.
7588 let previousCharOffset = endOffset - 1; // end.column > 0 so it's okay.
7589 let buffer = this._buffers[bufferIndex].buffer;
7590 if (buffer.charCodeAt(previousCharOffset) === 13) {
7591 return end.line - start.line + 1;
7594 return end.line - start.line;
7597 offsetInBuffer(bufferIndex, cursor) {
7598 let lineStarts = this._buffers[bufferIndex].lineStarts;
7599 return lineStarts[cursor.line] + cursor.column;
7601 deleteNodes(nodes) {
7602 for (let i = 0; i < nodes.length; i++) {
7603 rbTreeBase_1.rbDelete(this, nodes[i]);
7606 createNewPieces(text) {
7607 if (text.length > exports.AverageBufferSize) {
7608 // the content is large, operations like substring, charCode becomes slow
7609 // so here we split it into smaller chunks, just like what we did for CR/LF normalization
7611 while (text.length > exports.AverageBufferSize) {
7612 const lastChar = text.charCodeAt(exports.AverageBufferSize - 1);
7614 if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
7615 // last character is \r or a high surrogate => keep it back
7616 splitText = text.substring(0, exports.AverageBufferSize - 1);
7617 text = text.substring(exports.AverageBufferSize - 1);
7620 splitText = text.substring(0, exports.AverageBufferSize);
7621 text = text.substring(exports.AverageBufferSize);
7623 let lineStarts = createLineStartsFast(splitText);
7624 newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: splitText.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, splitText.length));
7625 this._buffers.push(new StringBuffer(splitText, lineStarts));
7627 let lineStarts = createLineStartsFast(text);
7628 newPieces.push(new Piece(this._buffers.length, /* buffer index */ { line: 0, column: 0 }, { line: lineStarts.length - 1, column: text.length - lineStarts[lineStarts.length - 1] }, lineStarts.length - 1, text.length));
7629 this._buffers.push(new StringBuffer(text, lineStarts));
7632 let startOffset = this._buffers[0].buffer.length;
7633 const lineStarts = createLineStartsFast(text, false);
7634 let start = this._lastChangeBufferPos;
7635 if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset
7636 && startOffset !== 0
7637 && this.startWithLF(text)
7638 && this.endWithCR(this._buffers[0].buffer) // todo, we can check this._lastChangeBufferPos's column as it's the last one
7640 this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };
7641 start = this._lastChangeBufferPos;
7642 for (let i = 0; i < lineStarts.length; i++) {
7643 lineStarts[i] += startOffset + 1;
7645 this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
7646 this._buffers[0].buffer += '_' + text;
7650 if (startOffset !== 0) {
7651 for (let i = 0; i < lineStarts.length; i++) {
7652 lineStarts[i] += startOffset;
7655 this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
7656 this._buffers[0].buffer += text;
7658 const endOffset = this._buffers[0].buffer.length;
7659 let endIndex = this._buffers[0].lineStarts.length - 1;
7660 let endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
7661 let endPos = { line: endIndex, column: endColumn };
7662 let newPiece = new Piece(0, /** todo@peng */ start, endPos, this.getLineFeedCnt(0, start, endPos), endOffset - startOffset);
7663 this._lastChangeBufferPos = endPos;
7666 getLinesRawContent() {
7667 return this.getContentOfSubTree(this.root);
7669 getLineRawContent(lineNumber, endOffset = 0) {
7672 let cache = this._searchCache.get2(lineNumber);
7675 let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber - 1);
7676 let buffer = this._buffers[x.piece.bufferIndex].buffer;
7677 let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
7678 if (cache.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
7679 ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);
7682 let accumualtedValue = this.getAccumulatedValue(x, lineNumber - cache.nodeStartLineNumber);
7683 return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);
7687 let nodeStartOffset = 0;
7688 const originalLineNumber = lineNumber;
7689 while (x !== rbTreeBase_1.SENTINEL) {
7690 if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
7693 else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
7694 let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
7695 let accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
7696 let buffer = this._buffers[x.piece.bufferIndex].buffer;
7697 let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
7698 nodeStartOffset += x.size_left;
7699 this._searchCache.set({
7702 nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)
7704 return buffer.substring(startOffset + prevAccumualtedValue, startOffset + accumualtedValue - endOffset);
7706 else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
7707 let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
7708 let buffer = this._buffers[x.piece.bufferIndex].buffer;
7709 let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
7710 ret = buffer.substring(startOffset + prevAccumualtedValue, startOffset + x.piece.length);
7714 lineNumber -= x.lf_left + x.piece.lineFeedCnt;
7715 nodeStartOffset += x.size_left + x.piece.length;
7720 // search in order, to find the node contains end column
7722 while (x !== rbTreeBase_1.SENTINEL) {
7723 let buffer = this._buffers[x.piece.bufferIndex].buffer;
7724 if (x.piece.lineFeedCnt > 0) {
7725 let accumualtedValue = this.getAccumulatedValue(x, 0);
7726 let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
7727 ret += buffer.substring(startOffset, startOffset + accumualtedValue - endOffset);
7731 let startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
7732 ret += buffer.substr(startOffset, x.piece.length);
7738 computeBufferMetadata() {
7742 while (x !== rbTreeBase_1.SENTINEL) {
7743 lfCnt += x.lf_left + x.piece.lineFeedCnt;
7744 len += x.size_left + x.piece.length;
7747 this._lineCnt = lfCnt;
7749 this._searchCache.valdiate(this._length);
7751 // #region node operations
7752 getIndexOf(node, accumulatedValue) {
7753 let piece = node.piece;
7754 let pos = this.positionInBuffer(node, accumulatedValue);
7755 let lineCnt = pos.line - piece.start.line;
7756 if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
7757 // we are checking the end of this node, so a CRLF check is necessary.
7758 let realLineCnt = this.getLineFeedCnt(node.piece.bufferIndex, piece.start, pos);
7759 if (realLineCnt !== lineCnt) {
7761 return { index: realLineCnt, remainder: 0 };
7764 return { index: lineCnt, remainder: pos.column };
7766 getAccumulatedValue(node, index) {
7770 let piece = node.piece;
7771 let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
7772 let expectedLineStartIndex = piece.start.line + index + 1;
7773 if (expectedLineStartIndex > piece.end.line) {
7774 return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
7777 return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
7780 deleteNodeTail(node, pos) {
7781 const piece = node.piece;
7782 const originalLFCnt = piece.lineFeedCnt;
7783 const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
7785 const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
7786 const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
7787 const lf_delta = newLineFeedCnt - originalLFCnt;
7788 const size_delta = newEndOffset - originalEndOffset;
7789 const newLength = piece.length + size_delta;
7790 node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
7791 rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta);
7793 deleteNodeHead(node, pos) {
7794 const piece = node.piece;
7795 const originalLFCnt = piece.lineFeedCnt;
7796 const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
7797 const newStart = pos;
7798 const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
7799 const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
7800 const lf_delta = newLineFeedCnt - originalLFCnt;
7801 const size_delta = originalStartOffset - newStartOffset;
7802 const newLength = piece.length + size_delta;
7803 node.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
7804 rbTreeBase_1.updateTreeMetadata(this, node, size_delta, lf_delta);
7806 shrinkNode(node, start, end) {
7807 const piece = node.piece;
7808 const originalStartPos = piece.start;
7809 const originalEndPos = piece.end;
7810 // old piece, originalStartPos, start
7811 const oldLength = piece.length;
7812 const oldLFCnt = piece.lineFeedCnt;
7813 const newEnd = start;
7814 const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
7815 const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
7816 node.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
7817 rbTreeBase_1.updateTreeMetadata(this, node, newLength - oldLength, newLineFeedCnt - oldLFCnt);
7818 // new right piece, end, originalEndPos
7819 let newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
7820 let newNode = this.rbInsertRight(node, newPiece);
7821 this.validateCRLFWithPrevNode(newNode);
7823 appendToNode(node, value) {
7824 if (this.adjustCarriageReturnFromNext(value, node)) {
7827 const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node);
7828 const startOffset = this._buffers[0].buffer.length;
7829 this._buffers[0].buffer += value;
7830 const lineStarts = createLineStartsFast(value, false);
7831 for (let i = 0; i < lineStarts.length; i++) {
7832 lineStarts[i] += startOffset;
7835 let prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
7836 this._buffers[0].lineStarts.pop();
7837 // _lastChangeBufferPos is already wrong
7838 this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };
7840 this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
7841 const endIndex = this._buffers[0].lineStarts.length - 1;
7842 const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
7843 const newEnd = { line: endIndex, column: endColumn };
7844 const newLength = node.piece.length + value.length;
7845 const oldLineFeedCnt = node.piece.lineFeedCnt;
7846 const newLineFeedCnt = this.getLineFeedCnt(0, node.piece.start, newEnd);
7847 const lf_delta = newLineFeedCnt - oldLineFeedCnt;
7848 node.piece = new Piece(node.piece.bufferIndex, node.piece.start, newEnd, newLineFeedCnt, newLength);
7849 this._lastChangeBufferPos = newEnd;
7850 rbTreeBase_1.updateTreeMetadata(this, node, value.length, lf_delta);
7854 let cache = this._searchCache.get(offset);
7858 nodeStartOffset: cache.nodeStartOffset,
7859 remainder: offset - cache.nodeStartOffset
7862 let nodeStartOffset = 0;
7863 while (x !== rbTreeBase_1.SENTINEL) {
7864 if (x.size_left > offset) {
7867 else if (x.size_left + x.piece.length >= offset) {
7868 nodeStartOffset += x.size_left;
7871 remainder: offset - x.size_left,
7874 this._searchCache.set(ret);
7878 offset -= x.size_left + x.piece.length;
7879 nodeStartOffset += x.size_left + x.piece.length;
7885 nodeAt2(lineNumber, column) {
7887 let nodeStartOffset = 0;
7888 while (x !== rbTreeBase_1.SENTINEL) {
7889 if (x.left !== rbTreeBase_1.SENTINEL && x.lf_left >= lineNumber - 1) {
7892 else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
7893 let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
7894 let accumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
7895 nodeStartOffset += x.size_left;
7898 remainder: Math.min(prevAccumualtedValue + column - 1, accumualtedValue),
7902 else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
7903 let prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
7904 if (prevAccumualtedValue + column - 1 <= x.piece.length) {
7907 remainder: prevAccumualtedValue + column - 1,
7912 column -= x.piece.length - prevAccumualtedValue;
7917 lineNumber -= x.lf_left + x.piece.lineFeedCnt;
7918 nodeStartOffset += x.size_left + x.piece.length;
7922 // search in order, to find the node contains position.column
7924 while (x !== rbTreeBase_1.SENTINEL) {
7925 if (x.piece.lineFeedCnt > 0) {
7926 let accumualtedValue = this.getAccumulatedValue(x, 0);
7927 let nodeStartOffset = this.offsetOfNode(x);
7930 remainder: Math.min(column - 1, accumualtedValue),
7935 if (x.piece.length >= column - 1) {
7936 let nodeStartOffset = this.offsetOfNode(x);
7939 remainder: column - 1,
7944 column -= x.piece.length;
7951 nodeCharCodeAt(node, offset) {
7952 if (node.piece.lineFeedCnt < 1) {
7955 let buffer = this._buffers[node.piece.bufferIndex];
7956 let newOffset = this.offsetInBuffer(node.piece.bufferIndex, node.piece.start) + offset;
7957 return buffer.buffer.charCodeAt(newOffset);
7959 offsetOfNode(node) {
7963 let pos = node.size_left;
7964 while (node !== this.root) {
7965 if (node.parent.right === node) {
7966 pos += node.parent.size_left + node.parent.piece.length;
7975 return !(this._EOLNormalized && this._EOL === '\n');
7978 if (typeof val === 'string') {
7979 return val.charCodeAt(0) === 10;
7981 if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
7984 let piece = val.piece;
7985 let lineStarts = this._buffers[piece.bufferIndex].lineStarts;
7986 let line = piece.start.line;
7987 let startOffset = lineStarts[line] + piece.start.column;
7988 if (line === lineStarts.length - 1) {
7989 // last line, so there is no line feed at the end of this line
7992 let nextLineOffset = lineStarts[line + 1];
7993 if (nextLineOffset > startOffset + 1) {
7996 return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
7999 if (typeof val === 'string') {
8000 return val.charCodeAt(val.length - 1) === 13;
8002 if (val === rbTreeBase_1.SENTINEL || val.piece.lineFeedCnt === 0) {
8005 return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
8007 validateCRLFWithPrevNode(nextNode) {
8008 if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
8009 let node = nextNode.prev();
8010 if (this.endWithCR(node)) {
8011 this.fixCRLF(node, nextNode);
8015 validateCRLFWithNextNode(node) {
8016 if (this.shouldCheckCRLF() && this.endWithCR(node)) {
8017 let nextNode = node.next();
8018 if (this.startWithLF(nextNode)) {
8019 this.fixCRLF(node, nextNode);
8023 fixCRLF(prev, next) {
8024 let nodesToDel = [];
8026 let lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
8028 if (prev.piece.end.column === 0) {
8029 // it means, last line ends with \r, not \r\n
8030 newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
8034 newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
8036 const prevNewLength = prev.piece.length - 1;
8037 const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
8038 prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
8039 rbTreeBase_1.updateTreeMetadata(this, prev, -1, -1);
8040 if (prev.piece.length === 0) {
8041 nodesToDel.push(prev);
8044 let newStart = { line: next.piece.start.line + 1, column: 0 };
8045 const newLength = next.piece.length - 1;
8046 const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
8047 next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
8048 rbTreeBase_1.updateTreeMetadata(this, next, -1, -1);
8049 if (next.piece.length === 0) {
8050 nodesToDel.push(next);
8052 // create new piece which contains \r\n
8053 let pieces = this.createNewPieces('\r\n');
8054 this.rbInsertRight(prev, pieces[0]);
8055 // delete empty nodes
8056 for (let i = 0; i < nodesToDel.length; i++) {
8057 rbTreeBase_1.rbDelete(this, nodesToDel[i]);
8060 adjustCarriageReturnFromNext(value, node) {
8061 if (this.shouldCheckCRLF() && this.endWithCR(value)) {
8062 let nextNode = node.next();
8063 if (this.startWithLF(nextNode)) {
8064 // move `\n` forward
8066 if (nextNode.piece.length === 1) {
8067 rbTreeBase_1.rbDelete(this, nextNode);
8070 const piece = nextNode.piece;
8071 const newStart = { line: piece.start.line + 1, column: 0 };
8072 const newLength = piece.length - 1;
8073 const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
8074 nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
8075 rbTreeBase_1.updateTreeMetadata(this, nextNode, -1, -1);
8084 // #region Tree operations
8085 iterate(node, callback) {
8086 if (node === rbTreeBase_1.SENTINEL) {
8087 return callback(rbTreeBase_1.SENTINEL);
8089 let leftRet = this.iterate(node.left, callback);
8093 return callback(node) && this.iterate(node.right, callback);
8095 getNodeContent(node) {
8096 if (node === rbTreeBase_1.SENTINEL) {
8099 let buffer = this._buffers[node.piece.bufferIndex];
8101 let piece = node.piece;
8102 let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
8103 let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
8104 currentContent = buffer.buffer.substring(startOffset, endOffset);
8105 return currentContent;
8107 getPieceContent(piece) {
8108 let buffer = this._buffers[piece.bufferIndex];
8109 let startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
8110 let endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
8111 let currentContent = buffer.buffer.substring(startOffset, endOffset);
8112 return currentContent;
8121 rbInsertRight(node, p) {
8122 let z = new rbTreeBase_1.TreeNode(p, 1 /* Red */);
8123 z.left = rbTreeBase_1.SENTINEL;
8124 z.right = rbTreeBase_1.SENTINEL;
8125 z.parent = rbTreeBase_1.SENTINEL;
8129 if (x === rbTreeBase_1.SENTINEL) {
8131 z.color = 0 /* Black */;
8133 else if (node.right === rbTreeBase_1.SENTINEL) {
8138 let nextNode = rbTreeBase_1.leftest(node.right);
8140 z.parent = nextNode;
8142 rbTreeBase_1.fixInsert(this, z);
8152 rbInsertLeft(node, p) {
8153 let z = new rbTreeBase_1.TreeNode(p, 1 /* Red */);
8154 z.left = rbTreeBase_1.SENTINEL;
8155 z.right = rbTreeBase_1.SENTINEL;
8156 z.parent = rbTreeBase_1.SENTINEL;
8159 if (this.root === rbTreeBase_1.SENTINEL) {
8161 z.color = 0 /* Black */;
8163 else if (node.left === rbTreeBase_1.SENTINEL) {
8168 let prevNode = rbTreeBase_1.righttest(node.left); // a
8170 z.parent = prevNode;
8172 rbTreeBase_1.fixInsert(this, z);
8175 getContentOfSubTree(node) {
8177 this.iterate(node, node => {
8178 str += this.getNodeContent(node);
8184 exports.PieceTreeBase = PieceTreeBase;
8189 /***/ (function(module, exports, __webpack_require__) {
8193 /*---------------------------------------------------------------------------------------------
8194 * Copyright (c) Microsoft Corporation. All rights reserved.
8195 * Licensed under the MIT License. See License.txt in the project root for license information.
8196 *--------------------------------------------------------------------------------------------*/
8197 Object.defineProperty(exports, "__esModule", { value: true });
8199 * A position in the editor.
8202 constructor(lineNumber, column) {
8203 this.lineNumber = lineNumber;
8204 this.column = column;
8207 * Create a new postion from this position.
8209 * @param newLineNumber new line number
8210 * @param newColumn new column
8212 with(newLineNumber = this.lineNumber, newColumn = this.column) {
8213 if (newLineNumber === this.lineNumber && newColumn === this.column) {
8217 return new Position(newLineNumber, newColumn);
8221 * Derive a new position from this position.
8223 * @param deltaLineNumber line number delta
8224 * @param deltaColumn column delta
8226 delta(deltaLineNumber = 0, deltaColumn = 0) {
8227 return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
8230 * Test if this position equals other position
8233 return Position.equals(this, other);
8236 * Test if position `a` equals position `b`
8238 static equals(a, b) {
8244 a.lineNumber === b.lineNumber &&
8245 a.column === b.column);
8248 * Test if this position is before other position.
8249 * If the two positions are equal, the result will be false.
8252 return Position.isBefore(this, other);
8255 * Test if position `a` is before position `b`.
8256 * If the two positions are equal, the result will be false.
8258 static isBefore(a, b) {
8259 if (a.lineNumber < b.lineNumber) {
8262 if (b.lineNumber < a.lineNumber) {
8265 return a.column < b.column;
8268 * Test if this position is before other position.
8269 * If the two positions are equal, the result will be true.
8271 isBeforeOrEqual(other) {
8272 return Position.isBeforeOrEqual(this, other);
8275 * Test if position `a` is before position `b`.
8276 * If the two positions are equal, the result will be true.
8278 static isBeforeOrEqual(a, b) {
8279 if (a.lineNumber < b.lineNumber) {
8282 if (b.lineNumber < a.lineNumber) {
8285 return a.column <= b.column;
8288 * A function that compares positions, useful for sorting
8290 static compare(a, b) {
8291 let aLineNumber = a.lineNumber | 0;
8292 let bLineNumber = b.lineNumber | 0;
8293 if (aLineNumber === bLineNumber) {
8294 let aColumn = a.column | 0;
8295 let bColumn = b.column | 0;
8296 return aColumn - bColumn;
8298 return aLineNumber - bLineNumber;
8301 * Clone this position.
8304 return new Position(this.lineNumber, this.column);
8307 * Convert to a human-readable representation.
8310 return '(' + this.lineNumber + ',' + this.column + ')';
8314 * Create a `Position` from an `IPosition`.
8317 return new Position(pos.lineNumber, pos.column);
8320 * Test if `obj` is an `IPosition`.
8322 static isIPosition(obj) {
8324 && (typeof obj.lineNumber === 'number')
8325 && (typeof obj.column === 'number'));
8328 exports.Position = Position;
8333 /***/ (function(module, exports, __webpack_require__) {
8337 /*---------------------------------------------------------------------------------------------
8338 * Copyright (c) Microsoft Corporation. All rights reserved.
8339 * Licensed under the MIT License. See License.txt in the project root for license information.
8340 *--------------------------------------------------------------------------------------------*/
8341 Object.defineProperty(exports, "__esModule", { value: true });
8343 constructor(piece, color) {
8353 if (this.right !== exports.SENTINEL) {
8354 return leftest(this.right);
8357 while (node.parent !== exports.SENTINEL) {
8358 if (node.parent.left === node) {
8363 if (node.parent === exports.SENTINEL) {
8364 return exports.SENTINEL;
8371 if (this.left !== exports.SENTINEL) {
8372 return righttest(this.left);
8375 while (node.parent !== exports.SENTINEL) {
8376 if (node.parent.right === node) {
8381 if (node.parent === exports.SENTINEL) {
8382 return exports.SENTINEL;
8394 exports.TreeNode = TreeNode;
8395 exports.SENTINEL = new TreeNode(null, 0 /* Black */);
8396 exports.SENTINEL.parent = exports.SENTINEL;
8397 exports.SENTINEL.left = exports.SENTINEL;
8398 exports.SENTINEL.right = exports.SENTINEL;
8399 exports.SENTINEL.color = 0 /* Black */;
8400 function leftest(node) {
8401 while (node.left !== exports.SENTINEL) {
8406 exports.leftest = leftest;
8407 function righttest(node) {
8408 while (node.right !== exports.SENTINEL) {
8413 exports.righttest = righttest;
8414 function calculateSize(node) {
8415 if (node === exports.SENTINEL) {
8418 return node.size_left + node.piece.length + calculateSize(node.right);
8420 exports.calculateSize = calculateSize;
8421 function calculateLF(node) {
8422 if (node === exports.SENTINEL) {
8425 return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right);
8427 exports.calculateLF = calculateLF;
8428 function resetSentinel() {
8429 exports.SENTINEL.parent = exports.SENTINEL;
8431 exports.resetSentinel = resetSentinel;
8432 function leftRotate(tree, x) {
8435 y.size_left += x.size_left + (x.piece ? x.piece.length : 0);
8436 y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
8438 if (y.left !== exports.SENTINEL) {
8441 y.parent = x.parent;
8442 if (x.parent === exports.SENTINEL) {
8445 else if (x.parent.left === x) {
8454 exports.leftRotate = leftRotate;
8455 function rightRotate(tree, y) {
8458 if (x.right !== exports.SENTINEL) {
8461 x.parent = y.parent;
8463 y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);
8464 y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
8465 if (y.parent === exports.SENTINEL) {
8468 else if (y === y.parent.right) {
8477 exports.rightRotate = rightRotate;
8478 function rbDelete(tree, z) {
8481 if (z.left === exports.SENTINEL) {
8485 else if (z.right === exports.SENTINEL) {
8490 y = leftest(z.right);
8493 if (y === tree.root) {
8495 // if x is null, we are removing the only node
8496 x.color = 0 /* Black */;
8499 tree.root.parent = exports.SENTINEL;
8502 let yWasRed = (y.color === 1 /* Red */);
8503 if (y === y.parent.left) {
8510 x.parent = y.parent;
8511 recomputeTreeMetadata(tree, x);
8514 if (y.parent === z) {
8518 x.parent = y.parent;
8520 // as we make changes to x's hierarchy, update size_left of subtree first
8521 recomputeTreeMetadata(tree, x);
8524 y.parent = z.parent;
8526 if (z === tree.root) {
8530 if (z === z.parent.left) {
8537 if (y.left !== exports.SENTINEL) {
8540 if (y.right !== exports.SENTINEL) {
8544 // we replace z with y, so in this sub tree, the length change is z.item.length
8545 y.size_left = z.size_left;
8546 y.lf_left = z.lf_left;
8547 recomputeTreeMetadata(tree, y);
8550 if (x.parent.left === x) {
8551 let newSizeLeft = calculateSize(x);
8552 let newLFLeft = calculateLF(x);
8553 if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
8554 let delta = newSizeLeft - x.parent.size_left;
8555 let lf_delta = newLFLeft - x.parent.lf_left;
8556 x.parent.size_left = newSizeLeft;
8557 x.parent.lf_left = newLFLeft;
8558 updateTreeMetadata(tree, x.parent, delta, lf_delta);
8561 recomputeTreeMetadata(tree, x.parent);
8568 while (x !== tree.root && x.color === 0 /* Black */) {
8569 if (x === x.parent.left) {
8571 if (w.color === 1 /* Red */) {
8572 w.color = 0 /* Black */;
8573 x.parent.color = 1 /* Red */;
8574 leftRotate(tree, x.parent);
8577 if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
8578 w.color = 1 /* Red */;
8582 if (w.right.color === 0 /* Black */) {
8583 w.left.color = 0 /* Black */;
8584 w.color = 1 /* Red */;
8585 rightRotate(tree, w);
8588 w.color = x.parent.color;
8589 x.parent.color = 0 /* Black */;
8590 w.right.color = 0 /* Black */;
8591 leftRotate(tree, x.parent);
8597 if (w.color === 1 /* Red */) {
8598 w.color = 0 /* Black */;
8599 x.parent.color = 1 /* Red */;
8600 rightRotate(tree, x.parent);
8603 if (w.left.color === 0 /* Black */ && w.right.color === 0 /* Black */) {
8604 w.color = 1 /* Red */;
8608 if (w.left.color === 0 /* Black */) {
8609 w.right.color = 0 /* Black */;
8610 w.color = 1 /* Red */;
8611 leftRotate(tree, w);
8614 w.color = x.parent.color;
8615 x.parent.color = 0 /* Black */;
8616 w.left.color = 0 /* Black */;
8617 rightRotate(tree, x.parent);
8622 x.color = 0 /* Black */;
8625 exports.rbDelete = rbDelete;
8626 function fixInsert(tree, x) {
8627 recomputeTreeMetadata(tree, x);
8628 while (x !== tree.root && x.parent.color === 1 /* Red */) {
8629 if (x.parent === x.parent.parent.left) {
8630 const y = x.parent.parent.right;
8631 if (y.color === 1 /* Red */) {
8632 x.parent.color = 0 /* Black */;
8633 y.color = 0 /* Black */;
8634 x.parent.parent.color = 1 /* Red */;
8635 x = x.parent.parent;
8638 if (x === x.parent.right) {
8640 leftRotate(tree, x);
8642 x.parent.color = 0 /* Black */;
8643 x.parent.parent.color = 1 /* Red */;
8644 rightRotate(tree, x.parent.parent);
8648 const y = x.parent.parent.left;
8649 if (y.color === 1 /* Red */) {
8650 x.parent.color = 0 /* Black */;
8651 y.color = 0 /* Black */;
8652 x.parent.parent.color = 1 /* Red */;
8653 x = x.parent.parent;
8656 if (x === x.parent.left) {
8658 rightRotate(tree, x);
8660 x.parent.color = 0 /* Black */;
8661 x.parent.parent.color = 1 /* Red */;
8662 leftRotate(tree, x.parent.parent);
8666 tree.root.color = 0 /* Black */;
8668 exports.fixInsert = fixInsert;
8669 function updateTreeMetadata(tree, x, delta, lineFeedCntDelta) {
8670 // node length change or line feed count change
8671 while (x !== tree.root && x !== exports.SENTINEL) {
8672 if (x.parent.left === x) {
8673 x.parent.size_left += delta;
8674 x.parent.lf_left += lineFeedCntDelta;
8679 exports.updateTreeMetadata = updateTreeMetadata;
8680 function recomputeTreeMetadata(tree, x) {
8683 if (x === tree.root) {
8687 // go upwards till the node whose left subtree is changed.
8688 while (x !== tree.root && x === x.parent.right) {
8691 if (x === tree.root) {
8692 // well, it means we add a node to the end (inorder)
8695 // x is the node whose right subtree is changed.
8697 delta = calculateSize(x.left) - x.size_left;
8698 lf_delta = calculateLF(x.left) - x.lf_left;
8699 x.size_left += delta;
8700 x.lf_left += lf_delta;
8702 // go upwards till root. O(logN)
8703 while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) {
8704 if (x.parent.left === x) {
8705 x.parent.size_left += delta;
8706 x.parent.lf_left += lf_delta;
8711 exports.recomputeTreeMetadata = recomputeTreeMetadata;
8716 /***/ (function(module, exports, __webpack_require__) {
8720 /*---------------------------------------------------------------------------------------------
8721 * Copyright (c) Microsoft Corporation. All rights reserved.
8722 * Licensed under the MIT License. See License.txt in the project root for license information.
8723 *--------------------------------------------------------------------------------------------*/
8724 Object.defineProperty(exports, "__esModule", { value: true });
8725 const pieceTreeBase_1 = __webpack_require__(43);
8726 exports.UTF8_BOM_CHARACTER = String.fromCharCode(65279 /* UTF8_BOM */);
8727 function startsWithUTF8BOM(str) {
8728 return !!(str && str.length > 0 && str.charCodeAt(0) === 65279 /* UTF8_BOM */);
8730 exports.startsWithUTF8BOM = startsWithUTF8BOM;
8731 class PieceTreeTextBufferFactory {
8732 constructor(_chunks, _bom, _cr, _lf, _crlf, _normalizeEOL) {
8733 this._chunks = _chunks;
8738 this._normalizeEOL = _normalizeEOL;
8740 _getEOL(defaultEOL) {
8741 const totalEOLCount = this._cr + this._lf + this._crlf;
8742 const totalCRCount = this._cr + this._crlf;
8743 if (totalEOLCount === 0) {
8744 // This is an empty file or a file with precisely one line
8745 return (defaultEOL === 1 /* LF */ ? '\n' : '\r\n');
8747 if (totalCRCount > totalEOLCount / 2) {
8748 // More than half of the file contains \r\n ending lines
8751 // At least one line more ends in \n
8754 create(defaultEOL) {
8755 const eol = this._getEOL(defaultEOL);
8756 let chunks = this._chunks;
8757 if (this._normalizeEOL &&
8758 ((eol === '\r\n' && (this._cr > 0 || this._lf > 0))
8759 || (eol === '\n' && (this._cr > 0 || this._crlf > 0)))) {
8761 for (let i = 0, len = chunks.length; i < len; i++) {
8762 let str = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
8763 let newLineStart = pieceTreeBase_1.createLineStartsFast(str);
8764 chunks[i] = new pieceTreeBase_1.StringBuffer(str, newLineStart);
8767 return new pieceTreeBase_1.PieceTreeBase(chunks, eol, this._normalizeEOL);
8769 getFirstLineText(lengthLimit) {
8770 return this._chunks[0].buffer.substr(0, 100).split(/\r\n|\r|\n/)[0];
8773 exports.PieceTreeTextBufferFactory = PieceTreeTextBufferFactory;
8774 class PieceTreeTextBufferBuilder {
8778 this._hasPreviousChar = false;
8779 this._previousChar = 0;
8780 this._tmpLineStarts = [];
8785 acceptChunk(chunk) {
8786 if (chunk.length === 0) {
8789 if (this.chunks.length === 0) {
8790 if (startsWithUTF8BOM(chunk)) {
8791 this.BOM = exports.UTF8_BOM_CHARACTER;
8792 chunk = chunk.substr(1);
8795 const lastChar = chunk.charCodeAt(chunk.length - 1);
8796 if (lastChar === 13 /* CarriageReturn */ || (lastChar >= 0xD800 && lastChar <= 0xDBFF)) {
8797 // last character is \r or a high surrogate => keep it back
8798 this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
8799 this._hasPreviousChar = true;
8800 this._previousChar = lastChar;
8803 this._acceptChunk1(chunk, false);
8804 this._hasPreviousChar = false;
8805 this._previousChar = lastChar;
8808 _acceptChunk1(chunk, allowEmptyStrings) {
8809 if (!allowEmptyStrings && chunk.length === 0) {
8813 if (this._hasPreviousChar) {
8814 this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
8817 this._acceptChunk2(chunk);
8820 _acceptChunk2(chunk) {
8821 const lineStarts = pieceTreeBase_1.createLineStarts(this._tmpLineStarts, chunk);
8822 this.chunks.push(new pieceTreeBase_1.StringBuffer(chunk, lineStarts.lineStarts));
8823 this.cr += lineStarts.cr;
8824 this.lf += lineStarts.lf;
8825 this.crlf += lineStarts.crlf;
8827 finish(normalizeEOL = true) {
8829 return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, normalizeEOL);
8832 if (this.chunks.length === 0) {
8833 this._acceptChunk1('', true);
8835 if (this._hasPreviousChar) {
8836 this._hasPreviousChar = false;
8837 // recreate last chunk
8838 let lastChunk = this.chunks[this.chunks.length - 1];
8839 lastChunk.buffer += String.fromCharCode(this._previousChar);
8840 let newLineStarts = pieceTreeBase_1.createLineStartsFast(lastChunk.buffer);
8841 lastChunk.lineStarts = newLineStarts;
8842 if (this._previousChar === 13 /* CarriageReturn */) {
8848 exports.PieceTreeTextBufferBuilder = PieceTreeTextBufferBuilder;
8853 /***/ (function(module, exports, __webpack_require__) {
8857 /*---------------------------------------------------------------------------------------------
8858 * Copyright (c) Microsoft Corporation. All rights reserved.
8859 * Licensed under the MIT License. See License.txt in the project root for license information.
8860 *--------------------------------------------------------------------------------------------*/
8861 Object.defineProperty(exports, "__esModule", { value: true });
8862 const position_1 = __webpack_require__(44);
8864 * A range in the editor. (startLineNumber,startColumn) is <= (endLineNumber,endColumn)
8867 constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
8868 if ((startLineNumber > endLineNumber) || (startLineNumber === endLineNumber && startColumn > endColumn)) {
8869 this.startLineNumber = endLineNumber;
8870 this.startColumn = endColumn;
8871 this.endLineNumber = startLineNumber;
8872 this.endColumn = startColumn;
8875 this.startLineNumber = startLineNumber;
8876 this.startColumn = startColumn;
8877 this.endLineNumber = endLineNumber;
8878 this.endColumn = endColumn;
8882 * Test if this range is empty.
8885 return Range.isEmpty(this);
8888 * Test if `range` is empty.
8890 static isEmpty(range) {
8891 return (range.startLineNumber === range.endLineNumber && range.startColumn === range.endColumn);
8894 * Test if position is in this range. If the position is at the edges, will return true.
8896 containsPosition(position) {
8897 return Range.containsPosition(this, position);
8900 * Test if `position` is in `range`. If the position is at the edges, will return true.
8902 static containsPosition(range, position) {
8903 if (position.lineNumber < range.startLineNumber || position.lineNumber > range.endLineNumber) {
8906 if (position.lineNumber === range.startLineNumber && position.column < range.startColumn) {
8909 if (position.lineNumber === range.endLineNumber && position.column > range.endColumn) {
8915 * Test if range is in this range. If the range is equal to this range, will return true.
8917 containsRange(range) {
8918 return Range.containsRange(this, range);
8921 * Test if `otherRange` is in `range`. If the ranges are equal, will return true.
8923 static containsRange(range, otherRange) {
8924 if (otherRange.startLineNumber < range.startLineNumber || otherRange.endLineNumber < range.startLineNumber) {
8927 if (otherRange.startLineNumber > range.endLineNumber || otherRange.endLineNumber > range.endLineNumber) {
8930 if (otherRange.startLineNumber === range.startLineNumber && otherRange.startColumn < range.startColumn) {
8933 if (otherRange.endLineNumber === range.endLineNumber && otherRange.endColumn > range.endColumn) {
8939 * A reunion of the two ranges.
8940 * The smallest position will be used as the start point, and the largest one as the end point.
8943 return Range.plusRange(this, range);
8946 * A reunion of the two ranges.
8947 * The smallest position will be used as the start point, and the largest one as the end point.
8949 static plusRange(a, b) {
8950 let startLineNumber;
8954 if (b.startLineNumber < a.startLineNumber) {
8955 startLineNumber = b.startLineNumber;
8956 startColumn = b.startColumn;
8958 else if (b.startLineNumber === a.startLineNumber) {
8959 startLineNumber = b.startLineNumber;
8960 startColumn = Math.min(b.startColumn, a.startColumn);
8963 startLineNumber = a.startLineNumber;
8964 startColumn = a.startColumn;
8966 if (b.endLineNumber > a.endLineNumber) {
8967 endLineNumber = b.endLineNumber;
8968 endColumn = b.endColumn;
8970 else if (b.endLineNumber === a.endLineNumber) {
8971 endLineNumber = b.endLineNumber;
8972 endColumn = Math.max(b.endColumn, a.endColumn);
8975 endLineNumber = a.endLineNumber;
8976 endColumn = a.endColumn;
8978 return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
8981 * A intersection of the two ranges.
8983 intersectRanges(range) {
8984 return Range.intersectRanges(this, range);
8987 * A intersection of the two ranges.
8989 static intersectRanges(a, b) {
8990 let resultStartLineNumber = a.startLineNumber;
8991 let resultStartColumn = a.startColumn;
8992 let resultEndLineNumber = a.endLineNumber;
8993 let resultEndColumn = a.endColumn;
8994 let otherStartLineNumber = b.startLineNumber;
8995 let otherStartColumn = b.startColumn;
8996 let otherEndLineNumber = b.endLineNumber;
8997 let otherEndColumn = b.endColumn;
8998 if (resultStartLineNumber < otherStartLineNumber) {
8999 resultStartLineNumber = otherStartLineNumber;
9000 resultStartColumn = otherStartColumn;
9002 else if (resultStartLineNumber === otherStartLineNumber) {
9003 resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
9005 if (resultEndLineNumber > otherEndLineNumber) {
9006 resultEndLineNumber = otherEndLineNumber;
9007 resultEndColumn = otherEndColumn;
9009 else if (resultEndLineNumber === otherEndLineNumber) {
9010 resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
9012 // Check if selection is now empty
9013 if (resultStartLineNumber > resultEndLineNumber) {
9016 if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
9019 return new Range(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
9022 * Test if this range equals other.
9024 equalsRange(other) {
9025 return Range.equalsRange(this, other);
9028 * Test if range `a` equals `b`.
9030 static equalsRange(a, b) {
9033 a.startLineNumber === b.startLineNumber &&
9034 a.startColumn === b.startColumn &&
9035 a.endLineNumber === b.endLineNumber &&
9036 a.endColumn === b.endColumn);
9039 * Return the end position (which will be after or equal to the start position)
9042 return new position_1.Position(this.endLineNumber, this.endColumn);
9045 * Return the start position (which will be before or equal to the end position)
9047 getStartPosition() {
9048 return new position_1.Position(this.startLineNumber, this.startColumn);
9051 * Transform to a user presentable string representation.
9054 return '[' + this.startLineNumber + ',' + this.startColumn + ' -> ' + this.endLineNumber + ',' + this.endColumn + ']';
9057 * Create a new range using this range's start position, and using endLineNumber and endColumn as the end position.
9059 setEndPosition(endLineNumber, endColumn) {
9060 return new Range(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
9063 * Create a new range using this range's end position, and using startLineNumber and startColumn as the start position.
9065 setStartPosition(startLineNumber, startColumn) {
9066 return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
9069 * Create a new empty range using this range's start position.
9072 return Range.collapseToStart(this);
9075 * Create a new empty range using this range's start position.
9077 static collapseToStart(range) {
9078 return new Range(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn);
9081 static fromPositions(start, end = start) {
9082 return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
9084 static lift(range) {
9088 return new Range(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
9091 * Test if `obj` is an `IRange`.
9093 static isIRange(obj) {
9095 && (typeof obj.startLineNumber === 'number')
9096 && (typeof obj.startColumn === 'number')
9097 && (typeof obj.endLineNumber === 'number')
9098 && (typeof obj.endColumn === 'number'));
9101 * Test if the two ranges are touching in any way.
9103 static areIntersectingOrTouching(a, b) {
9104 // Check if `a` is before `b`
9105 if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn)) {
9108 // Check if `b` is before `a`
9109 if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn)) {
9112 // These ranges must intersect
9116 * Test if the two ranges are intersecting. If the ranges are touching it returns true.
9118 static areIntersecting(a, b) {
9119 // Check if `a` is before `b`
9120 if (a.endLineNumber < b.startLineNumber || (a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn)) {
9123 // Check if `b` is before `a`
9124 if (b.endLineNumber < a.startLineNumber || (b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn)) {
9127 // These ranges must intersect
9131 * A function that compares ranges, useful for sorting ranges
9132 * It will first compare ranges on the startPosition and then on the endPosition
9134 static compareRangesUsingStarts(a, b) {
9136 const aStartLineNumber = a.startLineNumber | 0;
9137 const bStartLineNumber = b.startLineNumber | 0;
9138 if (aStartLineNumber === bStartLineNumber) {
9139 const aStartColumn = a.startColumn | 0;
9140 const bStartColumn = b.startColumn | 0;
9141 if (aStartColumn === bStartColumn) {
9142 const aEndLineNumber = a.endLineNumber | 0;
9143 const bEndLineNumber = b.endLineNumber | 0;
9144 if (aEndLineNumber === bEndLineNumber) {
9145 const aEndColumn = a.endColumn | 0;
9146 const bEndColumn = b.endColumn | 0;
9147 return aEndColumn - bEndColumn;
9149 return aEndLineNumber - bEndLineNumber;
9151 return aStartColumn - bStartColumn;
9153 return aStartLineNumber - bStartLineNumber;
9155 const aExists = (a ? 1 : 0);
9156 const bExists = (b ? 1 : 0);
9157 return aExists - bExists;
9160 * A function that compares ranges, useful for sorting ranges
9161 * It will first compare ranges on the endPosition and then on the startPosition
9163 static compareRangesUsingEnds(a, b) {
9164 if (a.endLineNumber === b.endLineNumber) {
9165 if (a.endColumn === b.endColumn) {
9166 if (a.startLineNumber === b.startLineNumber) {
9167 return a.startColumn - b.startColumn;
9169 return a.startLineNumber - b.startLineNumber;
9171 return a.endColumn - b.endColumn;
9173 return a.endLineNumber - b.endLineNumber;
9176 * Test if the range spans multiple lines.
9178 static spansMultipleLines(range) {
9179 return range.endLineNumber > range.startLineNumber;
9182 exports.Range = Range;
9187 /***/ (function(module, exports, __webpack_require__) {
9190 /* --------------------------------------------------------------------------------------------
\r
9191 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
9192 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
9193 * ------------------------------------------------------------------------------------------ */
\r
9195 Object.defineProperty(exports, "__esModule", { value: true });
\r
9196 const vscode_languageserver_protocol_1 = __webpack_require__(3);
\r
9197 const uuid_1 = __webpack_require__(38);
\r
9198 class ProgressImpl {
\r
9199 constructor(_connection, title, percentage, message, cancellable) {
\r
9200 this._connection = _connection;
\r
9201 this._id = uuid_1.generateUuid();
\r
9207 if (percentage !== undefined) {
\r
9208 params.percentage = percentage;
\r
9210 if (message !== undefined) {
\r
9211 params.message = message;
\r
9213 if (cancellable !== undefined) {
\r
9214 params.cancellable = cancellable;
\r
9216 ProgressImpl.Instances.set(this._id, this);
\r
9217 this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
\r
9218 this._connection.sendNotification(vscode_languageserver_protocol_1.Proposed.ProgressStartNotification.type, params);
\r
9221 return this._source.token;
\r
9223 report(arg0, arg1) {
\r
9226 if (typeof arg0 === 'number') {
\r
9227 percentage = arg0;
\r
9228 if (arg1 !== undefined) {
\r
9235 this._connection.sendNotification(vscode_languageserver_protocol_1.Proposed.ProgressReportNotification.type, { id: this._id, percentage, message });
\r
9238 ProgressImpl.Instances.delete(this._id);
\r
9239 this._source.dispose();
\r
9240 this._connection.sendNotification(vscode_languageserver_protocol_1.Proposed.ProgressDoneNotification.type, { id: this._id });
\r
9243 this._source.cancel();
\r
9246 ProgressImpl.Instances = new Map();
\r
9247 class NullProgress {
\r
9249 this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
\r
9252 return this._source.token;
\r
9259 exports.ProgressFeature = (Base) => {
\r
9260 return class extends Base {
\r
9262 let capabilities = cap;
\r
9263 if (capabilities.window && capabilities.window.progress) {
\r
9264 this._progressSupported = true;
\r
9265 this.connection.onNotification(vscode_languageserver_protocol_1.Proposed.ProgressCancelNotification.type, (params) => {
\r
9266 let progress = ProgressImpl.Instances.get(params.id);
\r
9267 if (progress !== undefined) {
\r
9268 progress.cancel();
\r
9273 createProgress(title, percentage, message, cancellable) {
\r
9274 if (this._progressSupported) {
\r
9275 return new ProgressImpl(this.connection, title, percentage, message, cancellable);
\r
9278 return new NullProgress();
\r
9287 /***/ (function(module, exports, __webpack_require__) {
9290 /*---------------------------------------------------------------------------------------------
9291 * Copyright (c) Microsoft Corporation. All rights reserved.
9292 * Licensed under the MIT License. See License.txt in the project root for license information.
9293 *--------------------------------------------------------------------------------------------*/
9295 Object.defineProperty(exports, "__esModule", { value: true });
9296 var url_1 = __webpack_require__(40);
9297 var https = __webpack_require__(50);
9298 var http = __webpack_require__(51);
9299 var HttpProxyAgent = __webpack_require__(52);
9300 var HttpsProxyAgent = __webpack_require__(69);
9301 var zlib = __webpack_require__(75);
9302 var nls = __webpack_require__(76);
9303 nls.config(process.env['VSCODE_NLS_CONFIG']);
9304 var localize = nls.loadMessageBundle();
9305 var proxyUrl = null;
9306 var strictSSL = true;
9307 function configure(_proxyUrl, _strictSSL) {
9308 proxyUrl = _proxyUrl;
9309 strictSSL = _strictSSL;
9311 exports.configure = configure;
9312 function xhr(options) {
9313 var agent = getProxyAgent(options.url, { proxyUrl: proxyUrl, strictSSL: strictSSL });
9314 options = assign({}, options);
9315 options = assign(options, { agent: agent, strictSSL: strictSSL });
9316 if (typeof options.followRedirects !== 'number') {
9317 options.followRedirects = 5;
9319 return request(options).then(function (result) { return new Promise(function (c, e) {
9320 var res = result.res;
9322 var encoding = res.headers && res.headers['content-encoding'];
9323 var isCompleted = false;
9324 if (encoding === 'gzip') {
9325 var gunzip = zlib.createGunzip();
9329 else if (encoding === 'deflate') {
9330 var inflate = zlib.createInflate();
9335 readable.on('data', function (c) { return data.push(c); });
9336 readable.on('end', function () {
9341 if (options.followRedirects > 0 && (res.statusCode >= 300 && res.statusCode <= 303 || res.statusCode === 307)) {
9342 var location = res.headers['location'];
9345 type: options.type, url: location, user: options.user, password: options.password, responseType: options.responseType, headers: options.headers,
9346 timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data
9348 xhr(newOptions).then(c, e);
9353 responseText: data.join(''),
9354 status: res.statusCode
9356 if ((res.statusCode >= 200 && res.statusCode < 300) || res.statusCode === 1223) {
9363 readable.on('error', function (err) {
9365 responseText: localize('error', 'Unable to access {0}. Error: {1}', options.url, err.message),
9371 }); }, function (err) {
9374 message = localize('error.cannot.connect.proxy', 'Unable to connect to {0} through a proxy . Error: {1}', options.url, err.message);
9377 message = localize('error.cannot.connect', 'Unable to connect to {0}. Error: {1}', options.url, err.message);
9379 return Promise.reject({
9380 responseText: message,
9386 function assign(destination) {
9388 for (var _i = 1; _i < arguments.length; _i++) {
9389 sources[_i - 1] = arguments[_i];
9391 sources.forEach(function (source) { return Object.keys(source).forEach(function (key) { return destination[key] = source[key]; }); });
9394 function request(options) {
9396 return new Promise(function (c, e) {
9397 var endpoint = url_1.parse(options.url);
9399 hostname: endpoint.hostname,
9400 port: endpoint.port ? parseInt(endpoint.port) : (endpoint.protocol === 'https:' ? 443 : 80),
9401 path: endpoint.path,
9402 method: options.type || 'GET',
9403 headers: options.headers,
9404 agent: options.agent,
9405 rejectUnauthorized: (typeof options.strictSSL === 'boolean') ? options.strictSSL : true
9407 if (options.user && options.password) {
9408 opts.auth = options.user + ':' + options.password;
9410 var handler = function (res) {
9411 if (res.statusCode >= 300 && res.statusCode < 400 && options.followRedirects && options.followRedirects > 0 && res.headers['location']) {
9412 c(request(assign({}, options, {
9413 url: res.headers['location'],
9414 followRedirects: options.followRedirects - 1
9418 c({ req: req, res: res });
9421 if (endpoint.protocol === 'https:') {
9422 req = https.request(opts, handler);
9425 req = http.request(opts, handler);
9428 if (options.timeout) {
9429 req.setTimeout(options.timeout);
9432 req.write(options.data);
9437 function getErrorStatusDescription(status) {
9442 case 400: return localize('status.400', 'Bad request. The request cannot be fulfilled due to bad syntax.');
9443 case 401: return localize('status.401', 'Unauthorized. The server is refusing to respond.');
9444 case 403: return localize('status.403', 'Forbidden. The server is refusing to respond.');
9445 case 404: return localize('status.404', 'Not Found. The requested location could not be found.');
9446 case 405: return localize('status.405', 'Method not allowed. A request was made using a request method not supported by that location.');
9447 case 406: return localize('status.406', 'Not Acceptable. The server can only generate a response that is not accepted by the client.');
9448 case 407: return localize('status.407', 'Proxy Authentication Required. The client must first authenticate itself with the proxy.');
9449 case 408: return localize('status.408', 'Request Timeout. The server timed out waiting for the request.');
9450 case 409: return localize('status.409', 'Conflict. The request could not be completed because of a conflict in the request.');
9451 case 410: return localize('status.410', 'Gone. The requested page is no longer available.');
9452 case 411: return localize('status.411', 'Length Required. The "Content-Length" is not defined.');
9453 case 412: return localize('status.412', 'Precondition Failed. The precondition given in the request evaluated to false by the server.');
9454 case 413: return localize('status.413', 'Request Entity Too Large. The server will not accept the request, because the request entity is too large.');
9455 case 414: return localize('status.414', 'Request-URI Too Long. The server will not accept the request, because the URL is too long.');
9456 case 415: return localize('status.415', 'Unsupported Media Type. The server will not accept the request, because the media type is not supported.');
9457 case 500: return localize('status.500', 'Internal Server Error.');
9458 case 501: return localize('status.501', 'Not Implemented. The server either does not recognize the request method, or it lacks the ability to fulfill the request.');
9459 case 503: return localize('status.503', 'Service Unavailable. The server is currently unavailable (overloaded or down).');
9460 default: return localize('status.416', 'HTTP status code {0}', status);
9463 exports.getErrorStatusDescription = getErrorStatusDescription;
9465 function getSystemProxyURI(requestURL) {
9466 if (requestURL.protocol === 'http:') {
9467 return process.env.HTTP_PROXY || process.env.http_proxy || null;
9469 else if (requestURL.protocol === 'https:') {
9470 return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null;
9474 function getProxyAgent(rawRequestURL, options) {
9475 if (options === void 0) { options = {}; }
9476 var requestURL = url_1.parse(rawRequestURL);
9477 var proxyURL = options.proxyUrl || getSystemProxyURI(requestURL);
9481 var proxyEndpoint = url_1.parse(proxyURL);
9482 if (!/^https?:$/.test(proxyEndpoint.protocol)) {
9486 host: proxyEndpoint.hostname,
9487 port: Number(proxyEndpoint.port),
9488 auth: proxyEndpoint.auth,
9489 rejectUnauthorized: (typeof options.strictSSL === 'boolean') ? options.strictSSL : true
9491 return requestURL.protocol === 'http:' ? new HttpProxyAgent(opts) : new HttpsProxyAgent(opts);
9493 //# sourceMappingURL=main.js.map
9497 /***/ (function(module, exports) {
9499 module.exports = require("https");
9503 /***/ (function(module, exports) {
9505 module.exports = require("http");
9509 /***/ (function(module, exports, __webpack_require__) {
9513 * Module dependencies.
9516 var net = __webpack_require__(15);
9517 var tls = __webpack_require__(53);
9518 var url = __webpack_require__(40);
9519 var Agent = __webpack_require__(54);
9520 var inherits = __webpack_require__(56).inherits;
9521 var debug = __webpack_require__(61)('http-proxy-agent');
9527 module.exports = HttpProxyAgent;
9530 * The `HttpProxyAgent` implements an HTTP Agent subclass that connects to the
9531 * specified "HTTP proxy server" in order to proxy HTTP requests.
9536 function HttpProxyAgent (opts) {
9537 if (!(this instanceof HttpProxyAgent)) return new HttpProxyAgent(opts);
9538 if ('string' == typeof opts) opts = url.parse(opts);
9539 if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
9540 debug('creating new HttpProxyAgent instance: %o', opts);
9541 Agent.call(this, opts);
9543 var proxy = Object.assign({}, opts);
9545 // if `true`, then connect to the proxy server over TLS. defaults to `false`.
9546 this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;
9548 // prefer `hostname` over `host`, and set the `port` if needed
9549 proxy.host = proxy.hostname || proxy.host;
9550 proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);
9552 if (proxy.host && proxy.path) {
9553 // if both a `host` and `path` are specified then it's most likely the
9554 // result of a `url.parse()` call... we need to remove the `path` portion so
9555 // that `net.connect()` doesn't attempt to open that as a unix socket file.
9557 delete proxy.pathname;
9562 inherits(HttpProxyAgent, Agent);
9565 * Called when the node-core HTTP client library is creating a new HTTP request.
9570 HttpProxyAgent.prototype.callback = function connect (req, opts, fn) {
9571 var proxy = this.proxy;
9573 // change the `http.ClientRequest` instance's "path" field
9574 // to the absolute path of the URL that will be requested
9575 var parsed = url.parse(req.path);
9576 if (null == parsed.protocol) parsed.protocol = 'http:';
9577 if (null == parsed.hostname) parsed.hostname = opts.hostname || opts.host;
9578 if (null == parsed.port) parsed.port = opts.port;
9579 if (parsed.port == 80) {
9580 // if port is 80, then we can remove the port so that the
9581 // ":80" portion is not on the produced URL
9584 var absolute = url.format(parsed);
9585 req.path = absolute;
9587 // inject the `Proxy-Authorization` header if necessary
9590 'Proxy-Authorization',
9591 'Basic ' + Buffer.from(proxy.auth).toString('base64')
9595 // create a socket connection to the proxy server
9597 if (this.secureProxy) {
9598 socket = tls.connect(proxy);
9600 socket = net.connect(proxy);
9603 // at this point, the http ClientRequest's internal `_header` field might have
9604 // already been set. If this is the case then we'll need to re-generate the
9605 // string since we just changed the `req.path`
9607 debug('regenerating stored HTTP header string for request');
9609 req._implicitHeader();
9610 if (req.output && req.output.length > 0) {
9611 debug('patching connection write() output buffer with updated header');
9612 // the _header has already been queued to be written to the socket
9613 var first = req.output[0];
9614 var endOfHeaders = first.indexOf('\r\n\r\n') + 4;
9615 req.output[0] = req._header + first.substring(endOfHeaders);
9616 debug('output buffer: %o', req.output);
9626 /***/ (function(module, exports) {
9628 module.exports = require("tls");
9632 /***/ (function(module, exports, __webpack_require__) {
9636 __webpack_require__(55);
9637 const inherits = __webpack_require__(56).inherits;
9638 const promisify = __webpack_require__(57);
9639 const EventEmitter = __webpack_require__(60).EventEmitter;
9641 module.exports = Agent;
9643 function isAgent(v) {
9644 return v && typeof v.addRequest === 'function';
9648 * Base `http.Agent` implementation.
9649 * No pooling/keep-alive is implemented by default.
9651 * @param {Function} callback
9654 function Agent(callback, _opts) {
9655 if (!(this instanceof Agent)) {
9656 return new Agent(callback, _opts);
9659 EventEmitter.call(this);
9661 // The callback gets promisified if it has 3 parameters
9662 // (i.e. it has a callback function) lazily
9663 this._promisifiedCallback = false;
9666 if ('function' === typeof callback) {
9667 this.callback = callback;
9668 } else if (callback) {
9672 // timeout for the socket to be returned from the callback
9673 this.timeout = (opts && opts.timeout) || null;
9675 this.options = opts;
9677 inherits(Agent, EventEmitter);
9680 * Override this function in your subclass!
9682 Agent.prototype.callback = function callback(req, opts) {
9684 '"agent-base" has no default implementation, you must subclass and override `callback()`'
9689 * Called by node-core's "_http_client.js" module when creating
9690 * a new HTTP request with this Agent instance.
9694 Agent.prototype.addRequest = function addRequest(req, _opts) {
9695 const ownOpts = Object.assign({}, _opts);
9697 // Set default `host` for HTTP to localhost
9698 if (null == ownOpts.host) {
9699 ownOpts.host = 'localhost';
9702 // Set default `port` for HTTP if none was explicitly specified
9703 if (null == ownOpts.port) {
9704 ownOpts.port = ownOpts.secureEndpoint ? 443 : 80;
9707 const opts = Object.assign({}, this.options, ownOpts);
9709 if (opts.host && opts.path) {
9710 // If both a `host` and `path` are specified then it's most likely the
9711 // result of a `url.parse()` call... we need to remove the `path` portion so
9712 // that `net.connect()` doesn't attempt to open that as a unix socket file.
9717 delete opts.hostname;
9718 delete opts._defaultAgent;
9719 delete opts.defaultPort;
9720 delete opts.createConnection;
9722 // Hint to use "Connection: close"
9723 // XXX: non-documented `http` module API :(
9725 req.shouldKeepAlive = false;
9727 // Create the `stream.Duplex` instance
9729 let timedOut = false;
9730 const timeoutMs = this.timeout;
9731 const freeSocket = this.freeSocket;
9733 function onerror(err) {
9734 if (req._hadError) return;
9735 req.emit('error', err);
9736 // For Safety. Some additional errors might fire later on
9737 // and we need to make sure we don't double-fire the error event.
9738 req._hadError = true;
9741 function ontimeout() {
9744 const err = new Error(
9745 'A "socket" was not created for HTTP request before ' + timeoutMs + 'ms'
9747 err.code = 'ETIMEOUT';
9751 function callbackError(err) {
9752 if (timedOut) return;
9753 if (timeout != null) {
9754 clearTimeout(timeout);
9760 function onsocket(socket) {
9761 if (timedOut) return;
9762 if (timeout != null) {
9763 clearTimeout(timeout);
9766 if (isAgent(socket)) {
9767 // `socket` is actually an http.Agent instance, so relinquish
9768 // responsibility for this `req` to the Agent from here on
9769 socket.addRequest(req, opts);
9770 } else if (socket) {
9772 freeSocket(socket, opts);
9774 socket.on('free', onfree);
9775 req.onSocket(socket);
9777 const err = new Error(
9778 'no Duplex stream was returned to agent-base for `' + req.method + ' ' + req.path + '`'
9784 if (!this._promisifiedCallback && this.callback.length >= 3) {
9785 // Legacy callback function - convert to a Promise
9786 this.callback = promisify(this.callback, this);
9787 this._promisifiedCallback = true;
9790 if (timeoutMs > 0) {
9791 timeout = setTimeout(ontimeout, timeoutMs);
9795 Promise.resolve(this.callback(req, opts)).then(onsocket, callbackError);
9797 Promise.reject(err).catch(callbackError);
9801 Agent.prototype.freeSocket = function freeSocket(socket, opts) {
9802 // TODO reuse sockets
9809 /***/ (function(module, exports, __webpack_require__) {
9813 const url = __webpack_require__(40);
9814 const https = __webpack_require__(50);
9817 * This currently needs to be applied to all Node.js versions
9818 * in order to determine if the `req` is an HTTP or HTTPS request.
9820 * There is currently no PR attempting to move this property upstream.
9822 const patchMarker = "__agent_base_https_request_patched__";
9823 if (!https.request[patchMarker]) {
9824 https.request = (function(request) {
9825 return function(_options, cb) {
9827 if (typeof _options === 'string') {
9828 options = url.parse(_options);
9830 options = Object.assign({}, _options);
9832 if (null == options.port) {
9835 options.secureEndpoint = true;
9836 return request.call(https, options, cb);
9839 https.request[patchMarker] = true;
9843 * This is needed for Node.js >= 9.0.0 to make sure `https.get()` uses the
9844 * patched `https.request()`.
9846 * Ref: https://github.com/nodejs/node/commit/5118f31
9848 https.get = function (_url, _options, cb) {
9850 if (typeof _url === 'string' && _options && typeof _options !== 'function') {
9851 options = Object.assign({}, url.parse(_url), _options);
9852 } else if (!_options && !cb) {
9859 const req = https.request(options, cb);
9867 /***/ (function(module, exports) {
9869 module.exports = require("util");
9873 /***/ (function(module, exports, __webpack_require__) {
9878 /* global module, require */
9879 module.exports = function () {
9883 // Get a promise object. This may be native, or it may be polyfilled
9885 var ES6Promise = __webpack_require__(58);
9888 * thatLooksLikeAPromiseToMe()
9890 * Duck-types a promise.
9893 * @return {bool} True if this resembles a promise
9895 function thatLooksLikeAPromiseToMe(o) {
9896 return o && typeof o.then === "function" && typeof o.catch === "function";
9902 * Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into
9903 * an ES6-compatible Promise. Promisify provides a default callback of the form (error, result)
9904 * and rejects when `error` is truthy. You can also supply settings object as the second argument.
9906 * @param {function} original - The function to promisify
9907 * @param {object} settings - Settings object
9908 * @param {object} settings.thisArg - A `this` context to use. If not set, assume `settings` _is_ `thisArg`
9909 * @param {bool} settings.multiArgs - Should multiple arguments be returned as an array?
9910 * @return {function} A promisified version of `original`
9912 return function promisify(original, settings) {
9914 return function () {
9915 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
9916 args[_key] = arguments[_key];
9919 var returnMultipleArguments = settings && settings.multiArgs;
9921 var target = void 0;
9922 if (settings && settings.thisArg) {
9923 target = settings.thisArg;
9924 } else if (settings) {
9928 // Return the promisified function
9929 return new ES6Promise(function (resolve, reject) {
9931 // Append the callback bound to the context
9932 args.push(function callback(err) {
9938 for (var _len2 = arguments.length, values = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
9939 values[_key2 - 1] = arguments[_key2];
9942 if (false === !!returnMultipleArguments) {
9943 return resolve(values[0]);
9949 // Call the function
9950 var response = original.apply(target, args);
9952 // If it looks like original already returns a promise,
9953 // then just resolve with that promise. Hopefully, the callback function we added will just be ignored.
9954 if (thatLooksLikeAPromiseToMe(response)) {
9964 /***/ (function(module, exports, __webpack_require__) {
9969 /* global self, window, module, global, require */
9970 module.exports = function () {
9974 var globalObject = void 0;
9976 function isFunction(x) {
9977 return typeof x === "function";
9980 // Seek the global object
9981 if (global !== undefined) {
9982 globalObject = global;
9983 } else if (window !== undefined && window.document) {
9984 globalObject = window;
9986 globalObject = self;
9989 // Test for any native promise implementation, and if that
9990 // implementation appears to conform to the specificaton.
9991 // This code mostly nicked from the es6-promise module polyfill
9992 // and then fooled with.
9993 var hasPromiseSupport = function () {
9995 // No promise object at all, and it's a non-starter
9996 if (!globalObject.hasOwnProperty("Promise")) {
10000 // There is a Promise object. Does it conform to the spec?
10001 var P = globalObject.Promise;
10003 // Some of these methods are missing from
10004 // Firefox/Chrome experimental implementations
10005 if (!P.hasOwnProperty("resolve") || !P.hasOwnProperty("reject")) {
10009 if (!P.hasOwnProperty("all") || !P.hasOwnProperty("race")) {
10013 // Older version of the spec had a resolver object
10014 // as the arg rather than a function
10015 return function () {
10017 var resolve = void 0;
10019 var p = new globalObject.Promise(function (r) {
10024 return isFunction(resolve);
10031 // Export the native Promise implementation if it
10032 // looks like it matches the spec
10033 if (hasPromiseSupport) {
10034 return globalObject.Promise;
10037 // Otherwise, return the es6-promise polyfill by @jaffathecake.
10038 return __webpack_require__(59).Promise;
10043 /***/ (function(module, exports, __webpack_require__) {
10046 * @overview es6-promise - a tiny implementation of Promises/A+.
10047 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
10048 * @license Licensed under MIT license
10049 * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
10050 * @version v4.2.8+1e68dce6
10053 (function (global, factory) {
10054 true ? module.exports = factory() :
10056 }(this, (function () { 'use strict';
10058 function objectOrFunction(x) {
10059 var type = typeof x;
10060 return x !== null && (type === 'object' || type === 'function');
10063 function isFunction(x) {
10064 return typeof x === 'function';
10069 var _isArray = void 0;
10070 if (Array.isArray) {
10071 _isArray = Array.isArray;
10073 _isArray = function (x) {
10074 return Object.prototype.toString.call(x) === '[object Array]';
10078 var isArray = _isArray;
10081 var vertxNext = void 0;
10082 var customSchedulerFn = void 0;
10084 var asap = function asap(callback, arg) {
10085 queue[len] = callback;
10086 queue[len + 1] = arg;
10089 // If len is 2, that means that we need to schedule an async flush.
10090 // If additional callbacks are queued before the queue is flushed, they
10091 // will be processed by this flush that we are scheduling.
10092 if (customSchedulerFn) {
10093 customSchedulerFn(flush);
10100 function setScheduler(scheduleFn) {
10101 customSchedulerFn = scheduleFn;
10104 function setAsap(asapFn) {
10108 var browserWindow = typeof window !== 'undefined' ? window : undefined;
10109 var browserGlobal = browserWindow || {};
10110 var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
10111 var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
10113 // test for web worker but not in IE10
10114 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
10117 function useNextTick() {
10118 // node version 0.10.x displays a deprecation warning when nextTick is used recursively
10119 // see https://github.com/cujojs/when/issues/410 for details
10120 return function () {
10121 return process.nextTick(flush);
10126 function useVertxTimer() {
10127 if (typeof vertxNext !== 'undefined') {
10128 return function () {
10133 return useSetTimeout();
10136 function useMutationObserver() {
10137 var iterations = 0;
10138 var observer = new BrowserMutationObserver(flush);
10139 var node = document.createTextNode('');
10140 observer.observe(node, { characterData: true });
10142 return function () {
10143 node.data = iterations = ++iterations % 2;
10148 function useMessageChannel() {
10149 var channel = new MessageChannel();
10150 channel.port1.onmessage = flush;
10151 return function () {
10152 return channel.port2.postMessage(0);
10156 function useSetTimeout() {
10157 // Store setTimeout reference so es6-promise will be unaffected by
10158 // other code modifying setTimeout (like sinon.useFakeTimers())
10159 var globalSetTimeout = setTimeout;
10160 return function () {
10161 return globalSetTimeout(flush, 1);
10165 var queue = new Array(1000);
10167 for (var i = 0; i < len; i += 2) {
10168 var callback = queue[i];
10169 var arg = queue[i + 1];
10173 queue[i] = undefined;
10174 queue[i + 1] = undefined;
10180 function attemptVertx() {
10182 var vertx = Function('return this')().require('vertx');
10183 vertxNext = vertx.runOnLoop || vertx.runOnContext;
10184 return useVertxTimer();
10186 return useSetTimeout();
10190 var scheduleFlush = void 0;
10191 // Decide what async method to use to triggering processing of queued callbacks:
10193 scheduleFlush = useNextTick();
10194 } else if (BrowserMutationObserver) {
10195 scheduleFlush = useMutationObserver();
10196 } else if (isWorker) {
10197 scheduleFlush = useMessageChannel();
10198 } else if (browserWindow === undefined && "function" === 'function') {
10199 scheduleFlush = attemptVertx();
10201 scheduleFlush = useSetTimeout();
10204 function then(onFulfillment, onRejection) {
10207 var child = new this.constructor(noop);
10209 if (child[PROMISE_ID] === undefined) {
10210 makePromise(child);
10213 var _state = parent._state;
10217 var callback = arguments[_state - 1];
10219 return invokeCallback(_state, child, callback, parent._result);
10222 subscribe(parent, child, onFulfillment, onRejection);
10229 `Promise.resolve` returns a promise that will become resolved with the
10230 passed `value`. It is shorthand for the following:
10233 let promise = new Promise(function(resolve, reject){
10237 promise.then(function(value){
10242 Instead of writing the above, your code now simply becomes the following:
10245 let promise = Promise.resolve(1);
10247 promise.then(function(value){
10254 @param {Any} value value that the returned promise will be resolved with
10255 Useful for tooling.
10256 @return {Promise} a promise that will become fulfilled with the given
10259 function resolve$1(object) {
10260 /*jshint validthis:true */
10261 var Constructor = this;
10263 if (object && typeof object === 'object' && object.constructor === Constructor) {
10267 var promise = new Constructor(noop);
10268 resolve(promise, object);
10272 var PROMISE_ID = Math.random().toString(36).substring(2);
10276 var PENDING = void 0;
10280 function selfFulfillment() {
10281 return new TypeError("You cannot resolve a promise with itself");
10284 function cannotReturnOwn() {
10285 return new TypeError('A promises callback cannot return that same promise.');
10288 function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
10290 then$$1.call(value, fulfillmentHandler, rejectionHandler);
10296 function handleForeignThenable(promise, thenable, then$$1) {
10297 asap(function (promise) {
10298 var sealed = false;
10299 var error = tryThen(then$$1, thenable, function (value) {
10304 if (thenable !== value) {
10305 resolve(promise, value);
10307 fulfill(promise, value);
10309 }, function (reason) {
10315 reject(promise, reason);
10316 }, 'Settle: ' + (promise._label || ' unknown promise'));
10318 if (!sealed && error) {
10320 reject(promise, error);
10325 function handleOwnThenable(promise, thenable) {
10326 if (thenable._state === FULFILLED) {
10327 fulfill(promise, thenable._result);
10328 } else if (thenable._state === REJECTED) {
10329 reject(promise, thenable._result);
10331 subscribe(thenable, undefined, function (value) {
10332 return resolve(promise, value);
10333 }, function (reason) {
10334 return reject(promise, reason);
10339 function handleMaybeThenable(promise, maybeThenable, then$$1) {
10340 if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
10341 handleOwnThenable(promise, maybeThenable);
10343 if (then$$1 === undefined) {
10344 fulfill(promise, maybeThenable);
10345 } else if (isFunction(then$$1)) {
10346 handleForeignThenable(promise, maybeThenable, then$$1);
10348 fulfill(promise, maybeThenable);
10353 function resolve(promise, value) {
10354 if (promise === value) {
10355 reject(promise, selfFulfillment());
10356 } else if (objectOrFunction(value)) {
10357 var then$$1 = void 0;
10359 then$$1 = value.then;
10361 reject(promise, error);
10364 handleMaybeThenable(promise, value, then$$1);
10366 fulfill(promise, value);
10370 function publishRejection(promise) {
10371 if (promise._onerror) {
10372 promise._onerror(promise._result);
10378 function fulfill(promise, value) {
10379 if (promise._state !== PENDING) {
10383 promise._result = value;
10384 promise._state = FULFILLED;
10386 if (promise._subscribers.length !== 0) {
10387 asap(publish, promise);
10391 function reject(promise, reason) {
10392 if (promise._state !== PENDING) {
10395 promise._state = REJECTED;
10396 promise._result = reason;
10398 asap(publishRejection, promise);
10401 function subscribe(parent, child, onFulfillment, onRejection) {
10402 var _subscribers = parent._subscribers;
10403 var length = _subscribers.length;
10406 parent._onerror = null;
10408 _subscribers[length] = child;
10409 _subscribers[length + FULFILLED] = onFulfillment;
10410 _subscribers[length + REJECTED] = onRejection;
10412 if (length === 0 && parent._state) {
10413 asap(publish, parent);
10417 function publish(promise) {
10418 var subscribers = promise._subscribers;
10419 var settled = promise._state;
10421 if (subscribers.length === 0) {
10425 var child = void 0,
10427 detail = promise._result;
10429 for (var i = 0; i < subscribers.length; i += 3) {
10430 child = subscribers[i];
10431 callback = subscribers[i + settled];
10434 invokeCallback(settled, child, callback, detail);
10440 promise._subscribers.length = 0;
10443 function invokeCallback(settled, promise, callback, detail) {
10444 var hasCallback = isFunction(callback),
10451 value = callback(detail);
10457 if (promise === value) {
10458 reject(promise, cannotReturnOwn());
10465 if (promise._state !== PENDING) {
10467 } else if (hasCallback && succeeded) {
10468 resolve(promise, value);
10469 } else if (succeeded === false) {
10470 reject(promise, error);
10471 } else if (settled === FULFILLED) {
10472 fulfill(promise, value);
10473 } else if (settled === REJECTED) {
10474 reject(promise, value);
10478 function initializePromise(promise, resolver) {
10480 resolver(function resolvePromise(value) {
10481 resolve(promise, value);
10482 }, function rejectPromise(reason) {
10483 reject(promise, reason);
10486 reject(promise, e);
10491 function nextId() {
10495 function makePromise(promise) {
10496 promise[PROMISE_ID] = id++;
10497 promise._state = undefined;
10498 promise._result = undefined;
10499 promise._subscribers = [];
10502 function validationError() {
10503 return new Error('Array Methods must be provided an Array');
10506 var Enumerator = function () {
10507 function Enumerator(Constructor, input) {
10508 this._instanceConstructor = Constructor;
10509 this.promise = new Constructor(noop);
10511 if (!this.promise[PROMISE_ID]) {
10512 makePromise(this.promise);
10515 if (isArray(input)) {
10516 this.length = input.length;
10517 this._remaining = input.length;
10519 this._result = new Array(this.length);
10521 if (this.length === 0) {
10522 fulfill(this.promise, this._result);
10524 this.length = this.length || 0;
10525 this._enumerate(input);
10526 if (this._remaining === 0) {
10527 fulfill(this.promise, this._result);
10531 reject(this.promise, validationError());
10535 Enumerator.prototype._enumerate = function _enumerate(input) {
10536 for (var i = 0; this._state === PENDING && i < input.length; i++) {
10537 this._eachEntry(input[i], i);
10541 Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
10542 var c = this._instanceConstructor;
10543 var resolve$$1 = c.resolve;
10546 if (resolve$$1 === resolve$1) {
10547 var _then = void 0;
10548 var error = void 0;
10549 var didError = false;
10551 _then = entry.then;
10557 if (_then === then && entry._state !== PENDING) {
10558 this._settledAt(entry._state, i, entry._result);
10559 } else if (typeof _then !== 'function') {
10561 this._result[i] = entry;
10562 } else if (c === Promise$1) {
10563 var promise = new c(noop);
10565 reject(promise, error);
10567 handleMaybeThenable(promise, entry, _then);
10569 this._willSettleAt(promise, i);
10571 this._willSettleAt(new c(function (resolve$$1) {
10572 return resolve$$1(entry);
10576 this._willSettleAt(resolve$$1(entry), i);
10580 Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
10581 var promise = this.promise;
10584 if (promise._state === PENDING) {
10587 if (state === REJECTED) {
10588 reject(promise, value);
10590 this._result[i] = value;
10594 if (this._remaining === 0) {
10595 fulfill(promise, this._result);
10599 Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
10600 var enumerator = this;
10602 subscribe(promise, undefined, function (value) {
10603 return enumerator._settledAt(FULFILLED, i, value);
10604 }, function (reason) {
10605 return enumerator._settledAt(REJECTED, i, reason);
10613 `Promise.all` accepts an array of promises, and returns a new promise which
10614 is fulfilled with an array of fulfillment values for the passed promises, or
10615 rejected with the reason of the first passed promise to be rejected. It casts all
10616 elements of the passed iterable to promises as it runs this algorithm.
10621 let promise1 = resolve(1);
10622 let promise2 = resolve(2);
10623 let promise3 = resolve(3);
10624 let promises = [ promise1, promise2, promise3 ];
10626 Promise.all(promises).then(function(array){
10627 // The array here would be [ 1, 2, 3 ];
10631 If any of the `promises` given to `all` are rejected, the first promise
10632 that is rejected will be given as an argument to the returned promises's
10633 rejection handler. For example:
10638 let promise1 = resolve(1);
10639 let promise2 = reject(new Error("2"));
10640 let promise3 = reject(new Error("3"));
10641 let promises = [ promise1, promise2, promise3 ];
10643 Promise.all(promises).then(function(array){
10644 // Code here never runs because there are rejected promises!
10645 }, function(error) {
10646 // error.message === "2"
10652 @param {Array} entries array of promises
10653 @param {String} label optional string for labeling the promise.
10654 Useful for tooling.
10655 @return {Promise} promise that is fulfilled when all `promises` have been
10656 fulfilled, or rejected if any of them become rejected.
10659 function all(entries) {
10660 return new Enumerator(this, entries).promise;
10664 `Promise.race` returns a new promise which is settled in the same way as the
10665 first passed promise to settle.
10670 let promise1 = new Promise(function(resolve, reject){
10671 setTimeout(function(){
10672 resolve('promise 1');
10676 let promise2 = new Promise(function(resolve, reject){
10677 setTimeout(function(){
10678 resolve('promise 2');
10682 Promise.race([promise1, promise2]).then(function(result){
10683 // result === 'promise 2' because it was resolved before promise1
10688 `Promise.race` is deterministic in that only the state of the first
10689 settled promise matters. For example, even if other promises given to the
10690 `promises` array argument are resolved, but the first settled promise has
10691 become rejected before the other promises became fulfilled, the returned
10692 promise will become rejected:
10695 let promise1 = new Promise(function(resolve, reject){
10696 setTimeout(function(){
10697 resolve('promise 1');
10701 let promise2 = new Promise(function(resolve, reject){
10702 setTimeout(function(){
10703 reject(new Error('promise 2'));
10707 Promise.race([promise1, promise2]).then(function(result){
10708 // Code here never runs
10709 }, function(reason){
10710 // reason.message === 'promise 2' because promise 2 became rejected before
10711 // promise 1 became fulfilled
10715 An example real-world use case is implementing timeouts:
10718 Promise.race([ajax('foo.json'), timeout(5000)])
10723 @param {Array} promises array of promises to observe
10724 Useful for tooling.
10725 @return {Promise} a promise which settles in the same way as the first passed
10728 function race(entries) {
10729 /*jshint validthis:true */
10730 var Constructor = this;
10732 if (!isArray(entries)) {
10733 return new Constructor(function (_, reject) {
10734 return reject(new TypeError('You must pass an array to race.'));
10737 return new Constructor(function (resolve, reject) {
10738 var length = entries.length;
10739 for (var i = 0; i < length; i++) {
10740 Constructor.resolve(entries[i]).then(resolve, reject);
10747 `Promise.reject` returns a promise rejected with the passed `reason`.
10748 It is shorthand for the following:
10751 let promise = new Promise(function(resolve, reject){
10752 reject(new Error('WHOOPS'));
10755 promise.then(function(value){
10756 // Code here doesn't run because the promise is rejected!
10757 }, function(reason){
10758 // reason.message === 'WHOOPS'
10762 Instead of writing the above, your code now simply becomes the following:
10765 let promise = Promise.reject(new Error('WHOOPS'));
10767 promise.then(function(value){
10768 // Code here doesn't run because the promise is rejected!
10769 }, function(reason){
10770 // reason.message === 'WHOOPS'
10776 @param {Any} reason value that the returned promise will be rejected with.
10777 Useful for tooling.
10778 @return {Promise} a promise rejected with the given `reason`.
10780 function reject$1(reason) {
10781 /*jshint validthis:true */
10782 var Constructor = this;
10783 var promise = new Constructor(noop);
10784 reject(promise, reason);
10788 function needsResolver() {
10789 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
10792 function needsNew() {
10793 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
10797 Promise objects represent the eventual result of an asynchronous operation. The
10798 primary way of interacting with a promise is through its `then` method, which
10799 registers callbacks to receive either a promise's eventual value or the reason
10800 why the promise cannot be fulfilled.
10805 - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
10806 - `thenable` is an object or function that defines a `then` method.
10807 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
10808 - `exception` is a value that is thrown using the throw statement.
10809 - `reason` is a value that indicates why a promise was rejected.
10810 - `settled` the final resting state of a promise, fulfilled or rejected.
10812 A promise can be in one of three states: pending, fulfilled, or rejected.
10814 Promises that are fulfilled have a fulfillment value and are in the fulfilled
10815 state. Promises that are rejected have a rejection reason and are in the
10816 rejected state. A fulfillment value is never a thenable.
10818 Promises can also be said to *resolve* a value. If this value is also a
10819 promise, then the original promise's settled state will match the value's
10820 settled state. So a promise that *resolves* a promise that rejects will
10821 itself reject, and a promise that *resolves* a promise that fulfills will
10829 let promise = new Promise(function(resolve, reject) {
10837 promise.then(function(value) {
10839 }, function(reason) {
10847 Promises shine when abstracting away asynchronous interactions such as
10851 function getJSON(url) {
10852 return new Promise(function(resolve, reject){
10853 let xhr = new XMLHttpRequest();
10855 xhr.open('GET', url);
10856 xhr.onreadystatechange = handler;
10857 xhr.responseType = 'json';
10858 xhr.setRequestHeader('Accept', 'application/json');
10861 function handler() {
10862 if (this.readyState === this.DONE) {
10863 if (this.status === 200) {
10864 resolve(this.response);
10866 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
10873 getJSON('/posts.json').then(function(json) {
10875 }, function(reason) {
10880 Unlike callbacks, promises are great composable primitives.
10885 getJSON('/comments')
10886 ]).then(function(values){
10887 values[0] // => postsJSON
10888 values[1] // => commentsJSON
10895 @param {Function} resolver
10896 Useful for tooling.
10900 var Promise$1 = function () {
10901 function Promise(resolver) {
10902 this[PROMISE_ID] = nextId();
10903 this._result = this._state = undefined;
10904 this._subscribers = [];
10906 if (noop !== resolver) {
10907 typeof resolver !== 'function' && needsResolver();
10908 this instanceof Promise ? initializePromise(this, resolver) : needsNew();
10913 The primary way of interacting with a promise is through its `then` method,
10914 which registers callbacks to receive either a promise's eventual value or the
10915 reason why the promise cannot be fulfilled.
10917 findUser().then(function(user){
10918 // user is available
10919 }, function(reason){
10920 // user is unavailable, and you are given the reason why
10925 The return value of `then` is itself a promise. This second, 'downstream'
10926 promise is resolved with the return value of the first promise's fulfillment
10927 or rejection handler, or rejected if the handler throws an exception.
10929 findUser().then(function (user) {
10931 }, function (reason) {
10932 return 'default name';
10933 }).then(function (userName) {
10934 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
10935 // will be `'default name'`
10937 findUser().then(function (user) {
10938 throw new Error('Found user, but still unhappy');
10939 }, function (reason) {
10940 throw new Error('`findUser` rejected and we're unhappy');
10941 }).then(function (value) {
10943 }, function (reason) {
10944 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
10945 // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
10948 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
10950 findUser().then(function (user) {
10951 throw new PedagogicalException('Upstream error');
10952 }).then(function (value) {
10954 }).then(function (value) {
10956 }, function (reason) {
10957 // The `PedgagocialException` is propagated all the way down to here
10962 Sometimes the value you want to propagate to a downstream promise can only be
10963 retrieved asynchronously. This can be achieved by returning a promise in the
10964 fulfillment or rejection handler. The downstream promise will then be pending
10965 until the returned promise is settled. This is called *assimilation*.
10967 findUser().then(function (user) {
10968 return findCommentsByAuthor(user);
10969 }).then(function (comments) {
10970 // The user's comments are now available
10973 If the assimliated promise rejects, then the downstream promise will also reject.
10975 findUser().then(function (user) {
10976 return findCommentsByAuthor(user);
10977 }).then(function (comments) {
10978 // If `findCommentsByAuthor` fulfills, we'll have the value here
10979 }, function (reason) {
10980 // If `findCommentsByAuthor` rejects, we'll have the reason here
10985 Synchronous Example
10989 result = findResult();
10997 findResult(function(result, err){
11007 findResult().then(function(result){
11009 }, function(reason){
11015 Synchronous Example
11019 author = findAuthor();
11020 books = findBooksByAuthor(author);
11028 function foundBooks(books) {
11030 function failure(reason) {
11032 findAuthor(function(author, err){
11038 findBoooksByAuthor(author, function(books, err) {
11059 then(findBooksByAuthor).
11060 then(function(books){
11062 }).catch(function(reason){
11063 // something went wrong
11067 @param {Function} onFulfilled
11068 @param {Function} onRejected
11069 Useful for tooling.
11074 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
11075 as the catch block of a try/catch statement.
11077 function findAuthor(){
11078 throw new Error('couldn't find that author');
11084 // something went wrong
11086 // async with promises
11087 findAuthor().catch(function(reason){
11088 // something went wrong
11092 @param {Function} onRejection
11093 Useful for tooling.
11098 Promise.prototype.catch = function _catch(onRejection) {
11099 return this.then(null, onRejection);
11103 `finally` will be invoked regardless of the promise's fate just as native
11104 try/catch/finally behaves
11106 Synchronous example:
11110 if (Math.random() > 0.5) {
11113 return new Author();
11117 return findAuthor(); // succeed or fail
11119 return findOtherAuther();
11122 // doesn't affect the return value
11126 Asynchronous example:
11129 findAuthor().catch(function(reason){
11130 return findOtherAuther();
11131 }).finally(function(){
11132 // author was either found, or not
11137 @param {Function} callback
11142 Promise.prototype.finally = function _finally(callback) {
11143 var promise = this;
11144 var constructor = promise.constructor;
11146 if (isFunction(callback)) {
11147 return promise.then(function (value) {
11148 return constructor.resolve(callback()).then(function () {
11151 }, function (reason) {
11152 return constructor.resolve(callback()).then(function () {
11158 return promise.then(callback, callback);
11164 Promise$1.prototype.then = then;
11165 Promise$1.all = all;
11166 Promise$1.race = race;
11167 Promise$1.resolve = resolve$1;
11168 Promise$1.reject = reject$1;
11169 Promise$1._setScheduler = setScheduler;
11170 Promise$1._setAsap = setAsap;
11171 Promise$1._asap = asap;
11174 function polyfill() {
11175 var local = void 0;
11177 if (typeof global !== 'undefined') {
11179 } else if (typeof self !== 'undefined') {
11183 local = Function('return this')();
11185 throw new Error('polyfill failed because global object is unavailable in this environment');
11189 var P = local.Promise;
11192 var promiseToString = null;
11194 promiseToString = Object.prototype.toString.call(P.resolve());
11196 // silently ignored
11199 if (promiseToString === '[object Promise]' && !P.cast) {
11204 local.Promise = Promise$1;
11207 // Strange compat..
11208 Promise$1.polyfill = polyfill;
11209 Promise$1.Promise = Promise$1;
11217 //# sourceMappingURL=es6-promise.map
11222 /***/ (function(module, exports) {
11224 module.exports = require("events");
11228 /***/ (function(module, exports, __webpack_require__) {
11231 * Detect Electron renderer process, which is node, but we should
11232 * treat as a browser.
11235 if (typeof process === 'undefined' || process.type === 'renderer') {
11236 module.exports = __webpack_require__(62);
11238 module.exports = __webpack_require__(65);
11244 /***/ (function(module, exports, __webpack_require__) {
11247 * This is the web browser implementation of `debug()`.
11249 * Expose `debug()` as the module.
11252 exports = module.exports = __webpack_require__(63);
11254 exports.formatArgs = formatArgs;
11255 exports.save = save;
11256 exports.load = load;
11257 exports.useColors = useColors;
11258 exports.storage = 'undefined' != typeof chrome
11259 && 'undefined' != typeof chrome.storage
11260 ? chrome.storage.local
11268 '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',
11269 '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',
11270 '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',
11271 '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',
11272 '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',
11273 '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',
11274 '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',
11275 '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',
11276 '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',
11277 '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',
11278 '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'
11282 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
11283 * and the Firebug extension (any Firefox version) are known
11284 * to support "%c" CSS customizations.
11286 * TODO: add a `localStorage` variable to explicitly enable/disable colors
11289 function useColors() {
11290 // NB: In an Electron preload script, document will be defined but not fully
11291 // initialized. Since we know we're in Chrome, we'll just detect this case
11293 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
11297 // Internet Explorer and Edge do not support colors.
11298 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
11302 // is webkit? http://stackoverflow.com/a/16459606/376773
11303 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
11304 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
11305 // is firebug? http://stackoverflow.com/a/398120/376773
11306 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
11307 // is firefox >= v31?
11308 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
11309 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
11310 // double check webkit in userAgent just in case we are in a worker
11311 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
11315 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
11318 exports.formatters.j = function(v) {
11320 return JSON.stringify(v);
11322 return '[UnexpectedJSONParseError]: ' + err.message;
11328 * Colorize log arguments if enabled.
11333 function formatArgs(args) {
11334 var useColors = this.useColors;
11336 args[0] = (useColors ? '%c' : '')
11338 + (useColors ? ' %c' : ' ')
11340 + (useColors ? '%c ' : ' ')
11341 + '+' + exports.humanize(this.diff);
11343 if (!useColors) return;
11345 var c = 'color: ' + this.color;
11346 args.splice(1, 0, c, 'color: inherit')
11348 // the final "%c" is somewhat tricky, because there could be other
11349 // arguments passed either before or after the %c, so we need to
11350 // figure out the correct index to insert the CSS into
11353 args[0].replace(/%[a-zA-Z%]/g, function(match) {
11354 if ('%%' === match) return;
11356 if ('%c' === match) {
11357 // we only are interested in the *last* %c
11358 // (the user may have provided their own)
11363 args.splice(lastC, 0, c);
11367 * Invokes `console.log()` when available.
11368 * No-op when `console.log` is not a "function".
11374 // this hackery is required for IE8/9, where
11375 // the `console.log` function doesn't have 'apply'
11376 return 'object' === typeof console
11378 && Function.prototype.apply.call(console.log, console, arguments);
11382 * Save `namespaces`.
11384 * @param {String} namespaces
11388 function save(namespaces) {
11390 if (null == namespaces) {
11391 exports.storage.removeItem('debug');
11393 exports.storage.debug = namespaces;
11399 * Load `namespaces`.
11401 * @return {String} returns the previously persisted debug modes
11408 r = exports.storage.debug;
11411 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
11412 if (!r && typeof process !== 'undefined' && 'env' in process) {
11413 r = process.env.DEBUG;
11420 * Enable namespaces listed in `localStorage.debug` initially.
11423 exports.enable(load());
11426 * Localstorage attempts to return the localstorage.
11428 * This is necessary because safari throws
11429 * when a user disables cookies/localstorage
11430 * and you attempt to access it.
11432 * @return {LocalStorage}
11436 function localstorage() {
11438 return window.localStorage;
11445 /***/ (function(module, exports, __webpack_require__) {
11449 * This is the common logic for both the Node.js and web browser
11450 * implementations of `debug()`.
11452 * Expose `debug()` as the module.
11455 exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
11456 exports.coerce = coerce;
11457 exports.disable = disable;
11458 exports.enable = enable;
11459 exports.enabled = enabled;
11460 exports.humanize = __webpack_require__(64);
11463 * Active `debug` instances.
11465 exports.instances = [];
11468 * The currently active debug mode names, and names to skip.
11471 exports.names = [];
11472 exports.skips = [];
11475 * Map of special "%n" handling functions, for the debug "format" argument.
11477 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
11480 exports.formatters = {};
11484 * @param {String} namespace
11489 function selectColor(namespace) {
11492 for (i in namespace) {
11493 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
11494 hash |= 0; // Convert to 32bit integer
11497 return exports.colors[Math.abs(hash) % exports.colors.length];
11501 * Create a debugger with the given `namespace`.
11503 * @param {String} namespace
11504 * @return {Function}
11508 function createDebug(namespace) {
11514 if (!debug.enabled) return;
11518 // set `diff` timestamp
11519 var curr = +new Date();
11520 var ms = curr - (prevTime || curr);
11522 self.prev = prevTime;
11526 // turn the `arguments` into a proper Array
11527 var args = new Array(arguments.length);
11528 for (var i = 0; i < args.length; i++) {
11529 args[i] = arguments[i];
11532 args[0] = exports.coerce(args[0]);
11534 if ('string' !== typeof args[0]) {
11535 // anything else let's inspect with %O
11536 args.unshift('%O');
11539 // apply any `formatters` transformations
11541 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
11542 // if we encounter an escaped % then don't increase the array index
11543 if (match === '%%') return match;
11545 var formatter = exports.formatters[format];
11546 if ('function' === typeof formatter) {
11547 var val = args[index];
11548 match = formatter.call(self, val);
11550 // now we need to remove `args[index]` since it's inlined in the `format`
11551 args.splice(index, 1);
11557 // apply env-specific formatting (colors, etc.)
11558 exports.formatArgs.call(self, args);
11560 var logFn = debug.log || exports.log || console.log.bind(console);
11561 logFn.apply(self, args);
11564 debug.namespace = namespace;
11565 debug.enabled = exports.enabled(namespace);
11566 debug.useColors = exports.useColors();
11567 debug.color = selectColor(namespace);
11568 debug.destroy = destroy;
11570 // env-specific initialization logic for debug instances
11571 if ('function' === typeof exports.init) {
11572 exports.init(debug);
11575 exports.instances.push(debug);
11580 function destroy () {
11581 var index = exports.instances.indexOf(this);
11582 if (index !== -1) {
11583 exports.instances.splice(index, 1);
11591 * Enables a debug mode by namespaces. This can include modes
11592 * separated by a colon and wildcards.
11594 * @param {String} namespaces
11598 function enable(namespaces) {
11599 exports.save(namespaces);
11601 exports.names = [];
11602 exports.skips = [];
11605 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
11606 var len = split.length;
11608 for (i = 0; i < len; i++) {
11609 if (!split[i]) continue; // ignore empty strings
11610 namespaces = split[i].replace(/\*/g, '.*?');
11611 if (namespaces[0] === '-') {
11612 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
11614 exports.names.push(new RegExp('^' + namespaces + '$'));
11618 for (i = 0; i < exports.instances.length; i++) {
11619 var instance = exports.instances[i];
11620 instance.enabled = exports.enabled(instance.namespace);
11625 * Disable debug output.
11630 function disable() {
11631 exports.enable('');
11635 * Returns true if the given mode name is enabled, false otherwise.
11637 * @param {String} name
11638 * @return {Boolean}
11642 function enabled(name) {
11643 if (name[name.length - 1] === '*') {
11647 for (i = 0, len = exports.skips.length; i < len; i++) {
11648 if (exports.skips[i].test(name)) {
11652 for (i = 0, len = exports.names.length; i < len; i++) {
11653 if (exports.names[i].test(name)) {
11663 * @param {Mixed} val
11668 function coerce(val) {
11669 if (val instanceof Error) return val.stack || val.message;
11676 /***/ (function(module, exports) {
11686 var y = d * 365.25;
11689 * Parse or format the given `val`.
11693 * - `long` verbose formatting [false]
11695 * @param {String|Number} val
11696 * @param {Object} [options]
11697 * @throws {Error} throw an error if val is not a non-empty string or a number
11698 * @return {String|Number}
11702 module.exports = function(val, options) {
11703 options = options || {};
11704 var type = typeof val;
11705 if (type === 'string' && val.length > 0) {
11707 } else if (type === 'number' && isNaN(val) === false) {
11708 return options.long ? fmtLong(val) : fmtShort(val);
11711 'val is not a non-empty string or a valid number. val=' +
11712 JSON.stringify(val)
11717 * Parse the given `str` and return milliseconds.
11719 * @param {String} str
11724 function parse(str) {
11726 if (str.length > 100) {
11729 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
11735 var n = parseFloat(match[1]);
11736 var type = (match[2] || 'ms').toLowerCase();
11766 case 'milliseconds':
11767 case 'millisecond':
11778 * Short format for `ms`.
11780 * @param {Number} ms
11785 function fmtShort(ms) {
11787 return Math.round(ms / d) + 'd';
11790 return Math.round(ms / h) + 'h';
11793 return Math.round(ms / m) + 'm';
11796 return Math.round(ms / s) + 's';
11802 * Long format for `ms`.
11804 * @param {Number} ms
11809 function fmtLong(ms) {
11810 return plural(ms, d, 'day') ||
11811 plural(ms, h, 'hour') ||
11812 plural(ms, m, 'minute') ||
11813 plural(ms, s, 'second') ||
11818 * Pluralization helper.
11821 function plural(ms, n, name) {
11825 if (ms < n * 1.5) {
11826 return Math.floor(ms / n) + ' ' + name;
11828 return Math.ceil(ms / n) + ' ' + name + 's';
11834 /***/ (function(module, exports, __webpack_require__) {
11837 * Module dependencies.
11840 var tty = __webpack_require__(66);
11841 var util = __webpack_require__(56);
11844 * This is the Node.js implementation of `debug()`.
11846 * Expose `debug()` as the module.
11849 exports = module.exports = __webpack_require__(63);
11850 exports.init = init;
11852 exports.formatArgs = formatArgs;
11853 exports.save = save;
11854 exports.load = load;
11855 exports.useColors = useColors;
11861 exports.colors = [ 6, 2, 3, 4, 5, 1 ];
11864 var supportsColor = __webpack_require__(67);
11865 if (supportsColor && supportsColor.level >= 2) {
11867 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68,
11868 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134,
11869 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,
11870 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204,
11871 205, 206, 207, 208, 209, 214, 215, 220, 221
11875 // swallow - we only care if `supports-color` is available; it doesn't have to be.
11879 * Build up the default `inspectOpts` object from the environment variables.
11881 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
11884 exports.inspectOpts = Object.keys(process.env).filter(function (key) {
11885 return /^debug_/i.test(key);
11886 }).reduce(function (obj, key) {
11891 .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
11893 // coerce string value into JS value
11894 var val = process.env[key];
11895 if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
11896 else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
11897 else if (val === 'null') val = null;
11898 else val = Number(val);
11905 * Is stdout a TTY? Colored output is enabled when `true`.
11908 function useColors() {
11909 return 'colors' in exports.inspectOpts
11910 ? Boolean(exports.inspectOpts.colors)
11911 : tty.isatty(process.stderr.fd);
11915 * Map %o to `util.inspect()`, all on a single line.
11918 exports.formatters.o = function(v) {
11919 this.inspectOpts.colors = this.useColors;
11920 return util.inspect(v, this.inspectOpts)
11921 .split('\n').map(function(str) {
11927 * Map %o to `util.inspect()`, allowing multiple lines if needed.
11930 exports.formatters.O = function(v) {
11931 this.inspectOpts.colors = this.useColors;
11932 return util.inspect(v, this.inspectOpts);
11936 * Adds ANSI color escape codes if enabled.
11941 function formatArgs(args) {
11942 var name = this.namespace;
11943 var useColors = this.useColors;
11946 var c = this.color;
11947 var colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c);
11948 var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m';
11950 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
11951 args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
11953 args[0] = getDate() + name + ' ' + args[0];
11957 function getDate() {
11958 if (exports.inspectOpts.hideDate) {
11961 return new Date().toISOString() + ' ';
11966 * Invokes `util.format()` with the specified arguments and writes to stderr.
11970 return process.stderr.write(util.format.apply(util, arguments) + '\n');
11974 * Save `namespaces`.
11976 * @param {String} namespaces
11980 function save(namespaces) {
11981 if (null == namespaces) {
11982 // If you set a process.env field to null or undefined, it gets cast to the
11983 // string 'null' or 'undefined'. Just delete instead.
11984 delete process.env.DEBUG;
11986 process.env.DEBUG = namespaces;
11991 * Load `namespaces`.
11993 * @return {String} returns the previously persisted debug modes
11998 return process.env.DEBUG;
12002 * Init logic for `debug` instances.
12004 * Create a new `inspectOpts` object in case `useColors` is set
12005 * differently for a particular `debug` instance.
12008 function init (debug) {
12009 debug.inspectOpts = {};
12011 var keys = Object.keys(exports.inspectOpts);
12012 for (var i = 0; i < keys.length; i++) {
12013 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
12018 * Enable namespaces listed in `process.env.DEBUG` initially.
12021 exports.enable(load());
12026 /***/ (function(module, exports) {
12028 module.exports = require("tty");
12032 /***/ (function(module, exports, __webpack_require__) {
12036 const os = __webpack_require__(13);
12037 const hasFlag = __webpack_require__(68);
12039 const env = process.env;
12042 if (hasFlag('no-color') ||
12043 hasFlag('no-colors') ||
12044 hasFlag('color=false')) {
12045 forceColor = false;
12046 } else if (hasFlag('color') ||
12047 hasFlag('colors') ||
12048 hasFlag('color=true') ||
12049 hasFlag('color=always')) {
12052 if ('FORCE_COLOR' in env) {
12053 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
12056 function translateLevel(level) {
12064 has256: level >= 2,
12069 function supportsColor(stream) {
12070 if (forceColor === false) {
12074 if (hasFlag('color=16m') ||
12075 hasFlag('color=full') ||
12076 hasFlag('color=truecolor')) {
12080 if (hasFlag('color=256')) {
12084 if (stream && !stream.isTTY && forceColor !== true) {
12088 const min = forceColor ? 1 : 0;
12090 if (process.platform === 'win32') {
12091 // Node.js 7.5.0 is the first version of Node.js to include a patch to
12092 // libuv that enables 256 color output on Windows. Anything earlier and it
12093 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
12094 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
12095 // release that supports 256 colors. Windows 10 build 14931 is the first release
12096 // that supports 16m/TrueColor.
12097 const osRelease = os.release().split('.');
12099 Number(process.versions.node.split('.')[0]) >= 8 &&
12100 Number(osRelease[0]) >= 10 &&
12101 Number(osRelease[2]) >= 10586
12103 return Number(osRelease[2]) >= 14931 ? 3 : 2;
12110 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
12117 if ('TEAMCITY_VERSION' in env) {
12118 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
12121 if (env.COLORTERM === 'truecolor') {
12125 if ('TERM_PROGRAM' in env) {
12126 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
12128 switch (env.TERM_PROGRAM) {
12130 return version >= 3 ? 3 : 2;
12131 case 'Apple_Terminal':
12137 if (/-256(color)?$/i.test(env.TERM)) {
12141 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
12145 if ('COLORTERM' in env) {
12149 if (env.TERM === 'dumb') {
12156 function getSupportLevel(stream) {
12157 const level = supportsColor(stream);
12158 return translateLevel(level);
12162 supportsColor: getSupportLevel,
12163 stdout: getSupportLevel(process.stdout),
12164 stderr: getSupportLevel(process.stderr)
12170 /***/ (function(module, exports, __webpack_require__) {
12174 module.exports = (flag, argv) => {
12175 argv = argv || process.argv;
12176 const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
12177 const pos = argv.indexOf(prefix + flag);
12178 const terminatorPos = argv.indexOf('--');
12179 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
12185 /***/ (function(module, exports, __webpack_require__) {
12188 * Module dependencies.
12191 var net = __webpack_require__(15);
12192 var tls = __webpack_require__(53);
12193 var url = __webpack_require__(40);
12194 var Agent = __webpack_require__(54);
12195 var inherits = __webpack_require__(56).inherits;
12196 var debug = __webpack_require__(70)('https-proxy-agent');
12202 module.exports = HttpsProxyAgent;
12205 * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to the
12206 * specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
12211 function HttpsProxyAgent(opts) {
12212 if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(opts);
12213 if ('string' == typeof opts) opts = url.parse(opts);
12216 'an HTTP(S) proxy server `host` and `port` must be specified!'
12218 debug('creating new HttpsProxyAgent instance: %o', opts);
12219 Agent.call(this, opts);
12221 var proxy = Object.assign({}, opts);
12223 // if `true`, then connect to the proxy server over TLS. defaults to `false`.
12224 this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;
12226 // prefer `hostname` over `host`, and set the `port` if needed
12227 proxy.host = proxy.hostname || proxy.host;
12228 proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);
12230 // ALPN is supported by Node.js >= v5.
12231 // attempt to negotiate http/1.1 for proxy servers that support http/2
12232 if (this.secureProxy && !('ALPNProtocols' in proxy)) {
12233 proxy.ALPNProtocols = ['http 1.1']
12236 if (proxy.host && proxy.path) {
12237 // if both a `host` and `path` are specified then it's most likely the
12238 // result of a `url.parse()` call... we need to remove the `path` portion so
12239 // that `net.connect()` doesn't attempt to open that as a unix socket file.
12241 delete proxy.pathname;
12244 this.proxy = proxy;
12245 this.defaultPort = 443;
12247 inherits(HttpsProxyAgent, Agent);
12250 * Called when the node-core HTTP client library is creating a new HTTP request.
12255 HttpsProxyAgent.prototype.callback = function connect(req, opts, fn) {
12256 var proxy = this.proxy;
12258 // create a socket connection to the proxy server
12260 if (this.secureProxy) {
12261 socket = tls.connect(proxy);
12263 socket = net.connect(proxy);
12266 // we need to buffer any HTTP traffic that happens with the proxy before we get
12267 // the CONNECT response, so that if the response is anything other than an "200"
12268 // response code, then we can re-play the "data" events on the socket once the
12269 // HTTP parser is hooked up...
12271 var buffersLength = 0;
12274 var b = socket.read();
12276 else socket.once('readable', read);
12279 function cleanup() {
12280 socket.removeListener('data', ondata);
12281 socket.removeListener('end', onend);
12282 socket.removeListener('error', onerror);
12283 socket.removeListener('close', onclose);
12284 socket.removeListener('readable', read);
12287 function onclose(err) {
12288 debug('onclose had error %o', err);
12295 function onerror(err) {
12300 function ondata(b) {
12302 buffersLength += b.length;
12303 var buffered = Buffer.concat(buffers, buffersLength);
12304 var str = buffered.toString('ascii');
12306 if (!~str.indexOf('\r\n\r\n')) {
12308 debug('have not received end of HTTP headers yet...');
12312 socket.once('data', ondata);
12317 var firstLine = str.substring(0, str.indexOf('\r\n'));
12318 var statusCode = +firstLine.split(' ')[1];
12319 debug('got proxy server response: %o', firstLine);
12321 if (200 == statusCode) {
12322 // 200 Connected status code!
12325 // nullify the buffered data since we won't be needing it
12326 buffers = buffered = null;
12328 if (opts.secureEndpoint) {
12329 // since the proxy is connecting to an SSL server, we have
12330 // to upgrade this socket connection to an SSL connection
12332 'upgrading proxy-connected socket to TLS connection: %o',
12335 opts.socket = socket;
12336 opts.servername = opts.servername || opts.host;
12338 opts.hostname = null;
12340 sock = tls.connect(opts);
12346 // some other status code that's not 200... need to re-play the HTTP header
12347 // "data" events onto the socket once the HTTP machinery is attached so that
12348 // the user can parse and handle the error status code
12351 // save a reference to the concat'd Buffer for the `onsocket` callback
12352 buffers = buffered;
12354 // need to wait for the "socket" event to re-play the "data" events
12355 req.once('socket', onsocket);
12360 function onsocket(socket) {
12361 // replay the "buffers" Buffer onto the `socket`, since at this point
12362 // the HTTP module machinery has been hooked up for the user
12363 if ('function' == typeof socket.ondata) {
12364 // node <= v0.11.3, the `ondata` function is set on the socket
12365 socket.ondata(buffers, 0, buffers.length);
12366 } else if (socket.listeners('data').length > 0) {
12367 // node > v0.11.3, the "data" event is listened for directly
12368 socket.emit('data', buffers);
12371 throw new Error('should not happen...');
12374 // nullify the cached Buffer instance
12378 socket.on('error', onerror);
12379 socket.on('close', onclose);
12380 socket.on('end', onend);
12385 socket.once('data', ondata);
12388 var hostname = opts.host + ':' + opts.port;
12389 var msg = 'CONNECT ' + hostname + ' HTTP/1.1\r\n';
12391 var headers = Object.assign({}, proxy.headers);
12393 headers['Proxy-Authorization'] =
12394 'Basic ' + Buffer.from(proxy.auth).toString('base64');
12397 // the Host header should only include the port
12398 // number when it is a non-standard port
12399 var host = opts.host;
12400 if (!isDefaultPort(opts.port, opts.secureEndpoint)) {
12401 host += ':' + opts.port;
12403 headers['Host'] = host;
12405 headers['Connection'] = 'close';
12406 Object.keys(headers).forEach(function(name) {
12407 msg += name + ': ' + headers[name] + '\r\n';
12410 socket.write(msg + '\r\n');
12413 function isDefaultPort(port, secure) {
12414 return Boolean((!secure && port === 80) || (secure && port === 443));
12420 /***/ (function(module, exports, __webpack_require__) {
12426 * Detect Electron renderer / nwjs process, which is node, but we should
12427 * treat as a browser.
12429 if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
12430 module.exports = __webpack_require__(71);
12432 module.exports = __webpack_require__(74);
12439 /***/ (function(module, exports, __webpack_require__) {
12444 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
12446 /* eslint-env browser */
12449 * This is the web browser implementation of `debug()`.
12452 exports.formatArgs = formatArgs;
12453 exports.save = save;
12454 exports.load = load;
12455 exports.useColors = useColors;
12456 exports.storage = localstorage();
12461 exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
12463 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
12464 * and the Firebug extension (any Firefox version) are known
12465 * to support "%c" CSS customizations.
12467 * TODO: add a `localStorage` variable to explicitly enable/disable colors
12469 // eslint-disable-next-line complexity
12471 function useColors() {
12472 // NB: In an Electron preload script, document will be defined but not fully
12473 // initialized. Since we know we're in Chrome, we'll just detect this case
12475 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
12477 } // Internet Explorer and Edge do not support colors.
12480 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
12482 } // Is webkit? http://stackoverflow.com/a/16459606/376773
12483 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
12486 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
12487 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
12488 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
12489 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
12490 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
12493 * Colorize log arguments if enabled.
12499 function formatArgs(args) {
12500 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
12502 if (!this.useColors) {
12506 var c = 'color: ' + this.color;
12507 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
12508 // arguments passed either before or after the %c, so we need to
12509 // figure out the correct index to insert the CSS into
12513 args[0].replace(/%[a-zA-Z%]/g, function (match) {
12514 if (match === '%%') {
12520 if (match === '%c') {
12521 // We only are interested in the *last* %c
12522 // (the user may have provided their own)
12526 args.splice(lastC, 0, c);
12529 * Invokes `console.log()` when available.
12530 * No-op when `console.log` is not a "function".
12539 // This hackery is required for IE8/9, where
12540 // the `console.log` function doesn't have 'apply'
12541 return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
12544 * Save `namespaces`.
12546 * @param {String} namespaces
12551 function save(namespaces) {
12554 exports.storage.setItem('debug', namespaces);
12556 exports.storage.removeItem('debug');
12558 } catch (error) {// Swallow
12559 // XXX (@Qix-) should we be logging these?
12563 * Load `namespaces`.
12565 * @return {String} returns the previously persisted debug modes
12574 r = exports.storage.getItem('debug');
12575 } catch (error) {} // Swallow
12576 // XXX (@Qix-) should we be logging these?
12577 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
12580 if (!r && typeof process !== 'undefined' && 'env' in process) {
12581 r = process.env.DEBUG;
12587 * Localstorage attempts to return the localstorage.
12589 * This is necessary because safari throws
12590 * when a user disables cookies/localstorage
12591 * and you attempt to access it.
12593 * @return {LocalStorage}
12598 function localstorage() {
12600 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
12601 // The Browser also has localStorage in the global context.
12602 return localStorage;
12603 } catch (error) {// Swallow
12604 // XXX (@Qix-) should we be logging these?
12608 module.exports = __webpack_require__(72)(exports);
12609 var formatters = module.exports.formatters;
12611 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
12614 formatters.j = function (v) {
12616 return JSON.stringify(v);
12618 return '[UnexpectedJSONParseError]: ' + error.message;
12626 /***/ (function(module, exports, __webpack_require__) {
12632 * This is the common logic for both the Node.js and web browser
12633 * implementations of `debug()`.
12635 function setup(env) {
12636 createDebug.debug = createDebug;
12637 createDebug.default = createDebug;
12638 createDebug.coerce = coerce;
12639 createDebug.disable = disable;
12640 createDebug.enable = enable;
12641 createDebug.enabled = enabled;
12642 createDebug.humanize = __webpack_require__(73);
12643 Object.keys(env).forEach(function (key) {
12644 createDebug[key] = env[key];
12647 * Active `debug` instances.
12650 createDebug.instances = [];
12652 * The currently active debug mode names, and names to skip.
12655 createDebug.names = [];
12656 createDebug.skips = [];
12658 * Map of special "%n" handling functions, for the debug "format" argument.
12660 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
12663 createDebug.formatters = {};
12665 * Selects a color for a debug namespace
12666 * @param {String} namespace The namespace string for the for the debug instance to be colored
12667 * @return {Number|String} An ANSI color code for the given namespace
12671 function selectColor(namespace) {
12674 for (var i = 0; i < namespace.length; i++) {
12675 hash = (hash << 5) - hash + namespace.charCodeAt(i);
12676 hash |= 0; // Convert to 32bit integer
12679 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
12682 createDebug.selectColor = selectColor;
12684 * Create a debugger with the given `namespace`.
12686 * @param {String} namespace
12687 * @return {Function}
12691 function createDebug(namespace) {
12696 if (!debug.enabled) {
12700 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
12701 args[_key] = arguments[_key];
12704 var self = debug; // Set `diff` timestamp
12706 var curr = Number(new Date());
12707 var ms = curr - (prevTime || curr);
12709 self.prev = prevTime;
12712 args[0] = createDebug.coerce(args[0]);
12714 if (typeof args[0] !== 'string') {
12715 // Anything else let's inspect with %O
12716 args.unshift('%O');
12717 } // Apply any `formatters` transformations
12721 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
12722 // If we encounter an escaped % then don't increase the array index
12723 if (match === '%%') {
12728 var formatter = createDebug.formatters[format];
12730 if (typeof formatter === 'function') {
12731 var val = args[index];
12732 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
12734 args.splice(index, 1);
12739 }); // Apply env-specific formatting (colors, etc.)
12741 createDebug.formatArgs.call(self, args);
12742 var logFn = self.log || createDebug.log;
12743 logFn.apply(self, args);
12746 debug.namespace = namespace;
12747 debug.enabled = createDebug.enabled(namespace);
12748 debug.useColors = createDebug.useColors();
12749 debug.color = selectColor(namespace);
12750 debug.destroy = destroy;
12751 debug.extend = extend; // Debug.formatArgs = formatArgs;
12752 // debug.rawLog = rawLog;
12753 // env-specific initialization logic for debug instances
12755 if (typeof createDebug.init === 'function') {
12756 createDebug.init(debug);
12759 createDebug.instances.push(debug);
12763 function destroy() {
12764 var index = createDebug.instances.indexOf(this);
12766 if (index !== -1) {
12767 createDebug.instances.splice(index, 1);
12774 function extend(namespace, delimiter) {
12775 return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
12778 * Enables a debug mode by namespaces. This can include modes
12779 * separated by a colon and wildcards.
12781 * @param {String} namespaces
12786 function enable(namespaces) {
12787 createDebug.save(namespaces);
12788 createDebug.names = [];
12789 createDebug.skips = [];
12791 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
12792 var len = split.length;
12794 for (i = 0; i < len; i++) {
12796 // ignore empty strings
12800 namespaces = split[i].replace(/\*/g, '.*?');
12802 if (namespaces[0] === '-') {
12803 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
12805 createDebug.names.push(new RegExp('^' + namespaces + '$'));
12809 for (i = 0; i < createDebug.instances.length; i++) {
12810 var instance = createDebug.instances[i];
12811 instance.enabled = createDebug.enabled(instance.namespace);
12815 * Disable debug output.
12821 function disable() {
12822 createDebug.enable('');
12825 * Returns true if the given mode name is enabled, false otherwise.
12827 * @param {String} name
12828 * @return {Boolean}
12833 function enabled(name) {
12834 if (name[name.length - 1] === '*') {
12841 for (i = 0, len = createDebug.skips.length; i < len; i++) {
12842 if (createDebug.skips[i].test(name)) {
12847 for (i = 0, len = createDebug.names.length; i < len; i++) {
12848 if (createDebug.names[i].test(name)) {
12858 * @param {Mixed} val
12864 function coerce(val) {
12865 if (val instanceof Error) {
12866 return val.stack || val.message;
12872 createDebug.enable(createDebug.load());
12873 return createDebug;
12876 module.exports = setup;
12882 /***/ (function(module, exports) {
12893 var y = d * 365.25;
12896 * Parse or format the given `val`.
12900 * - `long` verbose formatting [false]
12902 * @param {String|Number} val
12903 * @param {Object} [options]
12904 * @throws {Error} throw an error if val is not a non-empty string or a number
12905 * @return {String|Number}
12909 module.exports = function(val, options) {
12910 options = options || {};
12911 var type = typeof val;
12912 if (type === 'string' && val.length > 0) {
12914 } else if (type === 'number' && isFinite(val)) {
12915 return options.long ? fmtLong(val) : fmtShort(val);
12918 'val is not a non-empty string or a valid number. val=' +
12919 JSON.stringify(val)
12924 * Parse the given `str` and return milliseconds.
12926 * @param {String} str
12931 function parse(str) {
12933 if (str.length > 100) {
12936 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
12942 var n = parseFloat(match[1]);
12943 var type = (match[2] || 'ms').toLowerCase();
12977 case 'milliseconds':
12978 case 'millisecond':
12989 * Short format for `ms`.
12991 * @param {Number} ms
12996 function fmtShort(ms) {
12997 var msAbs = Math.abs(ms);
12999 return Math.round(ms / d) + 'd';
13002 return Math.round(ms / h) + 'h';
13005 return Math.round(ms / m) + 'm';
13008 return Math.round(ms / s) + 's';
13014 * Long format for `ms`.
13016 * @param {Number} ms
13021 function fmtLong(ms) {
13022 var msAbs = Math.abs(ms);
13024 return plural(ms, msAbs, d, 'day');
13027 return plural(ms, msAbs, h, 'hour');
13030 return plural(ms, msAbs, m, 'minute');
13033 return plural(ms, msAbs, s, 'second');
13039 * Pluralization helper.
13042 function plural(ms, msAbs, n, name) {
13043 var isPlural = msAbs >= n * 1.5;
13044 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
13050 /***/ (function(module, exports, __webpack_require__) {
13056 * Module dependencies.
13058 var tty = __webpack_require__(66);
13060 var util = __webpack_require__(56);
13062 * This is the Node.js implementation of `debug()`.
13066 exports.init = init;
13068 exports.formatArgs = formatArgs;
13069 exports.save = save;
13070 exports.load = load;
13071 exports.useColors = useColors;
13076 exports.colors = [6, 2, 3, 4, 5, 1];
13079 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
13080 // eslint-disable-next-line import/no-extraneous-dependencies
13081 var supportsColor = __webpack_require__(67);
13083 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
13084 exports.colors = [20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221];
13086 } catch (error) {} // Swallow - we only care if `supports-color` is available; it doesn't have to be.
13089 * Build up the default `inspectOpts` object from the environment variables.
13091 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
13095 exports.inspectOpts = Object.keys(process.env).filter(function (key) {
13096 return /^debug_/i.test(key);
13097 }).reduce(function (obj, key) {
13099 var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function (_, k) {
13100 return k.toUpperCase();
13101 }); // Coerce string value into JS value
13103 var val = process.env[key];
13105 if (/^(yes|on|true|enabled)$/i.test(val)) {
13107 } else if (/^(no|off|false|disabled)$/i.test(val)) {
13109 } else if (val === 'null') {
13119 * Is stdout a TTY? Colored output is enabled when `true`.
13122 function useColors() {
13123 return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
13126 * Adds ANSI color escape codes if enabled.
13132 function formatArgs(args) {
13133 var name = this.namespace,
13134 useColors = this.useColors;
13137 var c = this.color;
13138 var colorCode = "\x1B[3" + (c < 8 ? c : '8;5;' + c);
13139 var prefix = " ".concat(colorCode, ";1m").concat(name, " \x1B[0m");
13140 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
13141 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + "\x1B[0m");
13143 args[0] = getDate() + name + ' ' + args[0];
13147 function getDate() {
13148 if (exports.inspectOpts.hideDate) {
13152 return new Date().toISOString() + ' ';
13155 * Invokes `util.format()` with the specified arguments and writes to stderr.
13160 return process.stderr.write(util.format.apply(util, arguments) + '\n');
13163 * Save `namespaces`.
13165 * @param {String} namespaces
13170 function save(namespaces) {
13172 process.env.DEBUG = namespaces;
13174 // If you set a process.env field to null or undefined, it gets cast to the
13175 // string 'null' or 'undefined'. Just delete instead.
13176 delete process.env.DEBUG;
13180 * Load `namespaces`.
13182 * @return {String} returns the previously persisted debug modes
13188 return process.env.DEBUG;
13191 * Init logic for `debug` instances.
13193 * Create a new `inspectOpts` object in case `useColors` is set
13194 * differently for a particular `debug` instance.
13198 function init(debug) {
13199 debug.inspectOpts = {};
13200 var keys = Object.keys(exports.inspectOpts);
13202 for (var i = 0; i < keys.length; i++) {
13203 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
13207 module.exports = __webpack_require__(72)(exports);
13208 var formatters = module.exports.formatters;
13210 * Map %o to `util.inspect()`, all on a single line.
13213 formatters.o = function (v) {
13214 this.inspectOpts.colors = this.useColors;
13215 return util.inspect(v, this.inspectOpts).replace(/\s*\n\s*/g, ' ');
13218 * Map %O to `util.inspect()`, allowing multiple lines if needed.
13222 formatters.O = function (v) {
13223 this.inspectOpts.colors = this.useColors;
13224 return util.inspect(v, this.inspectOpts);
13231 /***/ (function(module, exports) {
13233 module.exports = require("zlib");
13237 /***/ (function(module, exports, __webpack_require__) {
13240 /* --------------------------------------------------------------------------------------------
\r
13241 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
13242 * Licensed under the MIT License. See License.txt in the project root for license information.
\r
13243 * ------------------------------------------------------------------------------------------ */
\r
13245 Object.defineProperty(exports, "__esModule", { value: true });
\r
13246 var path = __webpack_require__(1);
\r
13247 var fs = __webpack_require__(2);
\r
13248 var toString = Object.prototype.toString;
\r
13249 function isDefined(value) {
\r
13250 return typeof value !== 'undefined';
\r
13252 function isNumber(value) {
\r
13253 return toString.call(value) === '[object Number]';
\r
13255 function isString(value) {
\r
13256 return toString.call(value) === '[object String]';
\r
13258 function isBoolean(value) {
\r
13259 return value === true || value === false;
\r
13261 function readJsonFileSync(filename) {
\r
13262 return JSON.parse(fs.readFileSync(filename, 'utf8'));
\r
13264 var MessageFormat;
\r
13265 (function (MessageFormat) {
\r
13266 MessageFormat["file"] = "file";
\r
13267 MessageFormat["bundle"] = "bundle";
\r
13268 MessageFormat["both"] = "both";
\r
13269 })(MessageFormat = exports.MessageFormat || (exports.MessageFormat = {}));
\r
13270 var BundleFormat;
\r
13271 (function (BundleFormat) {
\r
13272 // the nls.bundle format
\r
13273 BundleFormat["standalone"] = "standalone";
\r
13274 BundleFormat["languagePack"] = "languagePack";
\r
13275 })(BundleFormat = exports.BundleFormat || (exports.BundleFormat = {}));
\r
13276 var LocalizeInfo;
\r
13277 (function (LocalizeInfo) {
\r
13278 function is(value) {
\r
13279 var candidate = value;
\r
13280 return candidate && isDefined(candidate.key) && isDefined(candidate.comment);
\r
13282 LocalizeInfo.is = is;
\r
13283 })(LocalizeInfo || (LocalizeInfo = {}));
\r
13284 var resolvedLanguage;
\r
13285 var resolvedBundles;
\r
13288 function initializeSettings() {
\r
13289 options = { locale: undefined, language: undefined, languagePackSupport: false, cacheLanguageResolution: true, messageFormat: MessageFormat.bundle };
\r
13290 if (isString(process.env.VSCODE_NLS_CONFIG)) {
\r
13292 var vscodeOptions = JSON.parse(process.env.VSCODE_NLS_CONFIG);
\r
13293 var language = void 0;
\r
13294 var locale = void 0;
\r
13295 if (vscodeOptions.availableLanguages) {
\r
13296 var value = vscodeOptions.availableLanguages['*'];
\r
13297 if (isString(value)) {
\r
13298 language = value;
\r
13301 if (isString(vscodeOptions.locale)) {
\r
13302 options.locale = vscodeOptions.locale.toLowerCase();
\r
13304 if (language === undefined) {
\r
13305 options.language = options.locale;
\r
13307 else if (language !== 'en') {
\r
13308 options.language = language;
\r
13310 if (isBoolean(vscodeOptions._languagePackSupport)) {
\r
13311 options.languagePackSupport = vscodeOptions._languagePackSupport;
\r
13313 if (isString(vscodeOptions._cacheRoot)) {
\r
13314 options.cacheRoot = vscodeOptions._cacheRoot;
\r
13316 if (isString(vscodeOptions._languagePackId)) {
\r
13317 options.languagePackId = vscodeOptions._languagePackId;
\r
13319 if (isString(vscodeOptions._translationsConfigFile)) {
\r
13320 options.translationsConfigFile = vscodeOptions._translationsConfigFile;
\r
13322 options.translationsConfig = readJsonFileSync(options.translationsConfigFile);
\r
13325 // We can't read the translation config file. Mark the cache as corrupted.
\r
13326 if (vscodeOptions._corruptedFile) {
\r
13327 fs.writeFile(vscodeOptions._corruptedFile, 'corrupted', 'utf8', function (err) {
\r
13328 console.error(err);
\r
13338 isPseudo = options.locale === 'pseudo';
\r
13339 resolvedLanguage = undefined;
\r
13340 resolvedBundles = Object.create(null);
\r
13342 initializeSettings();
\r
13343 function supportsLanguagePack() {
\r
13344 return options.languagePackSupport === true && options.cacheRoot !== undefined && options.languagePackId !== undefined && options.translationsConfigFile !== undefined
\r
13345 && options.translationsConfig !== undefined;
\r
13347 function format(message, args) {
\r
13350 // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
\r
13351 message = '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D';
\r
13353 if (args.length === 0) {
\r
13354 result = message;
\r
13357 result = message.replace(/\{(\d+)\}/g, function (match, rest) {
\r
13358 var index = rest[0];
\r
13359 var arg = args[index];
\r
13360 var replacement = match;
\r
13361 if (typeof arg === 'string') {
\r
13362 replacement = arg;
\r
13364 else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) {
\r
13365 replacement = String(arg);
\r
13367 return replacement;
\r
13372 function createScopedLocalizeFunction(messages) {
\r
13373 return function (key, message) {
\r
13375 for (var _i = 2; _i < arguments.length; _i++) {
\r
13376 args[_i - 2] = arguments[_i];
\r
13378 if (isNumber(key)) {
\r
13379 if (key >= messages.length) {
\r
13380 console.error("Broken localize call found. Index out of bounds. Stacktrace is\n: " + new Error('').stack);
\r
13383 return format(messages[key], args);
\r
13386 if (isString(message)) {
\r
13387 console.warn("Message " + message + " didn't get externalized correctly.");
\r
13388 return format(message, args);
\r
13391 console.error("Broken localize call found. Stacktrace is\n: " + new Error('').stack);
\r
13396 function localize(key, message) {
\r
13398 for (var _i = 2; _i < arguments.length; _i++) {
\r
13399 args[_i - 2] = arguments[_i];
\r
13401 return format(message, args);
\r
13403 function resolveLanguage(file) {
\r
13404 var resolvedLanguage;
\r
13405 if (options.cacheLanguageResolution && resolvedLanguage) {
\r
13406 resolvedLanguage = resolvedLanguage;
\r
13409 if (isPseudo || !options.language) {
\r
13410 resolvedLanguage = '.nls.json';
\r
13413 var locale = options.language;
\r
13415 var candidate = '.nls.' + locale + '.json';
\r
13416 if (fs.existsSync(file + candidate)) {
\r
13417 resolvedLanguage = candidate;
\r
13421 var index = locale.lastIndexOf('-');
\r
13423 locale = locale.substring(0, index);
\r
13426 resolvedLanguage = '.nls.json';
\r
13432 if (options.cacheLanguageResolution) {
\r
13433 resolvedLanguage = resolvedLanguage;
\r
13436 return file + resolvedLanguage;
\r
13438 function findInTheBoxBundle(root) {
\r
13439 var language = options.language;
\r
13440 while (language) {
\r
13441 var candidate = path.join(root, "nls.bundle." + language + ".json");
\r
13442 if (fs.existsSync(candidate)) {
\r
13443 return candidate;
\r
13446 var index = language.lastIndexOf('-');
\r
13448 language = language.substring(0, index);
\r
13451 language = undefined;
\r
13455 // Test if we can reslove the default bundle.
\r
13456 if (language === undefined) {
\r
13457 var candidate = path.join(root, 'nls.bundle.json');
\r
13458 if (fs.existsSync(candidate)) {
\r
13459 return candidate;
\r
13462 return undefined;
\r
13464 function mkdir(directory) {
\r
13466 fs.mkdirSync(directory);
\r
13469 if (err.code === 'EEXIST') {
\r
13472 else if (err.code === 'ENOENT') {
\r
13473 var parent = path.dirname(directory);
\r
13474 if (parent !== directory) {
\r
13476 fs.mkdirSync(directory);
\r
13484 function createDefaultNlsBundle(folder) {
\r
13485 var metaData = readJsonFileSync(path.join(folder, 'nls.metadata.json'));
\r
13486 var result = Object.create(null);
\r
13487 for (var module_1 in metaData) {
\r
13488 var entry = metaData[module_1];
\r
13489 result[module_1] = entry.messages;
\r
13493 function createNLSBundle(header, metaDataPath) {
\r
13494 var languagePackLocation = options.translationsConfig[header.id];
\r
13495 if (!languagePackLocation) {
\r
13496 return undefined;
\r
13498 var languagePack = readJsonFileSync(languagePackLocation).contents;
\r
13499 var metaData = readJsonFileSync(path.join(metaDataPath, 'nls.metadata.json'));
\r
13500 var result = Object.create(null);
\r
13501 for (var module_2 in metaData) {
\r
13502 var entry = metaData[module_2];
\r
13503 var translations = languagePack[header.outDir + "/" + module_2];
\r
13504 if (translations) {
\r
13505 var resultMessages = [];
\r
13506 for (var i = 0; i < entry.keys.length; i++) {
\r
13507 var messageKey = entry.keys[i];
\r
13508 var key = isString(messageKey) ? messageKey : messageKey.key;
\r
13509 var translatedMessage = translations[key];
\r
13510 if (translatedMessage === undefined) {
\r
13511 translatedMessage = entry.messages[i];
\r
13513 resultMessages.push(translatedMessage);
\r
13515 result[module_2] = resultMessages;
\r
13518 result[module_2] = entry.messages;
\r
13523 function touch(file) {
\r
13524 var d = new Date();
\r
13525 fs.utimes(file, d, d, function () {
\r
13526 // Do nothing. Ignore
\r
13529 function cacheBundle(key, bundle) {
\r
13530 resolvedBundles[key] = bundle;
\r
13533 function loadNlsBundleOrCreateFromI18n(header, bundlePath) {
\r
13535 var bundle = path.join(options.cacheRoot, header.id + "-" + header.hash + ".json");
\r
13536 var useMemoryOnly = false;
\r
13537 var writeBundle = false;
\r
13539 result = JSON.parse(fs.readFileSync(bundle, { encoding: 'utf8', flag: 'r' }));
\r
13544 if (err.code === 'ENOENT') {
\r
13545 writeBundle = true;
\r
13547 else if (err instanceof SyntaxError) {
\r
13548 // We have a syntax error. So no valid JSON. Use
\r
13549 console.log("Syntax error parsing message bundle: " + err.message + ".");
\r
13550 fs.unlink(bundle, function (err) {
\r
13552 console.error("Deleting corrupted bundle " + bundle + " failed.");
\r
13555 useMemoryOnly = true;
\r
13561 result = createNLSBundle(header, bundlePath);
\r
13562 if (!result || useMemoryOnly) {
\r
13565 if (writeBundle) {
\r
13567 fs.writeFileSync(bundle, JSON.stringify(result), { encoding: 'utf8', flag: 'wx' });
\r
13570 if (err.code === 'EEXIST') {
\r
13578 function loadDefaultNlsBundle(bundlePath) {
\r
13580 return createDefaultNlsBundle(bundlePath);
\r
13583 console.log("Generating default bundle from meta data failed.", err);
\r
13584 return undefined;
\r
13587 function loadNlsBundle(header, bundlePath) {
\r
13589 // Core decided to use a language pack. Do the same in the extension
\r
13590 if (supportsLanguagePack()) {
\r
13592 result = loadNlsBundleOrCreateFromI18n(header, bundlePath);
\r
13595 console.log("Load or create bundle failed ", err);
\r
13599 // No language pack found, but core is running in language pack mode
\r
13600 // Don't try to use old in the box bundles since the might be stale
\r
13601 // Fall right back to the default bundle.
\r
13602 if (options.languagePackSupport) {
\r
13603 return loadDefaultNlsBundle(bundlePath);
\r
13605 var candidate = findInTheBoxBundle(bundlePath);
\r
13608 return readJsonFileSync(candidate);
\r
13611 console.log("Loading in the box message bundle failed.", err);
\r
13614 result = loadDefaultNlsBundle(bundlePath);
\r
13618 function tryFindMetaDataHeaderFile(file) {
\r
13620 var dirname = path.dirname(file);
\r
13622 result = path.join(dirname, 'nls.metadata.header.json');
\r
13623 if (fs.existsSync(result)) {
\r
13626 var parent = path.dirname(dirname);
\r
13627 if (parent === dirname) {
\r
13628 result = undefined;
\r
13632 dirname = parent;
\r
13637 function loadMessageBundle(file) {
\r
13639 // No file. We are in dev mode. Return the default
\r
13640 // localize function.
\r
13643 // Remove extension since we load json files.
\r
13644 var ext = path.extname(file);
\r
13646 file = file.substr(0, file.length - ext.length);
\r
13648 if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.bundle) {
\r
13649 var headerFile = tryFindMetaDataHeaderFile(file);
\r
13650 if (headerFile) {
\r
13651 var bundlePath = path.dirname(headerFile);
\r
13652 var bundle = resolvedBundles[bundlePath];
\r
13653 if (bundle === undefined) {
\r
13655 var header = JSON.parse(fs.readFileSync(headerFile, 'utf8'));
\r
13657 var nlsBundle = loadNlsBundle(header, bundlePath);
\r
13658 bundle = cacheBundle(bundlePath, nlsBundle ? { header: header, nlsBundle: nlsBundle } : null);
\r
13661 console.error('Failed to load nls bundle', err);
\r
13662 bundle = cacheBundle(bundlePath, null);
\r
13666 console.error('Failed to read header file', err);
\r
13667 bundle = cacheBundle(bundlePath, null);
\r
13671 var module_3 = file.substr(bundlePath.length + 1).replace(/\\/g, '/');
\r
13672 var messages = bundle.nlsBundle[module_3];
\r
13673 if (messages === undefined) {
\r
13674 console.error("Messages for file " + file + " not found. See console for details.");
\r
13675 return function () {
\r
13676 return 'Messages not found.';
\r
13679 return createScopedLocalizeFunction(messages);
\r
13683 if (options.messageFormat === MessageFormat.both || options.messageFormat === MessageFormat.file) {
\r
13684 // Try to load a single file bundle
\r
13686 var json = readJsonFileSync(resolveLanguage(file));
\r
13687 if (Array.isArray(json)) {
\r
13688 return createScopedLocalizeFunction(json);
\r
13691 if (isDefined(json.messages) && isDefined(json.keys)) {
\r
13692 return createScopedLocalizeFunction(json.messages);
\r
13695 console.error("String bundle '" + file + "' uses an unsupported format.");
\r
13696 return function () {
\r
13697 return 'File bundle has unsupported format. See console for details';
\r
13703 if (err.code !== 'ENOENT') {
\r
13704 console.error('Failed to load single file bundle', err);
\r
13708 console.error("Failed to load message bundle for file " + file);
\r
13709 return function () {
\r
13710 return 'Failed to load message bundle. See console for details.';
\r
13713 exports.loadMessageBundle = loadMessageBundle;
\r
13714 function config(opts) {
\r
13716 if (isString(opts.locale)) {
\r
13717 options.locale = opts.locale.toLowerCase();
\r
13718 options.language = options.locale;
\r
13719 resolvedLanguage = undefined;
\r
13720 resolvedBundles = Object.create(null);
\r
13722 if (opts.messageFormat !== undefined) {
\r
13723 options.messageFormat = opts.messageFormat;
\r
13725 if (opts.bundleFormat === BundleFormat.standalone && options.languagePackSupport === true) {
\r
13726 options.languagePackSupport = false;
\r
13729 isPseudo = options.locale === 'pseudo';
\r
13730 return loadMessageBundle;
\r
13732 exports.config = config;
\r
13733 //# sourceMappingURL=main.js.map
13737 /***/ (function(module, __webpack_exports__, __webpack_require__) {
13740 __webpack_require__.r(__webpack_exports__);
13741 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setUriThrowOnMissingScheme", function() { return setUriThrowOnMissingScheme; });
13742 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; });
13743 /*---------------------------------------------------------------------------------------------
13744 * Copyright (c) Microsoft Corporation. All rights reserved.
13745 * Licensed under the MIT License. See License.txt in the project root for license information.
13746 *--------------------------------------------------------------------------------------------*/
13748 var __extends = (undefined && undefined.__extends) || (function () {
13749 var extendStatics = Object.setPrototypeOf ||
13750 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
13751 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
13752 return function (d, b) {
13753 extendStatics(d, b);
13754 function __() { this.constructor = d; }
13755 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13759 if (typeof process === 'object') {
13760 isWindows = process.platform === 'win32';
13762 else if (typeof navigator === 'object') {
13763 var userAgent = navigator.userAgent;
13764 isWindows = userAgent.indexOf('Windows') >= 0;
13767 var _schemePattern = /^\w[\w\d+.-]*$/;
13768 var _singleSlashStart = /^\//;
13769 var _doubleSlashStart = /^\/\//;
13770 var _throwOnMissingSchema = true;
13774 function setUriThrowOnMissingScheme(value) {
13775 var old = _throwOnMissingSchema;
13776 _throwOnMissingSchema = value;
13779 function _validateUri(ret, _strict) {
13780 // scheme, must be set
13782 if (_strict || _throwOnMissingSchema) {
13783 throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
13786 // console.warn(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
13789 // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
13790 // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
13791 if (ret.scheme && !_schemePattern.test(ret.scheme)) {
13792 throw new Error('[UriError]: Scheme contains illegal characters.');
13794 // path, http://tools.ietf.org/html/rfc3986#section-3.3
13795 // If a URI contains an authority component, then the path component
13796 // must either be empty or begin with a slash ("/") character. If a URI
13797 // does not contain an authority component, then the path cannot begin
13798 // with two slash characters ("//").
13800 if (ret.authority) {
13801 if (!_singleSlashStart.test(ret.path)) {
13802 throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
13806 if (_doubleSlashStart.test(ret.path)) {
13807 throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
13812 // for a while we allowed uris *without* schemes and this is the migration
13813 // for them, e.g. an uri without scheme and without strict-mode warns and falls
13814 // back to the file-scheme. that should cause the least carnage and still be a
13816 function _schemeFix(scheme, _strict) {
13817 if (_strict || _throwOnMissingSchema) {
13818 return scheme || _empty;
13821 // console.trace('BAD uri lacks scheme, falling back to file-scheme.');
13826 // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
13827 function _referenceResolution(scheme, path) {
13828 // the slash-character is our 'default base' as we don't
13829 // support constructing URIs relative to other URIs. This
13830 // also means that we alter and potentially break paths.
13831 // see https://tools.ietf.org/html/rfc3986#section-5.1.4
13839 else if (path[0] !== _slash) {
13840 path = _slash + path;
13848 var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
13849 function _isQueryStringScheme(scheme) {
13850 switch (scheme.toLowerCase()) {
13859 * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
13860 * This class is a simple parser which creates the basic component parts
13861 * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
13864 * foo://example.com:8042/over/there?name=ferret#nose
13865 * \_/ \______________/\_________/ \_________/ \__/
13867 * scheme authority path query fragment
13868 * | _____________________|__
13870 * urn:example:animal:ferret:nose
13872 var URI = (function () {
13876 function URI(schemeOrData, authority, path, query, fragment, _strict) {
13877 if (_strict === void 0) { _strict = false; }
13878 if (typeof schemeOrData === 'object') {
13879 this.scheme = schemeOrData.scheme || _empty;
13880 this.authority = schemeOrData.authority || _empty;
13881 this.path = schemeOrData.path || _empty;
13882 this.query = schemeOrData.query || _empty;
13883 this.fragment = schemeOrData.fragment || _empty;
13884 // no validation because it's this URI
13885 // that creates uri components.
13886 // _validateUri(this);
13889 this.scheme = _schemeFix(schemeOrData, _strict);
13890 this.authority = authority || _empty;
13891 this.path = _referenceResolution(this.scheme, path || _empty);
13892 this.query = query || _empty;
13893 this.fragment = fragment || _empty;
13894 _validateUri(this, _strict);
13897 URI.isUri = function (thing) {
13898 if (thing instanceof URI) {
13904 return typeof thing.authority === 'string'
13905 && typeof thing.fragment === 'string'
13906 && typeof thing.path === 'string'
13907 && typeof thing.query === 'string'
13908 && typeof thing.scheme === 'string'
13909 && typeof thing.fsPath === 'function'
13910 && typeof thing.with === 'function'
13911 && typeof thing.toString === 'function';
13913 Object.defineProperty(URI.prototype, "fsPath", {
13914 // ---- filesystem path -----------------------
13916 * Returns a string representing the corresponding file system path of this URI.
13917 * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
13918 * platform specific path separator.
13920 * * Will *not* validate the path for invalid characters and semantics.
13921 * * Will *not* look at the scheme of this URI.
13922 * * The result shall *not* be used for display purposes but for accessing a file on disk.
13925 * The *difference* to `URI#path` is the use of the platform specific separator and the handling
13926 * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
13929 const u = URI.parse('file://server/c$/folder/file.txt')
13930 u.authority === 'server'
13931 u.path === '/shares/c$/file.txt'
13932 u.fsPath === '\\server\c$\folder\file.txt'
13935 * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
13936 * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
13937 * with URIs that represent files on disk (`file` scheme).
13940 // if (this.scheme !== 'file') {
13941 // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
13943 return _makeFsPath(this);
13948 // ---- modify to new -------------------------
13949 URI.prototype.with = function (change) {
13953 var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
13954 if (scheme === undefined) {
13955 scheme = this.scheme;
13957 else if (scheme === null) {
13960 if (authority === undefined) {
13961 authority = this.authority;
13963 else if (authority === null) {
13964 authority = _empty;
13966 if (path === undefined) {
13969 else if (path === null) {
13972 if (query === undefined) {
13973 query = this.query;
13975 else if (query === null) {
13978 if (fragment === undefined) {
13979 fragment = this.fragment;
13981 else if (fragment === null) {
13984 if (scheme === this.scheme
13985 && authority === this.authority
13986 && path === this.path
13987 && query === this.query
13988 && fragment === this.fragment) {
13991 return new _URI(scheme, authority, path, query, fragment);
13993 // ---- parse & validate ------------------------
13995 * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
13996 * `file:///usr/home`, or `scheme:with/path`.
13998 * @param value A string which represents an URI (see `URI#toString`).
14000 URI.parse = function (value, _strict) {
14001 if (_strict === void 0) { _strict = false; }
14002 var match = _regexp.exec(value);
14004 return new _URI(_empty, _empty, _empty, _empty, _empty, _strict);
14006 return new _URI(match[2] || _empty, decodeURIComponentFast(match[4] || _empty, false, false), decodeURIComponentFast(match[5] || _empty, true, false), decodeURIComponentFast(match[7] || _empty, false, _isQueryStringScheme(match[2])), decodeURIComponentFast(match[9] || _empty, false, false), _strict);
14009 * Creates a new URI from a file system path, e.g. `c:\my\files`,
14010 * `/usr/home`, or `\\server\share\some\path`.
14012 * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
14013 * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
14014 * `URI.parse('file://' + path)` because the path might contain characters that are
14015 * interpreted (# and ?). See the following sample:
14017 const good = URI.file('/coding/c#/project1');
14018 good.scheme === 'file';
14019 good.path === '/coding/c#/project1';
14020 good.fragment === '';
14021 const bad = URI.parse('file://' + '/coding/c#/project1');
14022 bad.scheme === 'file';
14023 bad.path === '/coding/c'; // path is now broken
14024 bad.fragment === '/project1';
14027 * @param path A file system path (see `URI#fsPath`)
14029 URI.file = function (path) {
14030 var authority = _empty;
14031 // normalize to fwd-slashes on windows,
14032 // on other systems bwd-slashes are valid
14033 // filename character, eg /f\oo/ba\r.txt
14035 path = path.replace(/\\/g, _slash);
14037 // check for authority as used in UNC shares
14038 // or use the path as given
14039 if (path[0] === _slash && path[1] === _slash) {
14040 var idx = path.indexOf(_slash, 2);
14042 authority = path.substring(2);
14046 authority = path.substring(2, idx);
14047 path = path.substring(idx) || _slash;
14050 return new _URI('file', authority, path, _empty, _empty);
14052 URI.from = function (components) {
14053 return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
14055 // ---- printing/externalize ---------------------------
14057 * Creates a string representation for this URI. It's guaranteed that calling
14058 * `URI.parse` with the result of this function creates an URI which is equal
14061 * * The result shall *not* be used for display purposes but for externalization or transport.
14062 * * The result will be encoded using the percentage encoding and encoding happens mostly
14063 * ignore the scheme-specific encoding rules.
14065 * @param skipEncoding Do not encode the result, default is `false`
14067 URI.prototype.toString = function (skipEncoding) {
14068 if (skipEncoding === void 0) { skipEncoding = false; }
14069 return _asFormatted(this, skipEncoding);
14071 URI.prototype.toJSON = function () {
14074 URI.revive = function (data) {
14078 else if (data instanceof URI) {
14082 var result = new _URI(data);
14083 result._formatted = data.external;
14084 result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
14091 var _pathSepMarker = isWindows ? 1 : undefined;
14092 // tslint:disable-next-line:class-name
14093 var _URI = (function (_super) {
14094 __extends(_URI, _super);
14096 var _this = _super !== null && _super.apply(this, arguments) || this;
14097 _this._formatted = null;
14098 _this._fsPath = null;
14101 Object.defineProperty(_URI.prototype, "fsPath", {
14103 if (!this._fsPath) {
14104 this._fsPath = _makeFsPath(this);
14106 return this._fsPath;
14111 _URI.prototype.toString = function (skipEncoding) {
14112 if (skipEncoding === void 0) { skipEncoding = false; }
14113 if (!skipEncoding) {
14114 if (!this._formatted) {
14115 this._formatted = _asFormatted(this, false);
14117 return this._formatted;
14120 // we don't cache that
14121 return _asFormatted(this, true);
14124 _URI.prototype.toJSON = function () {
14129 if (this._fsPath) {
14130 res.fsPath = this._fsPath;
14131 res._sep = _pathSepMarker;
14133 if (this._formatted) {
14134 res.external = this._formatted;
14138 res.path = this.path;
14141 res.scheme = this.scheme;
14143 if (this.authority) {
14144 res.authority = this.authority;
14147 res.query = this.query;
14149 if (this.fragment) {
14150 res.fragment = this.fragment;
14156 function isHex(value, pos) {
14157 if (pos >= value.length) {
14160 var code = value.charCodeAt(pos);
14161 return (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */) // 0-9
14162 || (code >= 97 /* a */ && code <= 102 /* f */) //a-f
14163 || (code >= 65 /* A */ && code <= 70 /* F */); //A-F
14165 function decodeURIComponentFast(uriComponent, isPath, isQueryString) {
14167 var nativeDecodePos = -1;
14168 for (var pos = 0; pos < uriComponent.length; pos++) {
14169 var code = uriComponent.charCodeAt(pos);
14171 if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
14172 var chA = uriComponent.charCodeAt(pos + 1);
14173 var chB = uriComponent.charCodeAt(pos + 2);
14174 // when in a path -> check and accept %2f and %2F (fwd slash)
14175 // when in a query string -> check and accept %3D, %26, and %3B (equals, ampersand, semi-colon)
14176 if ((isPath && chA === 50 /* Digit2 */ && (chB === 70 /* F */ || chB === 102 /* f */))
14178 (isQueryString && ((chA === 50 /* Digit2 */ && chB === 54 /* Digit6 */) // %26
14180 (chA === 51 /* Digit3 */ && (chB === 66 /* B */ || chB === 98 /* b */ || chB === 68 /* D */ || chB === 100 /* d */)) // %3D, %3D
14182 if (nativeDecodePos !== -1) {
14183 res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
14184 nativeDecodePos = -1;
14186 if (res !== undefined) {
14187 res += uriComponent.substr(pos, 3);
14192 if (res === undefined) {
14193 res = uriComponent.substring(0, pos);
14195 if (nativeDecodePos === -1) {
14196 nativeDecodePos = pos;
14201 if (nativeDecodePos !== -1) {
14202 res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
14203 nativeDecodePos = -1;
14205 if (res !== undefined) {
14206 res += String.fromCharCode(code);
14210 if (nativeDecodePos !== -1) {
14211 res += decodeURIComponent(uriComponent.substr(nativeDecodePos));
14213 return res !== undefined ? res : uriComponent;
14215 // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
14216 var encodeTable = (_a = {},
14217 _a[58 /* Colon */] = '%3A',
14218 _a[47 /* Slash */] = '%2F',
14219 _a[63 /* QuestionMark */] = '%3F',
14220 _a[35 /* Hash */] = '%23',
14221 _a[91 /* OpenSquareBracket */] = '%5B',
14222 _a[93 /* CloseSquareBracket */] = '%5D',
14223 _a[64 /* AtSign */] = '%40',
14224 _a[33 /* ExclamationMark */] = '%21',
14225 _a[36 /* DollarSign */] = '%24',
14226 _a[38 /* Ampersand */] = '%26',
14227 _a[39 /* SingleQuote */] = '%27',
14228 _a[40 /* OpenParen */] = '%28',
14229 _a[41 /* CloseParen */] = '%29',
14230 _a[42 /* Asterisk */] = '%2A',
14231 _a[43 /* Plus */] = '%2B',
14232 _a[44 /* Comma */] = '%2C',
14233 _a[59 /* Semicolon */] = '%3B',
14234 _a[61 /* Equals */] = '%3D',
14235 _a[32 /* Space */] = '%20',
14237 function encodeURIComponentFast(uriComponent, isPath, isQueryString) {
14238 var res = undefined;
14239 var nativeEncodePos = -1;
14240 for (var pos = 0; pos < uriComponent.length; pos++) {
14241 var code = uriComponent.charCodeAt(pos);
14242 // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
14243 if ((code >= 97 /* a */ && code <= 122 /* z */)
14244 || (code >= 65 /* A */ && code <= 90 /* Z */)
14245 || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
14246 || code === 45 /* Dash */
14247 || code === 46 /* Period */
14248 || code === 95 /* Underline */
14249 || code === 126 /* Tilde */
14250 || (isPath && code === 47 /* Slash */) // path => allow slash AS-IS
14251 || (isQueryString && (code === 61 /* Equals */ || code === 38 /* Ampersand */ || code === 59 /* Semicolon */)) // query string => allow &=;
14253 // check if we are delaying native encode
14254 if (nativeEncodePos !== -1) {
14255 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
14256 nativeEncodePos = -1;
14258 // check if we write into a new string (by default we try to return the param)
14259 if (res !== undefined) {
14260 res += uriComponent.charAt(pos);
14263 else if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
14264 // at percentage encoded value
14265 // check if we are delaying native encode
14266 if (nativeEncodePos !== -1) {
14267 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
14268 nativeEncodePos = -1;
14270 // check if we write into a new string (by default we try to return the param)
14271 if (res !== undefined) {
14272 res += uriComponent.substr(pos, 3);
14277 // encoding needed, we need to allocate a new string
14278 if (res === undefined) {
14279 res = uriComponent.substr(0, pos);
14281 // check with default table first
14282 var escaped = encodeTable[code];
14283 if (escaped !== undefined) {
14284 // check if we are delaying native encode
14285 if (nativeEncodePos !== -1) {
14286 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
14287 nativeEncodePos = -1;
14289 // append escaped variant to result
14292 else if (nativeEncodePos === -1) {
14293 // use native encode only when needed
14294 nativeEncodePos = pos;
14298 if (nativeEncodePos !== -1) {
14299 res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
14301 return res !== undefined ? res : uriComponent;
14303 function encodeURIComponentMinimal(path) {
14304 var res = undefined;
14305 for (var pos = 0; pos < path.length; pos++) {
14306 var code = path.charCodeAt(pos);
14307 if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
14308 if (res === undefined) {
14309 res = path.substr(0, pos);
14311 res += encodeTable[code];
14314 if (res !== undefined) {
14319 return res !== undefined ? res : path;
14322 * Compute `fsPath` for the given uri
14324 function _makeFsPath(uri) {
14326 if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
14327 // unc path: file://shares/c$/far/boo
14328 value = "//" + uri.authority + uri.path;
14330 else if (uri.path.charCodeAt(0) === 47 /* Slash */
14331 && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
14332 && uri.path.charCodeAt(2) === 58 /* Colon */) {
14333 // windows drive letter: file:///c:/far/boo
14334 value = uri.path[1].toLowerCase() + uri.path.substr(2);
14341 value = value.replace(/\//g, '\\');
14346 * Create the external version of a uri
14348 function _asFormatted(uri, skipEncoding) {
14349 var encoder = !skipEncoding
14350 ? encodeURIComponentFast
14351 : encodeURIComponentMinimal;
14353 var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
14358 if (authority || scheme === 'file') {
14363 var idx = authority.indexOf('@');
14366 var userinfo = authority.substr(0, idx);
14367 authority = authority.substr(idx + 1);
14368 idx = userinfo.indexOf(':');
14370 res += encoder(userinfo, false, false);
14373 // <user>:<pass>@<auth>
14374 res += encoder(userinfo.substr(0, idx), false, false);
14376 res += encoder(userinfo.substr(idx + 1), false, false);
14380 authority = authority.toLowerCase();
14381 idx = authority.indexOf(':');
14383 res += encoder(authority, false, false);
14387 res += encoder(authority.substr(0, idx), false, false);
14388 res += authority.substr(idx);
14392 // lower-case windows drive letters in /C:/fff or C:/fff
14393 if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
14394 var code = path.charCodeAt(1);
14395 if (code >= 65 /* A */ && code <= 90 /* Z */) {
14396 path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
14399 else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
14400 var code = path.charCodeAt(0);
14401 if (code >= 65 /* A */ && code <= 90 /* Z */) {
14402 path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
14405 // encode the rest of the path
14406 res += encoder(path, true, false);
14410 res += encoder(query, false, _isQueryStringScheme(scheme));
14414 res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
14423 /***/ (function(module, exports, __webpack_require__) {
14427 /*---------------------------------------------------------------------------------------------
14428 * Copyright (c) Microsoft Corporation. All rights reserved.
14429 * Licensed under the MIT License. See License.txt in the project root for license information.
14430 *--------------------------------------------------------------------------------------------*/
14431 Object.defineProperty(exports, "__esModule", { value: true });
14432 const vscode_languageserver_1 = __webpack_require__(34);
14433 function formatError(message, err) {
14434 if (err instanceof Error) {
14436 return `${message}: ${error.message}\n${error.stack}`;
14438 else if (typeof err === 'string') {
14439 return `${message}: ${err}`;
14442 return `${message}: ${err.toString()}`;
14446 exports.formatError = formatError;
14447 function runSafeAsync(func, errorVal, errorMessage, token) {
14448 return new Promise((resolve) => {
14449 setImmediate(() => {
14450 if (token.isCancellationRequested) {
14451 resolve(cancelValue());
14453 return func().then(result => {
14454 if (token.isCancellationRequested) {
14455 resolve(cancelValue());
14462 console.error(formatError(errorMessage, e));
14468 exports.runSafeAsync = runSafeAsync;
14469 function runSafe(func, errorVal, errorMessage, token) {
14470 return new Promise((resolve) => {
14471 setImmediate(() => {
14472 if (token.isCancellationRequested) {
14473 resolve(cancelValue());
14477 let result = func();
14478 if (token.isCancellationRequested) {
14479 resolve(cancelValue());
14487 console.error(formatError(errorMessage, e));
14494 exports.runSafe = runSafe;
14495 function cancelValue() {
14496 console.log('cancelled');
14497 return new vscode_languageserver_1.ResponseError(vscode_languageserver_1.ErrorCodes.RequestCancelled, 'Request cancelled');
14503 /***/ (function(module, __webpack_exports__, __webpack_require__) {
14506 __webpack_require__.r(__webpack_exports__);
14507 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLanguageService", function() { return getLanguageService; });
14508 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
14509 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextDocument"]; });
14511 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Position"]; });
14513 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["CompletionItem"]; });
14515 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["CompletionList"]; });
14517 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Hover"]; });
14519 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"]; });
14521 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SymbolInformation"]; });
14523 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Diagnostic"]; });
14525 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextEdit"]; });
14527 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FormattingOptions"]; });
14529 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkedString"]; });
14531 /* harmony import */ var _services_jsonCompletion__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(81);
14532 /* harmony import */ var _services_jsonHover__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(92);
14533 /* harmony import */ var _services_jsonValidation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(93);
14534 /* harmony import */ var _services_jsonDocumentSymbols__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(96);
14535 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(82);
14536 /* harmony import */ var _services_configuration__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(98);
14537 /* harmony import */ var _services_jsonSchemaService__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(94);
14538 /* harmony import */ var _services_jsonFolding__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(99);
14539 /* harmony import */ var _services_jsonSelectionRanges__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(100);
14540 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(83);
14541 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(89);
14542 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["Color"]; });
14544 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ColorInformation"]; });
14546 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ColorPresentation"]; });
14548 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["FoldingRange"]; });
14550 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["FoldingRangeKind"]; });
14552 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["SelectionRange"]; });
14554 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ErrorCode", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ErrorCode"]; });
14556 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClientCapabilities", function() { return _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_11__["ClientCapabilities"]; });
14558 /*---------------------------------------------------------------------------------------------
14559 * Copyright (c) Microsoft Corporation. All rights reserved.
14560 * Licensed under the MIT License. See License.txt in the project root for license information.
14561 *--------------------------------------------------------------------------------------------*/
14575 function getLanguageService(params) {
14576 var promise = params.promiseConstructor || Promise;
14577 var jsonSchemaService = new _services_jsonSchemaService__WEBPACK_IMPORTED_MODULE_7__["JSONSchemaService"](params.schemaRequestService, params.workspaceContext, promise);
14578 jsonSchemaService.setSchemaContributions(_services_configuration__WEBPACK_IMPORTED_MODULE_6__["schemaContributions"]);
14579 var jsonCompletion = new _services_jsonCompletion__WEBPACK_IMPORTED_MODULE_1__["JSONCompletion"](jsonSchemaService, params.contributions, promise, params.clientCapabilities);
14580 var jsonHover = new _services_jsonHover__WEBPACK_IMPORTED_MODULE_2__["JSONHover"](jsonSchemaService, params.contributions, promise);
14581 var jsonDocumentSymbols = new _services_jsonDocumentSymbols__WEBPACK_IMPORTED_MODULE_4__["JSONDocumentSymbols"](jsonSchemaService);
14582 var jsonValidation = new _services_jsonValidation__WEBPACK_IMPORTED_MODULE_3__["JSONValidation"](jsonSchemaService, promise);
14584 configure: function (settings) {
14585 jsonSchemaService.clearExternalSchemas();
14586 if (settings.schemas) {
14587 settings.schemas.forEach(function (settings) {
14588 jsonSchemaService.registerExternalSchema(settings.uri, settings.fileMatch, settings.schema);
14591 jsonValidation.configure(settings);
14593 resetSchema: function (uri) { return jsonSchemaService.onResourceChange(uri); },
14594 doValidation: jsonValidation.doValidation.bind(jsonValidation),
14595 parseJSONDocument: function (document) { return Object(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_5__["parse"])(document, { collectComments: true }); },
14596 newJSONDocument: function (root, diagnostics) { return Object(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_5__["newJSONDocument"])(root, diagnostics); },
14597 doResolve: jsonCompletion.doResolve.bind(jsonCompletion),
14598 doComplete: jsonCompletion.doComplete.bind(jsonCompletion),
14599 findDocumentSymbols: jsonDocumentSymbols.findDocumentSymbols.bind(jsonDocumentSymbols),
14600 findDocumentSymbols2: jsonDocumentSymbols.findDocumentSymbols2.bind(jsonDocumentSymbols),
14601 findColorSymbols: function (d, s) { return jsonDocumentSymbols.findDocumentColors(d, s).then(function (s) { return s.map(function (s) { return s.range; }); }); },
14602 findDocumentColors: jsonDocumentSymbols.findDocumentColors.bind(jsonDocumentSymbols),
14603 getColorPresentations: jsonDocumentSymbols.getColorPresentations.bind(jsonDocumentSymbols),
14604 doHover: jsonHover.doHover.bind(jsonHover),
14605 getFoldingRanges: _services_jsonFolding__WEBPACK_IMPORTED_MODULE_8__["getFoldingRanges"],
14606 getSelectionRanges: _services_jsonSelectionRanges__WEBPACK_IMPORTED_MODULE_9__["getSelectionRanges"],
14607 format: function (d, r, o) {
14608 var range = void 0;
14610 var offset = d.offsetAt(r.start);
14611 var length = d.offsetAt(r.end) - offset;
14612 range = { offset: offset, length: length };
14614 var options = { tabSize: o ? o.tabSize : 4, insertSpaces: o ? o.insertSpaces : true, eol: '\n' };
14615 return Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_10__["format"])(d.getText(), range, options).map(function (e) {
14616 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextEdit"].replace(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"].create(d.positionAt(e.offset), d.positionAt(e.offset + e.length)), e.content);
14625 /***/ (function(module, __webpack_exports__, __webpack_require__) {
14628 __webpack_require__.r(__webpack_exports__);
14629 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Position", function() { return Position; });
14630 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return Range; });
14631 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Location", function() { return Location; });
14632 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocationLink", function() { return LocationLink; });
14633 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
14634 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return ColorInformation; });
14635 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return ColorPresentation; });
14636 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return FoldingRangeKind; });
14637 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return FoldingRange; });
14638 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticRelatedInformation", function() { return DiagnosticRelatedInformation; });
14639 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticSeverity", function() { return DiagnosticSeverity; });
14640 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiagnosticTag", function() { return DiagnosticTag; });
14641 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Diagnostic", function() { return Diagnostic; });
14642 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Command", function() { return Command; });
14643 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return TextEdit; });
14644 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentEdit", function() { return TextDocumentEdit; });
14645 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CreateFile", function() { return CreateFile; });
14646 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenameFile", function() { return RenameFile; });
14647 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteFile", function() { return DeleteFile; });
14648 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceEdit", function() { return WorkspaceEdit; });
14649 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkspaceChange", function() { return WorkspaceChange; });
14650 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentIdentifier", function() { return TextDocumentIdentifier; });
14651 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VersionedTextDocumentIdentifier", function() { return VersionedTextDocumentIdentifier; });
14652 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentItem", function() { return TextDocumentItem; });
14653 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupKind", function() { return MarkupKind; });
14654 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkupContent", function() { return MarkupContent; });
14655 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItemKind", function() { return CompletionItemKind; });
14656 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InsertTextFormat", function() { return InsertTextFormat; });
14657 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionItem", function() { return CompletionItem; });
14658 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CompletionList", function() { return CompletionList; });
14659 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MarkedString", function() { return MarkedString; });
14660 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hover", function() { return Hover; });
14661 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParameterInformation", function() { return ParameterInformation; });
14662 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignatureInformation", function() { return SignatureInformation; });
14663 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlightKind", function() { return DocumentHighlightKind; });
14664 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentHighlight", function() { return DocumentHighlight; });
14665 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolKind", function() { return SymbolKind; });
14666 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolInformation", function() { return SymbolInformation; });
14667 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentSymbol", function() { return DocumentSymbol; });
14668 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionKind", function() { return CodeActionKind; });
14669 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeActionContext", function() { return CodeActionContext; });
14670 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeAction", function() { return CodeAction; });
14671 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeLens", function() { return CodeLens; });
14672 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FormattingOptions", function() { return FormattingOptions; });
14673 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DocumentLink", function() { return DocumentLink; });
14674 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return SelectionRange; });
14675 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EOL", function() { return EOL; });
14676 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocument", function() { return TextDocument; });
14677 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextDocumentSaveReason", function() { return TextDocumentSaveReason; });
14678 /* --------------------------------------------------------------------------------------------
14679 * Copyright (c) Microsoft Corporation. All rights reserved.
14680 * Licensed under the MIT License. See License.txt in the project root for license information.
14681 * ------------------------------------------------------------------------------------------ */
14684 * The Position namespace provides helper functions to work with
14685 * [Position](#Position) literals.
14688 (function (Position) {
14690 * Creates a new Position literal from the given line and character.
14691 * @param line The position's line.
14692 * @param character The position's character.
14694 function create(line, character) {
14695 return { line: line, character: character };
14697 Position.create = create;
14699 * Checks whether the given liternal conforms to the [Position](#Position) interface.
14701 function is(value) {
14702 var candidate = value;
14703 return Is.objectLiteral(candidate) && Is.number(candidate.line) && Is.number(candidate.character);
14706 })(Position || (Position = {}));
14708 * The Range namespace provides helper functions to work with
14709 * [Range](#Range) literals.
14712 (function (Range) {
14713 function create(one, two, three, four) {
14714 if (Is.number(one) && Is.number(two) && Is.number(three) && Is.number(four)) {
14715 return { start: Position.create(one, two), end: Position.create(three, four) };
14717 else if (Position.is(one) && Position.is(two)) {
14718 return { start: one, end: two };
14721 throw new Error("Range#create called with invalid arguments[" + one + ", " + two + ", " + three + ", " + four + "]");
14724 Range.create = create;
14726 * Checks whether the given literal conforms to the [Range](#Range) interface.
14728 function is(value) {
14729 var candidate = value;
14730 return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
14733 })(Range || (Range = {}));
14735 * The Location namespace provides helper functions to work with
14736 * [Location](#Location) literals.
14739 (function (Location) {
14741 * Creates a Location literal.
14742 * @param uri The location's uri.
14743 * @param range The location's range.
14745 function create(uri, range) {
14746 return { uri: uri, range: range };
14748 Location.create = create;
14750 * Checks whether the given literal conforms to the [Location](#Location) interface.
14752 function is(value) {
14753 var candidate = value;
14754 return Is.defined(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
14757 })(Location || (Location = {}));
14759 * The LocationLink namespace provides helper functions to work with
14760 * [LocationLink](#LocationLink) literals.
14763 (function (LocationLink) {
14765 * Creates a LocationLink literal.
14766 * @param targetUri The definition's uri.
14767 * @param targetRange The full range of the definition.
14768 * @param targetSelectionRange The span of the symbol definition at the target.
14769 * @param originSelectionRange The span of the symbol being defined in the originating source file.
14771 function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
14772 return { targetUri: targetUri, targetRange: targetRange, targetSelectionRange: targetSelectionRange, originSelectionRange: originSelectionRange };
14774 LocationLink.create = create;
14776 * Checks whether the given literal conforms to the [LocationLink](#LocationLink) interface.
14778 function is(value) {
14779 var candidate = value;
14780 return Is.defined(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri)
14781 && (Range.is(candidate.targetSelectionRange) || Is.undefined(candidate.targetSelectionRange))
14782 && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
14784 LocationLink.is = is;
14785 })(LocationLink || (LocationLink = {}));
14787 * The Color namespace provides helper functions to work with
14788 * [Color](#Color) literals.
14791 (function (Color) {
14793 * Creates a new Color literal.
14795 function create(red, green, blue, alpha) {
14803 Color.create = create;
14805 * Checks whether the given literal conforms to the [Color](#Color) interface.
14807 function is(value) {
14808 var candidate = value;
14809 return Is.number(candidate.red)
14810 && Is.number(candidate.green)
14811 && Is.number(candidate.blue)
14812 && Is.number(candidate.alpha);
14815 })(Color || (Color = {}));
14817 * The ColorInformation namespace provides helper functions to work with
14818 * [ColorInformation](#ColorInformation) literals.
14820 var ColorInformation;
14821 (function (ColorInformation) {
14823 * Creates a new ColorInformation literal.
14825 function create(range, color) {
14831 ColorInformation.create = create;
14833 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
14835 function is(value) {
14836 var candidate = value;
14837 return Range.is(candidate.range) && Color.is(candidate.color);
14839 ColorInformation.is = is;
14840 })(ColorInformation || (ColorInformation = {}));
14842 * The Color namespace provides helper functions to work with
14843 * [ColorPresentation](#ColorPresentation) literals.
14845 var ColorPresentation;
14846 (function (ColorPresentation) {
14848 * Creates a new ColorInformation literal.
14850 function create(label, textEdit, additionalTextEdits) {
14853 textEdit: textEdit,
14854 additionalTextEdits: additionalTextEdits,
14857 ColorPresentation.create = create;
14859 * Checks whether the given literal conforms to the [ColorInformation](#ColorInformation) interface.
14861 function is(value) {
14862 var candidate = value;
14863 return Is.string(candidate.label)
14864 && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate))
14865 && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
14867 ColorPresentation.is = is;
14868 })(ColorPresentation || (ColorPresentation = {}));
14870 * Enum of known range kinds
14872 var FoldingRangeKind;
14873 (function (FoldingRangeKind) {
14875 * Folding range for a comment
14877 FoldingRangeKind["Comment"] = "comment";
14879 * Folding range for a imports or includes
14881 FoldingRangeKind["Imports"] = "imports";
14883 * Folding range for a region (e.g. `#region`)
14885 FoldingRangeKind["Region"] = "region";
14886 })(FoldingRangeKind || (FoldingRangeKind = {}));
14888 * The folding range namespace provides helper functions to work with
14889 * [FoldingRange](#FoldingRange) literals.
14892 (function (FoldingRange) {
14894 * Creates a new FoldingRange literal.
14896 function create(startLine, endLine, startCharacter, endCharacter, kind) {
14898 startLine: startLine,
14901 if (Is.defined(startCharacter)) {
14902 result.startCharacter = startCharacter;
14904 if (Is.defined(endCharacter)) {
14905 result.endCharacter = endCharacter;
14907 if (Is.defined(kind)) {
14908 result.kind = kind;
14912 FoldingRange.create = create;
14914 * Checks whether the given literal conforms to the [FoldingRange](#FoldingRange) interface.
14916 function is(value) {
14917 var candidate = value;
14918 return Is.number(candidate.startLine) && Is.number(candidate.startLine)
14919 && (Is.undefined(candidate.startCharacter) || Is.number(candidate.startCharacter))
14920 && (Is.undefined(candidate.endCharacter) || Is.number(candidate.endCharacter))
14921 && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
14923 FoldingRange.is = is;
14924 })(FoldingRange || (FoldingRange = {}));
14926 * The DiagnosticRelatedInformation namespace provides helper functions to work with
14927 * [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) literals.
14929 var DiagnosticRelatedInformation;
14930 (function (DiagnosticRelatedInformation) {
14932 * Creates a new DiagnosticRelatedInformation literal.
14934 function create(location, message) {
14936 location: location,
14940 DiagnosticRelatedInformation.create = create;
14942 * Checks whether the given literal conforms to the [DiagnosticRelatedInformation](#DiagnosticRelatedInformation) interface.
14944 function is(value) {
14945 var candidate = value;
14946 return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
14948 DiagnosticRelatedInformation.is = is;
14949 })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
14951 * The diagnostic's severity.
14953 var DiagnosticSeverity;
14954 (function (DiagnosticSeverity) {
14956 * Reports an error.
14958 DiagnosticSeverity.Error = 1;
14960 * Reports a warning.
14962 DiagnosticSeverity.Warning = 2;
14964 * Reports an information.
14966 DiagnosticSeverity.Information = 3;
14970 DiagnosticSeverity.Hint = 4;
14971 })(DiagnosticSeverity || (DiagnosticSeverity = {}));
14973 (function (DiagnosticTag) {
14975 * Unused or unnecessary code.
14977 * Clients are allowed to render diagnostics with this tag faded out instead of having
14978 * an error squiggle.
14980 DiagnosticTag.Unnecessary = 1;
14981 })(DiagnosticTag || (DiagnosticTag = {}));
14983 * The Diagnostic namespace provides helper functions to work with
14984 * [Diagnostic](#Diagnostic) literals.
14987 (function (Diagnostic) {
14989 * Creates a new Diagnostic literal.
14991 function create(range, message, severity, code, source, relatedInformation) {
14992 var result = { range: range, message: message };
14993 if (Is.defined(severity)) {
14994 result.severity = severity;
14996 if (Is.defined(code)) {
14997 result.code = code;
14999 if (Is.defined(source)) {
15000 result.source = source;
15002 if (Is.defined(relatedInformation)) {
15003 result.relatedInformation = relatedInformation;
15007 Diagnostic.create = create;
15009 * Checks whether the given literal conforms to the [Diagnostic](#Diagnostic) interface.
15011 function is(value) {
15012 var candidate = value;
15013 return Is.defined(candidate)
15014 && Range.is(candidate.range)
15015 && Is.string(candidate.message)
15016 && (Is.number(candidate.severity) || Is.undefined(candidate.severity))
15017 && (Is.number(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code))
15018 && (Is.string(candidate.source) || Is.undefined(candidate.source))
15019 && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
15021 Diagnostic.is = is;
15022 })(Diagnostic || (Diagnostic = {}));
15024 * The Command namespace provides helper functions to work with
15025 * [Command](#Command) literals.
15028 (function (Command) {
15030 * Creates a new Command literal.
15032 function create(title, command) {
15034 for (var _i = 2; _i < arguments.length; _i++) {
15035 args[_i - 2] = arguments[_i];
15037 var result = { title: title, command: command };
15038 if (Is.defined(args) && args.length > 0) {
15039 result.arguments = args;
15043 Command.create = create;
15045 * Checks whether the given literal conforms to the [Command](#Command) interface.
15047 function is(value) {
15048 var candidate = value;
15049 return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
15052 })(Command || (Command = {}));
15054 * The TextEdit namespace provides helper function to create replace,
15055 * insert and delete edits more easily.
15058 (function (TextEdit) {
15060 * Creates a replace text edit.
15061 * @param range The range of text to be replaced.
15062 * @param newText The new text.
15064 function replace(range, newText) {
15065 return { range: range, newText: newText };
15067 TextEdit.replace = replace;
15069 * Creates a insert text edit.
15070 * @param position The position to insert the text at.
15071 * @param newText The text to be inserted.
15073 function insert(position, newText) {
15074 return { range: { start: position, end: position }, newText: newText };
15076 TextEdit.insert = insert;
15078 * Creates a delete text edit.
15079 * @param range The range of text to be deleted.
15081 function del(range) {
15082 return { range: range, newText: '' };
15084 TextEdit.del = del;
15085 function is(value) {
15086 var candidate = value;
15087 return Is.objectLiteral(candidate)
15088 && Is.string(candidate.newText)
15089 && Range.is(candidate.range);
15092 })(TextEdit || (TextEdit = {}));
15094 * The TextDocumentEdit namespace provides helper function to create
15095 * an edit that manipulates a text document.
15097 var TextDocumentEdit;
15098 (function (TextDocumentEdit) {
15100 * Creates a new `TextDocumentEdit`
15102 function create(textDocument, edits) {
15103 return { textDocument: textDocument, edits: edits };
15105 TextDocumentEdit.create = create;
15106 function is(value) {
15107 var candidate = value;
15108 return Is.defined(candidate)
15109 && VersionedTextDocumentIdentifier.is(candidate.textDocument)
15110 && Array.isArray(candidate.edits);
15112 TextDocumentEdit.is = is;
15113 })(TextDocumentEdit || (TextDocumentEdit = {}));
15115 (function (CreateFile) {
15116 function create(uri, options) {
15121 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
15122 result.options = options;
15126 CreateFile.create = create;
15127 function is(value) {
15128 var candidate = value;
15129 return candidate && candidate.kind === 'create' && Is.string(candidate.uri) &&
15130 (candidate.options === void 0 ||
15131 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
15133 CreateFile.is = is;
15134 })(CreateFile || (CreateFile = {}));
15136 (function (RenameFile) {
15137 function create(oldUri, newUri, options) {
15143 if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
15144 result.options = options;
15148 RenameFile.create = create;
15149 function is(value) {
15150 var candidate = value;
15151 return candidate && candidate.kind === 'rename' && Is.string(candidate.oldUri) && Is.string(candidate.newUri) &&
15152 (candidate.options === void 0 ||
15153 ((candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))));
15155 RenameFile.is = is;
15156 })(RenameFile || (RenameFile = {}));
15158 (function (DeleteFile) {
15159 function create(uri, options) {
15164 if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
15165 result.options = options;
15169 DeleteFile.create = create;
15170 function is(value) {
15171 var candidate = value;
15172 return candidate && candidate.kind === 'delete' && Is.string(candidate.uri) &&
15173 (candidate.options === void 0 ||
15174 ((candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))));
15176 DeleteFile.is = is;
15177 })(DeleteFile || (DeleteFile = {}));
15179 (function (WorkspaceEdit) {
15180 function is(value) {
15181 var candidate = value;
15182 return candidate &&
15183 (candidate.changes !== void 0 || candidate.documentChanges !== void 0) &&
15184 (candidate.documentChanges === void 0 || candidate.documentChanges.every(function (change) {
15185 if (Is.string(change.kind)) {
15186 return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
15189 return TextDocumentEdit.is(change);
15193 WorkspaceEdit.is = is;
15194 })(WorkspaceEdit || (WorkspaceEdit = {}));
15195 var TextEditChangeImpl = /** @class */ (function () {
15196 function TextEditChangeImpl(edits) {
15197 this.edits = edits;
15199 TextEditChangeImpl.prototype.insert = function (position, newText) {
15200 this.edits.push(TextEdit.insert(position, newText));
15202 TextEditChangeImpl.prototype.replace = function (range, newText) {
15203 this.edits.push(TextEdit.replace(range, newText));
15205 TextEditChangeImpl.prototype.delete = function (range) {
15206 this.edits.push(TextEdit.del(range));
15208 TextEditChangeImpl.prototype.add = function (edit) {
15209 this.edits.push(edit);
15211 TextEditChangeImpl.prototype.all = function () {
15214 TextEditChangeImpl.prototype.clear = function () {
15215 this.edits.splice(0, this.edits.length);
15217 return TextEditChangeImpl;
15220 * A workspace change helps constructing changes to a workspace.
15222 var WorkspaceChange = /** @class */ (function () {
15223 function WorkspaceChange(workspaceEdit) {
15225 this._textEditChanges = Object.create(null);
15226 if (workspaceEdit) {
15227 this._workspaceEdit = workspaceEdit;
15228 if (workspaceEdit.documentChanges) {
15229 workspaceEdit.documentChanges.forEach(function (change) {
15230 if (TextDocumentEdit.is(change)) {
15231 var textEditChange = new TextEditChangeImpl(change.edits);
15232 _this._textEditChanges[change.textDocument.uri] = textEditChange;
15236 else if (workspaceEdit.changes) {
15237 Object.keys(workspaceEdit.changes).forEach(function (key) {
15238 var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
15239 _this._textEditChanges[key] = textEditChange;
15244 Object.defineProperty(WorkspaceChange.prototype, "edit", {
15246 * Returns the underlying [WorkspaceEdit](#WorkspaceEdit) literal
15247 * use to be returned from a workspace edit operation like rename.
15250 return this._workspaceEdit;
15255 WorkspaceChange.prototype.getTextEditChange = function (key) {
15256 if (VersionedTextDocumentIdentifier.is(key)) {
15257 if (!this._workspaceEdit) {
15258 this._workspaceEdit = {
15259 documentChanges: []
15262 if (!this._workspaceEdit.documentChanges) {
15263 throw new Error('Workspace edit is not configured for document changes.');
15265 var textDocument = key;
15266 var result = this._textEditChanges[textDocument.uri];
15269 var textDocumentEdit = {
15270 textDocument: textDocument,
15273 this._workspaceEdit.documentChanges.push(textDocumentEdit);
15274 result = new TextEditChangeImpl(edits);
15275 this._textEditChanges[textDocument.uri] = result;
15280 if (!this._workspaceEdit) {
15281 this._workspaceEdit = {
15282 changes: Object.create(null)
15285 if (!this._workspaceEdit.changes) {
15286 throw new Error('Workspace edit is not configured for normal text edit changes.');
15288 var result = this._textEditChanges[key];
15291 this._workspaceEdit.changes[key] = edits;
15292 result = new TextEditChangeImpl(edits);
15293 this._textEditChanges[key] = result;
15298 WorkspaceChange.prototype.createFile = function (uri, options) {
15299 this.checkDocumentChanges();
15300 this._workspaceEdit.documentChanges.push(CreateFile.create(uri, options));
15302 WorkspaceChange.prototype.renameFile = function (oldUri, newUri, options) {
15303 this.checkDocumentChanges();
15304 this._workspaceEdit.documentChanges.push(RenameFile.create(oldUri, newUri, options));
15306 WorkspaceChange.prototype.deleteFile = function (uri, options) {
15307 this.checkDocumentChanges();
15308 this._workspaceEdit.documentChanges.push(DeleteFile.create(uri, options));
15310 WorkspaceChange.prototype.checkDocumentChanges = function () {
15311 if (!this._workspaceEdit || !this._workspaceEdit.documentChanges) {
15312 throw new Error('Workspace edit is not configured for document changes.');
15315 return WorkspaceChange;
15319 * The TextDocumentIdentifier namespace provides helper functions to work with
15320 * [TextDocumentIdentifier](#TextDocumentIdentifier) literals.
15322 var TextDocumentIdentifier;
15323 (function (TextDocumentIdentifier) {
15325 * Creates a new TextDocumentIdentifier literal.
15326 * @param uri The document's uri.
15328 function create(uri) {
15329 return { uri: uri };
15331 TextDocumentIdentifier.create = create;
15333 * Checks whether the given literal conforms to the [TextDocumentIdentifier](#TextDocumentIdentifier) interface.
15335 function is(value) {
15336 var candidate = value;
15337 return Is.defined(candidate) && Is.string(candidate.uri);
15339 TextDocumentIdentifier.is = is;
15340 })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
15342 * The VersionedTextDocumentIdentifier namespace provides helper functions to work with
15343 * [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) literals.
15345 var VersionedTextDocumentIdentifier;
15346 (function (VersionedTextDocumentIdentifier) {
15348 * Creates a new VersionedTextDocumentIdentifier literal.
15349 * @param uri The document's uri.
15350 * @param uri The document's text.
15352 function create(uri, version) {
15353 return { uri: uri, version: version };
15355 VersionedTextDocumentIdentifier.create = create;
15357 * Checks whether the given literal conforms to the [VersionedTextDocumentIdentifier](#VersionedTextDocumentIdentifier) interface.
15359 function is(value) {
15360 var candidate = value;
15361 return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.number(candidate.version));
15363 VersionedTextDocumentIdentifier.is = is;
15364 })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
15366 * The TextDocumentItem namespace provides helper functions to work with
15367 * [TextDocumentItem](#TextDocumentItem) literals.
15369 var TextDocumentItem;
15370 (function (TextDocumentItem) {
15372 * Creates a new TextDocumentItem literal.
15373 * @param uri The document's uri.
15374 * @param languageId The document's language identifier.
15375 * @param version The document's version number.
15376 * @param text The document's text.
15378 function create(uri, languageId, version, text) {
15379 return { uri: uri, languageId: languageId, version: version, text: text };
15381 TextDocumentItem.create = create;
15383 * Checks whether the given literal conforms to the [TextDocumentItem](#TextDocumentItem) interface.
15385 function is(value) {
15386 var candidate = value;
15387 return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.number(candidate.version) && Is.string(candidate.text);
15389 TextDocumentItem.is = is;
15390 })(TextDocumentItem || (TextDocumentItem = {}));
15392 * Describes the content type that a client supports in various
15393 * result literals like `Hover`, `ParameterInfo` or `CompletionItem`.
15395 * Please note that `MarkupKinds` must not start with a `$`. This kinds
15396 * are reserved for internal usage.
15399 (function (MarkupKind) {
15401 * Plain text is supported as a content format
15403 MarkupKind.PlainText = 'plaintext';
15405 * Markdown is supported as a content format
15407 MarkupKind.Markdown = 'markdown';
15408 })(MarkupKind || (MarkupKind = {}));
15409 (function (MarkupKind) {
15411 * Checks whether the given value is a value of the [MarkupKind](#MarkupKind) type.
15413 function is(value) {
15414 var candidate = value;
15415 return candidate === MarkupKind.PlainText || candidate === MarkupKind.Markdown;
15417 MarkupKind.is = is;
15418 })(MarkupKind || (MarkupKind = {}));
15420 (function (MarkupContent) {
15422 * Checks whether the given value conforms to the [MarkupContent](#MarkupContent) interface.
15424 function is(value) {
15425 var candidate = value;
15426 return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
15428 MarkupContent.is = is;
15429 })(MarkupContent || (MarkupContent = {}));
15431 * The kind of a completion entry.
15433 var CompletionItemKind;
15434 (function (CompletionItemKind) {
15435 CompletionItemKind.Text = 1;
15436 CompletionItemKind.Method = 2;
15437 CompletionItemKind.Function = 3;
15438 CompletionItemKind.Constructor = 4;
15439 CompletionItemKind.Field = 5;
15440 CompletionItemKind.Variable = 6;
15441 CompletionItemKind.Class = 7;
15442 CompletionItemKind.Interface = 8;
15443 CompletionItemKind.Module = 9;
15444 CompletionItemKind.Property = 10;
15445 CompletionItemKind.Unit = 11;
15446 CompletionItemKind.Value = 12;
15447 CompletionItemKind.Enum = 13;
15448 CompletionItemKind.Keyword = 14;
15449 CompletionItemKind.Snippet = 15;
15450 CompletionItemKind.Color = 16;
15451 CompletionItemKind.File = 17;
15452 CompletionItemKind.Reference = 18;
15453 CompletionItemKind.Folder = 19;
15454 CompletionItemKind.EnumMember = 20;
15455 CompletionItemKind.Constant = 21;
15456 CompletionItemKind.Struct = 22;
15457 CompletionItemKind.Event = 23;
15458 CompletionItemKind.Operator = 24;
15459 CompletionItemKind.TypeParameter = 25;
15460 })(CompletionItemKind || (CompletionItemKind = {}));
15462 * Defines whether the insert text in a completion item should be interpreted as
15463 * plain text or a snippet.
15465 var InsertTextFormat;
15466 (function (InsertTextFormat) {
15468 * The primary text to be inserted is treated as a plain string.
15470 InsertTextFormat.PlainText = 1;
15472 * The primary text to be inserted is treated as a snippet.
15474 * A snippet can define tab stops and placeholders with `$1`, `$2`
15475 * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
15476 * the end of the snippet. Placeholders with equal identifiers are linked,
15477 * that is typing in one will update others too.
15479 * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
15481 InsertTextFormat.Snippet = 2;
15482 })(InsertTextFormat || (InsertTextFormat = {}));
15484 * The CompletionItem namespace provides functions to deal with
15485 * completion items.
15487 var CompletionItem;
15488 (function (CompletionItem) {
15490 * Create a completion item and seed it with a label.
15491 * @param label The completion item's label
15493 function create(label) {
15494 return { label: label };
15496 CompletionItem.create = create;
15497 })(CompletionItem || (CompletionItem = {}));
15499 * The CompletionList namespace provides functions to deal with
15500 * completion lists.
15502 var CompletionList;
15503 (function (CompletionList) {
15505 * Creates a new completion list.
15507 * @param items The completion items.
15508 * @param isIncomplete The list is not complete.
15510 function create(items, isIncomplete) {
15511 return { items: items ? items : [], isIncomplete: !!isIncomplete };
15513 CompletionList.create = create;
15514 })(CompletionList || (CompletionList = {}));
15516 (function (MarkedString) {
15518 * Creates a marked string from plain text.
15520 * @param plainText The plain text.
15522 function fromPlainText(plainText) {
15523 return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
15525 MarkedString.fromPlainText = fromPlainText;
15527 * Checks whether the given value conforms to the [MarkedString](#MarkedString) type.
15529 function is(value) {
15530 var candidate = value;
15531 return Is.string(candidate) || (Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value));
15533 MarkedString.is = is;
15534 })(MarkedString || (MarkedString = {}));
15536 (function (Hover) {
15538 * Checks whether the given value conforms to the [Hover](#Hover) interface.
15540 function is(value) {
15541 var candidate = value;
15542 return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) ||
15543 MarkedString.is(candidate.contents) ||
15544 Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
15547 })(Hover || (Hover = {}));
15549 * The ParameterInformation namespace provides helper functions to work with
15550 * [ParameterInformation](#ParameterInformation) literals.
15552 var ParameterInformation;
15553 (function (ParameterInformation) {
15555 * Creates a new parameter information literal.
15557 * @param label A label string.
15558 * @param documentation A doc string.
15560 function create(label, documentation) {
15561 return documentation ? { label: label, documentation: documentation } : { label: label };
15563 ParameterInformation.create = create;
15565 })(ParameterInformation || (ParameterInformation = {}));
15567 * The SignatureInformation namespace provides helper functions to work with
15568 * [SignatureInformation](#SignatureInformation) literals.
15570 var SignatureInformation;
15571 (function (SignatureInformation) {
15572 function create(label, documentation) {
15573 var parameters = [];
15574 for (var _i = 2; _i < arguments.length; _i++) {
15575 parameters[_i - 2] = arguments[_i];
15577 var result = { label: label };
15578 if (Is.defined(documentation)) {
15579 result.documentation = documentation;
15581 if (Is.defined(parameters)) {
15582 result.parameters = parameters;
15585 result.parameters = [];
15589 SignatureInformation.create = create;
15590 })(SignatureInformation || (SignatureInformation = {}));
15592 * A document highlight kind.
15594 var DocumentHighlightKind;
15595 (function (DocumentHighlightKind) {
15597 * A textual occurrence.
15599 DocumentHighlightKind.Text = 1;
15601 * Read-access of a symbol, like reading a variable.
15603 DocumentHighlightKind.Read = 2;
15605 * Write-access of a symbol, like writing to a variable.
15607 DocumentHighlightKind.Write = 3;
15608 })(DocumentHighlightKind || (DocumentHighlightKind = {}));
15610 * DocumentHighlight namespace to provide helper functions to work with
15611 * [DocumentHighlight](#DocumentHighlight) literals.
15613 var DocumentHighlight;
15614 (function (DocumentHighlight) {
15616 * Create a DocumentHighlight object.
15617 * @param range The range the highlight applies to.
15619 function create(range, kind) {
15620 var result = { range: range };
15621 if (Is.number(kind)) {
15622 result.kind = kind;
15626 DocumentHighlight.create = create;
15627 })(DocumentHighlight || (DocumentHighlight = {}));
15632 (function (SymbolKind) {
15633 SymbolKind.File = 1;
15634 SymbolKind.Module = 2;
15635 SymbolKind.Namespace = 3;
15636 SymbolKind.Package = 4;
15637 SymbolKind.Class = 5;
15638 SymbolKind.Method = 6;
15639 SymbolKind.Property = 7;
15640 SymbolKind.Field = 8;
15641 SymbolKind.Constructor = 9;
15642 SymbolKind.Enum = 10;
15643 SymbolKind.Interface = 11;
15644 SymbolKind.Function = 12;
15645 SymbolKind.Variable = 13;
15646 SymbolKind.Constant = 14;
15647 SymbolKind.String = 15;
15648 SymbolKind.Number = 16;
15649 SymbolKind.Boolean = 17;
15650 SymbolKind.Array = 18;
15651 SymbolKind.Object = 19;
15652 SymbolKind.Key = 20;
15653 SymbolKind.Null = 21;
15654 SymbolKind.EnumMember = 22;
15655 SymbolKind.Struct = 23;
15656 SymbolKind.Event = 24;
15657 SymbolKind.Operator = 25;
15658 SymbolKind.TypeParameter = 26;
15659 })(SymbolKind || (SymbolKind = {}));
15660 var SymbolInformation;
15661 (function (SymbolInformation) {
15663 * Creates a new symbol information literal.
15665 * @param name The name of the symbol.
15666 * @param kind The kind of the symbol.
15667 * @param range The range of the location of the symbol.
15668 * @param uri The resource of the location of symbol, defaults to the current document.
15669 * @param containerName The name of the symbol containing the symbol.
15671 function create(name, kind, range, uri, containerName) {
15675 location: { uri: uri, range: range }
15677 if (containerName) {
15678 result.containerName = containerName;
15682 SymbolInformation.create = create;
15683 })(SymbolInformation || (SymbolInformation = {}));
15685 * Represents programming constructs like variables, classes, interfaces etc.
15686 * that appear in a document. Document symbols can be hierarchical and they
15687 * have two ranges: one that encloses its definition and one that points to
15688 * its most interesting range, e.g. the range of an identifier.
15690 var DocumentSymbol = /** @class */ (function () {
15691 function DocumentSymbol() {
15693 return DocumentSymbol;
15696 (function (DocumentSymbol) {
15698 * Creates a new symbol information literal.
15700 * @param name The name of the symbol.
15701 * @param detail The detail of the symbol.
15702 * @param kind The kind of the symbol.
15703 * @param range The range of the symbol.
15704 * @param selectionRange The selectionRange of the symbol.
15705 * @param children Children of the symbol.
15707 function create(name, detail, kind, range, selectionRange, children) {
15713 selectionRange: selectionRange
15715 if (children !== void 0) {
15716 result.children = children;
15720 DocumentSymbol.create = create;
15722 * Checks whether the given literal conforms to the [DocumentSymbol](#DocumentSymbol) interface.
15724 function is(value) {
15725 var candidate = value;
15726 return candidate &&
15727 Is.string(candidate.name) && Is.number(candidate.kind) &&
15728 Range.is(candidate.range) && Range.is(candidate.selectionRange) &&
15729 (candidate.detail === void 0 || Is.string(candidate.detail)) &&
15730 (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) &&
15731 (candidate.children === void 0 || Array.isArray(candidate.children));
15733 DocumentSymbol.is = is;
15734 })(DocumentSymbol || (DocumentSymbol = {}));
15736 * A set of predefined code action kinds
15738 var CodeActionKind;
15739 (function (CodeActionKind) {
15741 * Base kind for quickfix actions: 'quickfix'
15743 CodeActionKind.QuickFix = 'quickfix';
15745 * Base kind for refactoring actions: 'refactor'
15747 CodeActionKind.Refactor = 'refactor';
15749 * Base kind for refactoring extraction actions: 'refactor.extract'
15751 * Example extract actions:
15754 * - Extract function
15755 * - Extract variable
15756 * - Extract interface from class
15759 CodeActionKind.RefactorExtract = 'refactor.extract';
15761 * Base kind for refactoring inline actions: 'refactor.inline'
15763 * Example inline actions:
15765 * - Inline function
15766 * - Inline variable
15767 * - Inline constant
15770 CodeActionKind.RefactorInline = 'refactor.inline';
15772 * Base kind for refactoring rewrite actions: 'refactor.rewrite'
15774 * Example rewrite actions:
15776 * - Convert JavaScript function to class
15777 * - Add or remove parameter
15778 * - Encapsulate field
15779 * - Make method static
15780 * - Move method to base class
15783 CodeActionKind.RefactorRewrite = 'refactor.rewrite';
15785 * Base kind for source actions: `source`
15787 * Source code actions apply to the entire file.
15789 CodeActionKind.Source = 'source';
15791 * Base kind for an organize imports source action: `source.organizeImports`
15793 CodeActionKind.SourceOrganizeImports = 'source.organizeImports';
15794 })(CodeActionKind || (CodeActionKind = {}));
15796 * The CodeActionContext namespace provides helper functions to work with
15797 * [CodeActionContext](#CodeActionContext) literals.
15799 var CodeActionContext;
15800 (function (CodeActionContext) {
15802 * Creates a new CodeActionContext literal.
15804 function create(diagnostics, only) {
15805 var result = { diagnostics: diagnostics };
15806 if (only !== void 0 && only !== null) {
15807 result.only = only;
15811 CodeActionContext.create = create;
15813 * Checks whether the given literal conforms to the [CodeActionContext](#CodeActionContext) interface.
15815 function is(value) {
15816 var candidate = value;
15817 return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string));
15819 CodeActionContext.is = is;
15820 })(CodeActionContext || (CodeActionContext = {}));
15822 (function (CodeAction) {
15823 function create(title, commandOrEdit, kind) {
15824 var result = { title: title };
15825 if (Command.is(commandOrEdit)) {
15826 result.command = commandOrEdit;
15829 result.edit = commandOrEdit;
15831 if (kind !== void null) {
15832 result.kind = kind;
15836 CodeAction.create = create;
15837 function is(value) {
15838 var candidate = value;
15839 return candidate && Is.string(candidate.title) &&
15840 (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) &&
15841 (candidate.kind === void 0 || Is.string(candidate.kind)) &&
15842 (candidate.edit !== void 0 || candidate.command !== void 0) &&
15843 (candidate.command === void 0 || Command.is(candidate.command)) &&
15844 (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
15846 CodeAction.is = is;
15847 })(CodeAction || (CodeAction = {}));
15849 * The CodeLens namespace provides helper functions to work with
15850 * [CodeLens](#CodeLens) literals.
15853 (function (CodeLens) {
15855 * Creates a new CodeLens literal.
15857 function create(range, data) {
15858 var result = { range: range };
15859 if (Is.defined(data))
15860 result.data = data;
15863 CodeLens.create = create;
15865 * Checks whether the given literal conforms to the [CodeLens](#CodeLens) interface.
15867 function is(value) {
15868 var candidate = value;
15869 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
15872 })(CodeLens || (CodeLens = {}));
15874 * The FormattingOptions namespace provides helper functions to work with
15875 * [FormattingOptions](#FormattingOptions) literals.
15877 var FormattingOptions;
15878 (function (FormattingOptions) {
15880 * Creates a new FormattingOptions literal.
15882 function create(tabSize, insertSpaces) {
15883 return { tabSize: tabSize, insertSpaces: insertSpaces };
15885 FormattingOptions.create = create;
15887 * Checks whether the given literal conforms to the [FormattingOptions](#FormattingOptions) interface.
15889 function is(value) {
15890 var candidate = value;
15891 return Is.defined(candidate) && Is.number(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
15893 FormattingOptions.is = is;
15894 })(FormattingOptions || (FormattingOptions = {}));
15896 * A document link is a range in a text document that links to an internal or external resource, like another
15897 * text document or a web site.
15899 var DocumentLink = /** @class */ (function () {
15900 function DocumentLink() {
15902 return DocumentLink;
15906 * The DocumentLink namespace provides helper functions to work with
15907 * [DocumentLink](#DocumentLink) literals.
15909 (function (DocumentLink) {
15911 * Creates a new DocumentLink literal.
15913 function create(range, target, data) {
15914 return { range: range, target: target, data: data };
15916 DocumentLink.create = create;
15918 * Checks whether the given literal conforms to the [DocumentLink](#DocumentLink) interface.
15920 function is(value) {
15921 var candidate = value;
15922 return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
15924 DocumentLink.is = is;
15925 })(DocumentLink || (DocumentLink = {}));
15927 * The SelectionRange namespace provides helper function to work with
15928 * SelectionRange literals.
15930 var SelectionRange;
15931 (function (SelectionRange) {
15933 * Creates a new SelectionRange
15934 * @param range the range.
15935 * @param parent an optional parent.
15937 function create(range, parent) {
15938 return { range: range, parent: parent };
15940 SelectionRange.create = create;
15941 function is(value) {
15942 var candidate = value;
15943 return candidate !== undefined && Range.is(candidate.range) && (candidate.parent === undefined || SelectionRange.is(candidate.parent));
15945 SelectionRange.is = is;
15946 })(SelectionRange || (SelectionRange = {}));
15947 var EOL = ['\n', '\r\n', '\r'];
15949 (function (TextDocument) {
15951 * Creates a new ITextDocument literal from the given uri and content.
15952 * @param uri The document's uri.
15953 * @param languageId The document's language Id.
15954 * @param content The document's content.
15956 function create(uri, languageId, version, content) {
15957 return new FullTextDocument(uri, languageId, version, content);
15959 TextDocument.create = create;
15961 * Checks whether the given literal conforms to the [ITextDocument](#ITextDocument) interface.
15963 function is(value) {
15964 var candidate = value;
15965 return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.number(candidate.lineCount)
15966 && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
15968 TextDocument.is = is;
15969 function applyEdits(document, edits) {
15970 var text = document.getText();
15971 var sortedEdits = mergeSort(edits, function (a, b) {
15972 var diff = a.range.start.line - b.range.start.line;
15974 return a.range.start.character - b.range.start.character;
15978 var lastModifiedOffset = text.length;
15979 for (var i = sortedEdits.length - 1; i >= 0; i--) {
15980 var e = sortedEdits[i];
15981 var startOffset = document.offsetAt(e.range.start);
15982 var endOffset = document.offsetAt(e.range.end);
15983 if (endOffset <= lastModifiedOffset) {
15984 text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
15987 throw new Error('Overlapping edit');
15989 lastModifiedOffset = startOffset;
15993 TextDocument.applyEdits = applyEdits;
15994 function mergeSort(data, compare) {
15995 if (data.length <= 1) {
15999 var p = (data.length / 2) | 0;
16000 var left = data.slice(0, p);
16001 var right = data.slice(p);
16002 mergeSort(left, compare);
16003 mergeSort(right, compare);
16007 while (leftIdx < left.length && rightIdx < right.length) {
16008 var ret = compare(left[leftIdx], right[rightIdx]);
16010 // smaller_equal -> take left to preserve order
16011 data[i++] = left[leftIdx++];
16014 // greater -> take right
16015 data[i++] = right[rightIdx++];
16018 while (leftIdx < left.length) {
16019 data[i++] = left[leftIdx++];
16021 while (rightIdx < right.length) {
16022 data[i++] = right[rightIdx++];
16026 })(TextDocument || (TextDocument = {}));
16028 * Represents reasons why a text document is saved.
16030 var TextDocumentSaveReason;
16031 (function (TextDocumentSaveReason) {
16033 * Manually triggered, e.g. by the user pressing save, by starting debugging,
16034 * or by an API call.
16036 TextDocumentSaveReason.Manual = 1;
16038 * Automatic after a delay.
16040 TextDocumentSaveReason.AfterDelay = 2;
16042 * When the editor lost focus.
16044 TextDocumentSaveReason.FocusOut = 3;
16045 })(TextDocumentSaveReason || (TextDocumentSaveReason = {}));
16046 var FullTextDocument = /** @class */ (function () {
16047 function FullTextDocument(uri, languageId, version, content) {
16049 this._languageId = languageId;
16050 this._version = version;
16051 this._content = content;
16052 this._lineOffsets = null;
16054 Object.defineProperty(FullTextDocument.prototype, "uri", {
16061 Object.defineProperty(FullTextDocument.prototype, "languageId", {
16063 return this._languageId;
16068 Object.defineProperty(FullTextDocument.prototype, "version", {
16070 return this._version;
16075 FullTextDocument.prototype.getText = function (range) {
16077 var start = this.offsetAt(range.start);
16078 var end = this.offsetAt(range.end);
16079 return this._content.substring(start, end);
16081 return this._content;
16083 FullTextDocument.prototype.update = function (event, version) {
16084 this._content = event.text;
16085 this._version = version;
16086 this._lineOffsets = null;
16088 FullTextDocument.prototype.getLineOffsets = function () {
16089 if (this._lineOffsets === null) {
16090 var lineOffsets = [];
16091 var text = this._content;
16092 var isLineStart = true;
16093 for (var i = 0; i < text.length; i++) {
16095 lineOffsets.push(i);
16096 isLineStart = false;
16098 var ch = text.charAt(i);
16099 isLineStart = (ch === '\r' || ch === '\n');
16100 if (ch === '\r' && i + 1 < text.length && text.charAt(i + 1) === '\n') {
16104 if (isLineStart && text.length > 0) {
16105 lineOffsets.push(text.length);
16107 this._lineOffsets = lineOffsets;
16109 return this._lineOffsets;
16111 FullTextDocument.prototype.positionAt = function (offset) {
16112 offset = Math.max(Math.min(offset, this._content.length), 0);
16113 var lineOffsets = this.getLineOffsets();
16114 var low = 0, high = lineOffsets.length;
16116 return Position.create(0, offset);
16118 while (low < high) {
16119 var mid = Math.floor((low + high) / 2);
16120 if (lineOffsets[mid] > offset) {
16127 // low is the least x for which the line offset is larger than the current offset
16128 // or array.length if no line offset is larger than the current offset
16129 var line = low - 1;
16130 return Position.create(line, offset - lineOffsets[line]);
16132 FullTextDocument.prototype.offsetAt = function (position) {
16133 var lineOffsets = this.getLineOffsets();
16134 if (position.line >= lineOffsets.length) {
16135 return this._content.length;
16137 else if (position.line < 0) {
16140 var lineOffset = lineOffsets[position.line];
16141 var nextLineOffset = (position.line + 1 < lineOffsets.length) ? lineOffsets[position.line + 1] : this._content.length;
16142 return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
16144 Object.defineProperty(FullTextDocument.prototype, "lineCount", {
16146 return this.getLineOffsets().length;
16151 return FullTextDocument;
16155 var toString = Object.prototype.toString;
16156 function defined(value) {
16157 return typeof value !== 'undefined';
16159 Is.defined = defined;
16160 function undefined(value) {
16161 return typeof value === 'undefined';
16163 Is.undefined = undefined;
16164 function boolean(value) {
16165 return value === true || value === false;
16167 Is.boolean = boolean;
16168 function string(value) {
16169 return toString.call(value) === '[object String]';
16171 Is.string = string;
16172 function number(value) {
16173 return toString.call(value) === '[object Number]';
16175 Is.number = number;
16176 function func(value) {
16177 return toString.call(value) === '[object Function]';
16180 function objectLiteral(value) {
16181 // Strictly speaking class instances pass this check as well. Since the LSP
16182 // doesn't use classes we ignore this for now. If we do we need to add something
16183 // like this: `Object.getPrototypeOf(Object.getPrototypeOf(x)) === null`
16184 return value !== null && typeof value === 'object';
16186 Is.objectLiteral = objectLiteral;
16187 function typedArray(value, check) {
16188 return Array.isArray(value) && value.every(check);
16190 Is.typedArray = typedArray;
16191 })(Is || (Is = {}));
16196 /***/ (function(module, __webpack_exports__, __webpack_require__) {
16199 __webpack_require__.r(__webpack_exports__);
16200 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONCompletion", function() { return JSONCompletion; });
16201 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82);
16202 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(83);
16203 /* harmony import */ var _utils_json__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(90);
16204 /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(91);
16205 /* harmony import */ var _utils_objects__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(88);
16206 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(80);
16207 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(76);
16208 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_6__);
16209 /*---------------------------------------------------------------------------------------------
16210 * Copyright (c) Microsoft Corporation. All rights reserved.
16211 * Licensed under the MIT License. See License.txt in the project root for license information.
16212 *--------------------------------------------------------------------------------------------*/
16220 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_6__["loadMessageBundle"]();
16221 var JSONCompletion = /** @class */ (function () {
16222 function JSONCompletion(schemaService, contributions, promiseConstructor, clientCapabilities) {
16223 if (contributions === void 0) { contributions = []; }
16224 if (promiseConstructor === void 0) { promiseConstructor = Promise; }
16225 if (clientCapabilities === void 0) { clientCapabilities = {}; }
16226 this.schemaService = schemaService;
16227 this.contributions = contributions;
16228 this.promiseConstructor = promiseConstructor;
16229 this.clientCapabilities = clientCapabilities;
16230 this.templateVarIdCounter = 0;
16232 JSONCompletion.prototype.doResolve = function (item) {
16233 for (var i = this.contributions.length - 1; i >= 0; i--) {
16234 if (this.contributions[i].resolveCompletion) {
16235 var resolver = this.contributions[i].resolveCompletion(item);
16241 return this.promiseConstructor.resolve(item);
16243 JSONCompletion.prototype.doComplete = function (document, position, doc) {
16247 isIncomplete: false
16249 var offset = document.offsetAt(position);
16250 var node = doc.getNodeFromOffset(offset, true);
16251 if (this.isInComment(document, node ? node.offset : 0, offset)) {
16252 return Promise.resolve(result);
16254 var currentWord = this.getCurrentWord(document, offset);
16255 var overwriteRange = null;
16256 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
16257 overwriteRange = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["Range"].create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
16260 var overwriteStart = offset - currentWord.length;
16261 if (overwriteStart > 0 && document.getText()[overwriteStart - 1] === '"') {
16264 overwriteRange = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["Range"].create(document.positionAt(overwriteStart), position);
16268 add: function (suggestion) {
16269 var existing = proposed[suggestion.label];
16271 proposed[suggestion.label] = suggestion;
16272 if (overwriteRange) {
16273 suggestion.textEdit = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["TextEdit"].replace(overwriteRange, suggestion.insertText);
16275 result.items.push(suggestion);
16277 else if (!existing.documentation) {
16278 existing.documentation = suggestion.documentation;
16281 setAsIncomplete: function () {
16282 result.isIncomplete = true;
16284 error: function (message) {
16285 console.error(message);
16287 log: function (message) {
16288 console.log(message);
16290 getNumberOfProposals: function () {
16291 return result.items.length;
16294 return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
16295 var collectionPromises = [];
16296 var addValue = true;
16297 var currentKey = '';
16298 var currentProperty = null;
16300 if (node.type === 'string') {
16301 var parent = node.parent;
16302 if (parent && parent.type === 'property' && parent.keyNode === node) {
16303 addValue = !parent.valueNode;
16304 currentProperty = parent;
16305 currentKey = document.getText().substr(node.offset + 1, node.length - 2);
16307 node = parent.parent;
16312 // proposals for properties
16313 if (node && node.type === 'object') {
16314 // don't suggest keys when the cursor is just before the opening curly brace
16315 if (node.offset === offset) {
16318 // don't suggest properties that are already present
16319 var properties = node.properties;
16320 properties.forEach(function (p) {
16321 if (!currentProperty || currentProperty !== p) {
16322 proposed[p.keyNode.value] = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItem"].create('__');
16325 var separatorAfter_1 = '';
16327 separatorAfter_1 = _this.evaluateSeparatorAfter(document, document.offsetAt(overwriteRange.end));
16330 // property proposals with schema
16331 _this.getPropertyCompletions(schema, doc, node, addValue, separatorAfter_1, collector);
16334 // property proposals without schema
16335 _this.getSchemaLessPropertyCompletions(doc, node, currentKey, collector);
16337 var location_1 = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
16338 _this.contributions.forEach(function (contribution) {
16339 var collectPromise = contribution.collectPropertyCompletions(document.uri, location_1, currentWord, addValue, separatorAfter_1 === '', collector);
16340 if (collectPromise) {
16341 collectionPromises.push(collectPromise);
16344 if ((!schema && currentWord.length > 0 && document.getText().charAt(offset - currentWord.length - 1) !== '"')) {
16346 kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
16347 label: _this.getLabelForValue(currentWord),
16348 insertText: _this.getInsertTextForProperty(currentWord, null, false, separatorAfter_1),
16349 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: '',
16351 collector.setAsIncomplete();
16354 // proposals for values
16357 // value proposals with schema
16358 _this.getValueCompletions(schema, doc, node, offset, document, collector, types);
16361 // value proposals without schema
16362 _this.getSchemaLessValueCompletions(doc, node, offset, document, collector);
16364 if (_this.contributions.length > 0) {
16365 _this.getContributedValueCompletions(doc, node, offset, document, collector, collectionPromises);
16367 return _this.promiseConstructor.all(collectionPromises).then(function () {
16368 if (collector.getNumberOfProposals() === 0) {
16369 var offsetForSeparator = offset;
16370 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
16371 offsetForSeparator = node.offset + node.length;
16373 var separatorAfter = _this.evaluateSeparatorAfter(document, offsetForSeparator);
16374 _this.addFillerValueCompletions(types, separatorAfter, collector);
16380 JSONCompletion.prototype.getPropertyCompletions = function (schema, doc, node, addValue, separatorAfter, collector) {
16382 var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
16383 matchingSchemas.forEach(function (s) {
16384 if (s.node === node && !s.inverted) {
16385 var schemaProperties_1 = s.schema.properties;
16386 if (schemaProperties_1) {
16387 Object.keys(schemaProperties_1).forEach(function (key) {
16388 var propertySchema = schemaProperties_1[key];
16389 if (typeof propertySchema === 'object' && !propertySchema.deprecationMessage && !propertySchema.doNotSuggest) {
16391 kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
16392 label: _this.sanitizeLabel(key),
16393 insertText: _this.getInsertTextForProperty(key, propertySchema, addValue, separatorAfter),
16394 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16395 filterText: _this.getFilterTextForValue(key),
16396 documentation: _this.fromMarkup(propertySchema.markdownDescription) || propertySchema.description || '',
16398 if (Object(_utils_strings__WEBPACK_IMPORTED_MODULE_3__["endsWith"])(proposal.insertText, "$1" + separatorAfter)) {
16399 proposal.command = {
16401 command: 'editor.action.triggerSuggest'
16404 collector.add(proposal);
16411 JSONCompletion.prototype.getSchemaLessPropertyCompletions = function (doc, node, currentKey, collector) {
16413 var collectCompletionsForSimilarObject = function (obj) {
16414 obj.properties.forEach(function (p) {
16415 var key = p.keyNode.value;
16417 kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
16418 label: _this.sanitizeLabel(key),
16419 insertText: _this.getInsertTextForValue(key, ''),
16420 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16421 filterText: _this.getFilterTextForValue(key),
16427 if (node.parent.type === 'property') {
16428 // if the object is a property value, check the tree for other objects that hang under a property of the same name
16429 var parentKey_1 = node.parent.keyNode.value;
16430 doc.visit(function (n) {
16431 if (n.type === 'property' && n !== node.parent && n.keyNode.value === parentKey_1 && n.valueNode && n.valueNode.type === 'object') {
16432 collectCompletionsForSimilarObject(n.valueNode);
16437 else if (node.parent.type === 'array') {
16438 // if the object is in an array, use all other array elements as similar objects
16439 node.parent.items.forEach(function (n) {
16440 if (n.type === 'object' && n !== node) {
16441 collectCompletionsForSimilarObject(n);
16446 else if (node.type === 'object') {
16448 kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property,
16450 insertText: this.getInsertTextForProperty('$schema', null, true, ''),
16451 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: '',
16452 filterText: this.getFilterTextForValue("$schema")
16456 JSONCompletion.prototype.getSchemaLessValueCompletions = function (doc, node, offset, document, collector) {
16458 var offsetForSeparator = offset;
16459 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
16460 offsetForSeparator = node.offset + node.length;
16461 node = node.parent;
16465 kind: this.getSuggestionKind('object'),
16466 label: 'Empty object',
16467 insertText: this.getInsertTextForValue({}, ''),
16468 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16472 kind: this.getSuggestionKind('array'),
16473 label: 'Empty array',
16474 insertText: this.getInsertTextForValue([], ''),
16475 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16480 var separatorAfter = this.evaluateSeparatorAfter(document, offsetForSeparator);
16481 var collectSuggestionsForValues = function (value) {
16482 if (!_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["contains"](value.parent, offset, true)) {
16484 kind: _this.getSuggestionKind(value.type),
16485 label: _this.getLabelTextForMatchingNode(value, document),
16486 insertText: _this.getInsertTextForMatchingNode(value, document, separatorAfter),
16487 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: ''
16490 if (value.type === 'boolean') {
16491 _this.addBooleanValueCompletion(!value.value, separatorAfter, collector);
16494 if (node.type === 'property') {
16495 if (offset > node.colonOffset) {
16496 var valueNode = node.valueNode;
16497 if (valueNode && (offset > (valueNode.offset + valueNode.length) || valueNode.type === 'object' || valueNode.type === 'array')) {
16500 // suggest values at the same key
16501 var parentKey_2 = node.keyNode.value;
16502 doc.visit(function (n) {
16503 if (n.type === 'property' && n.keyNode.value === parentKey_2 && n.valueNode) {
16504 collectSuggestionsForValues(n.valueNode);
16508 if (parentKey_2 === '$schema' && node.parent && !node.parent.parent) {
16509 this.addDollarSchemaCompletions(separatorAfter, collector);
16513 if (node.type === 'array') {
16514 if (node.parent && node.parent.type === 'property') {
16515 // suggest items of an array at the same key
16516 var parentKey_3 = node.parent.keyNode.value;
16517 doc.visit(function (n) {
16518 if (n.type === 'property' && n.keyNode.value === parentKey_3 && n.valueNode && n.valueNode.type === 'array') {
16519 n.valueNode.items.forEach(collectSuggestionsForValues);
16525 // suggest items in the same array
16526 node.items.forEach(collectSuggestionsForValues);
16530 JSONCompletion.prototype.getValueCompletions = function (schema, doc, node, offset, document, collector, types) {
16532 var offsetForSeparator = offset;
16533 var parentKey = null;
16534 var valueNode = null;
16535 if (node && (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
16536 offsetForSeparator = node.offset + node.length;
16538 node = node.parent;
16541 this.addSchemaValueCompletions(schema.schema, '', collector, types);
16544 if ((node.type === 'property') && offset > node.colonOffset) {
16545 var valueNode_1 = node.valueNode;
16546 if (valueNode_1 && offset > (valueNode_1.offset + valueNode_1.length)) {
16547 return; // we are past the value node
16549 parentKey = node.keyNode.value;
16550 node = node.parent;
16552 if (node && (parentKey !== null || node.type === 'array')) {
16553 var separatorAfter_2 = this.evaluateSeparatorAfter(document, offsetForSeparator);
16554 var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset, valueNode);
16555 matchingSchemas.forEach(function (s) {
16556 if (s.node === node && !s.inverted && s.schema) {
16557 if (node.type === 'array' && s.schema.items) {
16558 if (Array.isArray(s.schema.items)) {
16559 var index = _this.findItemAtOffset(node, document, offset);
16560 if (index < s.schema.items.length) {
16561 _this.addSchemaValueCompletions(s.schema.items[index], separatorAfter_2, collector, types);
16565 _this.addSchemaValueCompletions(s.schema.items, separatorAfter_2, collector, types);
16568 if (s.schema.properties) {
16569 var propertySchema = s.schema.properties[parentKey];
16570 if (propertySchema) {
16571 _this.addSchemaValueCompletions(propertySchema, separatorAfter_2, collector, types);
16576 if (parentKey === '$schema' && !node.parent) {
16577 this.addDollarSchemaCompletions(separatorAfter_2, collector);
16579 if (types['boolean']) {
16580 this.addBooleanValueCompletion(true, separatorAfter_2, collector);
16581 this.addBooleanValueCompletion(false, separatorAfter_2, collector);
16583 if (types['null']) {
16584 this.addNullValueCompletion(separatorAfter_2, collector);
16588 JSONCompletion.prototype.getContributedValueCompletions = function (doc, node, offset, document, collector, collectionPromises) {
16590 this.contributions.forEach(function (contribution) {
16591 var collectPromise = contribution.collectDefaultCompletions(document.uri, collector);
16592 if (collectPromise) {
16593 collectionPromises.push(collectPromise);
16598 if (node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null') {
16599 node = node.parent;
16601 if ((node.type === 'property') && offset > node.colonOffset) {
16602 var parentKey_4 = node.keyNode.value;
16603 var valueNode = node.valueNode;
16604 if (!valueNode || offset <= (valueNode.offset + valueNode.length)) {
16605 var location_2 = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node.parent);
16606 this.contributions.forEach(function (contribution) {
16607 var collectPromise = contribution.collectValueCompletions(document.uri, location_2, parentKey_4, collector);
16608 if (collectPromise) {
16609 collectionPromises.push(collectPromise);
16616 JSONCompletion.prototype.addSchemaValueCompletions = function (schema, separatorAfter, collector, types) {
16618 if (typeof schema === 'object') {
16619 this.addEnumValueCompletions(schema, separatorAfter, collector);
16620 this.addDefaultValueCompletions(schema, separatorAfter, collector);
16621 this.collectTypes(schema, types);
16622 if (Array.isArray(schema.allOf)) {
16623 schema.allOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
16625 if (Array.isArray(schema.anyOf)) {
16626 schema.anyOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
16628 if (Array.isArray(schema.oneOf)) {
16629 schema.oneOf.forEach(function (s) { return _this.addSchemaValueCompletions(s, separatorAfter, collector, types); });
16633 JSONCompletion.prototype.addDefaultValueCompletions = function (schema, separatorAfter, collector, arrayDepth) {
16635 if (arrayDepth === void 0) { arrayDepth = 0; }
16636 var hasProposals = false;
16637 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.default)) {
16638 var type = schema.type;
16639 var value = schema.default;
16640 for (var i = arrayDepth; i > 0; i--) {
16645 kind: this.getSuggestionKind(type),
16646 label: this.getLabelForValue(value),
16647 insertText: this.getInsertTextForValue(value, separatorAfter),
16648 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16649 detail: localize('json.suggest.default', 'Default value')
16651 hasProposals = true;
16653 if (Array.isArray(schema.examples)) {
16654 schema.examples.forEach(function (example) {
16655 var type = schema.type;
16656 var value = example;
16657 for (var i = arrayDepth; i > 0; i--) {
16662 kind: _this.getSuggestionKind(type),
16663 label: _this.getLabelForValue(value),
16664 insertText: _this.getInsertTextForValue(value, separatorAfter),
16665 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet
16667 hasProposals = true;
16670 if (Array.isArray(schema.defaultSnippets)) {
16671 schema.defaultSnippets.forEach(function (s) {
16672 var type = schema.type;
16673 var value = s.body;
16674 var label = s.label;
16677 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(value)) {
16678 var type_1 = schema.type;
16679 for (var i = arrayDepth; i > 0; i--) {
16683 insertText = _this.getInsertTextForSnippetValue(value, separatorAfter);
16684 filterText = _this.getFilterTextForSnippetValue(value);
16685 label = label || _this.getLabelForSnippetValue(value);
16687 else if (typeof s.bodyText === 'string') {
16688 var prefix = '', suffix = '', indent = '';
16689 for (var i = arrayDepth; i > 0; i--) {
16690 prefix = prefix + indent + '[\n';
16691 suffix = suffix + '\n' + indent + ']';
16695 insertText = prefix + indent + s.bodyText.split('\n').join('\n' + indent) + suffix + separatorAfter;
16696 label = label || _this.sanitizeLabel(insertText),
16697 filterText = insertText.replace(/[\n]/g, ''); // remove new lines
16700 kind: _this.getSuggestionKind(type),
16702 documentation: _this.fromMarkup(s.markdownDescription) || s.description,
16703 insertText: insertText,
16704 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16705 filterText: filterText
16707 hasProposals = true;
16710 if (!hasProposals && typeof schema.items === 'object' && !Array.isArray(schema.items)) {
16711 this.addDefaultValueCompletions(schema.items, separatorAfter, collector, arrayDepth + 1);
16714 JSONCompletion.prototype.addEnumValueCompletions = function (schema, separatorAfter, collector) {
16715 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.const)) {
16717 kind: this.getSuggestionKind(schema.type),
16718 label: this.getLabelForValue(schema.const),
16719 insertText: this.getInsertTextForValue(schema.const, separatorAfter),
16720 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16721 documentation: this.fromMarkup(schema.markdownDescription) || schema.description
16724 if (Array.isArray(schema.enum)) {
16725 for (var i = 0, length = schema.enum.length; i < length; i++) {
16726 var enm = schema.enum[i];
16727 var documentation = this.fromMarkup(schema.markdownDescription) || schema.description;
16728 if (schema.markdownEnumDescriptions && i < schema.markdownEnumDescriptions.length && this.doesSupportMarkdown()) {
16729 documentation = this.fromMarkup(schema.markdownEnumDescriptions[i]);
16731 else if (schema.enumDescriptions && i < schema.enumDescriptions.length) {
16732 documentation = schema.enumDescriptions[i];
16735 kind: this.getSuggestionKind(schema.type),
16736 label: this.getLabelForValue(enm),
16737 insertText: this.getInsertTextForValue(enm, separatorAfter),
16738 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16739 documentation: documentation
16744 JSONCompletion.prototype.collectTypes = function (schema, types) {
16745 if (Array.isArray(schema.enum) || Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(schema.const)) {
16748 var type = schema.type;
16749 if (Array.isArray(type)) {
16750 type.forEach(function (t) { return types[t] = true; });
16753 types[type] = true;
16756 JSONCompletion.prototype.addFillerValueCompletions = function (types, separatorAfter, collector) {
16757 if (types['object']) {
16759 kind: this.getSuggestionKind('object'),
16761 insertText: this.getInsertTextForGuessedValue({}, separatorAfter),
16762 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16763 detail: localize('defaults.object', 'New object'),
16767 if (types['array']) {
16769 kind: this.getSuggestionKind('array'),
16771 insertText: this.getInsertTextForGuessedValue([], separatorAfter),
16772 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16773 detail: localize('defaults.array', 'New array'),
16778 JSONCompletion.prototype.addBooleanValueCompletion = function (value, separatorAfter, collector) {
16780 kind: this.getSuggestionKind('boolean'),
16781 label: value ? 'true' : 'false',
16782 insertText: this.getInsertTextForValue(value, separatorAfter),
16783 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16787 JSONCompletion.prototype.addNullValueCompletion = function (separatorAfter, collector) {
16789 kind: this.getSuggestionKind('null'),
16791 insertText: 'null' + separatorAfter,
16792 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet,
16796 JSONCompletion.prototype.addDollarSchemaCompletions = function (separatorAfter, collector) {
16798 var schemaIds = this.schemaService.getRegisteredSchemaIds(function (schema) { return schema === 'http' || schema === 'https'; });
16799 schemaIds.forEach(function (schemaId) { return collector.add({
16800 kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Module,
16801 label: _this.getLabelForValue(schemaId),
16802 filterText: _this.getFilterTextForValue(schemaId),
16803 insertText: _this.getInsertTextForValue(schemaId, separatorAfter),
16804 insertTextFormat: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["InsertTextFormat"].Snippet, documentation: ''
16807 JSONCompletion.prototype.sanitizeLabel = function (label) {
16808 label = label.replace(/[\n]/g, '↵');
16809 if (label.length > 57) {
16810 label = label.substr(0, 57).trim() + '...';
16814 JSONCompletion.prototype.getLabelForValue = function (value) {
16815 return this.sanitizeLabel(JSON.stringify(value));
16817 JSONCompletion.prototype.getFilterTextForValue = function (value) {
16818 return JSON.stringify(value);
16820 JSONCompletion.prototype.getFilterTextForSnippetValue = function (value) {
16821 return JSON.stringify(value).replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
16823 JSONCompletion.prototype.getLabelForSnippetValue = function (value) {
16824 var label = JSON.stringify(value);
16825 label = label.replace(/\$\{\d+:([^}]+)\}|\$\d+/g, '$1');
16826 return this.sanitizeLabel(label);
16828 JSONCompletion.prototype.getInsertTextForPlainText = function (text) {
16829 return text.replace(/[\\\$\}]/g, '\\$&'); // escape $, \ and }
16831 JSONCompletion.prototype.getInsertTextForValue = function (value, separatorAfter) {
16832 var text = JSON.stringify(value, null, '\t');
16833 if (text === '{}') {
16834 return '{$1}' + separatorAfter;
16836 else if (text === '[]') {
16837 return '[$1]' + separatorAfter;
16839 return this.getInsertTextForPlainText(text + separatorAfter);
16841 JSONCompletion.prototype.getInsertTextForSnippetValue = function (value, separatorAfter) {
16842 var replacer = function (value) {
16843 if (typeof value === 'string') {
16844 if (value[0] === '^') {
16845 return value.substr(1);
16848 return JSON.stringify(value);
16850 return Object(_utils_json__WEBPACK_IMPORTED_MODULE_2__["stringifyObject"])(value, '', replacer) + separatorAfter;
16852 JSONCompletion.prototype.getInsertTextForGuessedValue = function (value, separatorAfter) {
16853 switch (typeof value) {
16855 if (value === null) {
16856 return '${1:null}' + separatorAfter;
16858 return this.getInsertTextForValue(value, separatorAfter);
16860 var snippetValue = JSON.stringify(value);
16861 snippetValue = snippetValue.substr(1, snippetValue.length - 2); // remove quotes
16862 snippetValue = this.getInsertTextForPlainText(snippetValue); // escape \ and }
16863 return '"${1:' + snippetValue + '}"' + separatorAfter;
16866 return '${1:' + JSON.stringify(value) + '}' + separatorAfter;
16868 return this.getInsertTextForValue(value, separatorAfter);
16870 JSONCompletion.prototype.getSuggestionKind = function (type) {
16871 if (Array.isArray(type)) {
16873 type = array.length > 0 ? array[0] : null;
16876 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
16879 case 'string': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
16880 case 'object': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Module;
16881 case 'property': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Property;
16882 default: return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["CompletionItemKind"].Value;
16885 JSONCompletion.prototype.getLabelTextForMatchingNode = function (node, document) {
16886 switch (node.type) {
16892 var content = document.getText().substr(node.offset, node.length);
16896 JSONCompletion.prototype.getInsertTextForMatchingNode = function (node, document, separatorAfter) {
16897 switch (node.type) {
16899 return this.getInsertTextForValue([], separatorAfter);
16901 return this.getInsertTextForValue({}, separatorAfter);
16903 var content = document.getText().substr(node.offset, node.length) + separatorAfter;
16904 return this.getInsertTextForPlainText(content);
16907 JSONCompletion.prototype.getInsertTextForProperty = function (key, propertySchema, addValue, separatorAfter) {
16908 var propertyText = this.getInsertTextForValue(key, '');
16910 return propertyText;
16912 var resultText = propertyText + ': ';
16914 var nValueProposals = 0;
16915 if (propertySchema) {
16916 if (Array.isArray(propertySchema.defaultSnippets)) {
16917 if (propertySchema.defaultSnippets.length === 1) {
16918 var body = propertySchema.defaultSnippets[0].body;
16919 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(body)) {
16920 value = this.getInsertTextForSnippetValue(body, '');
16923 nValueProposals += propertySchema.defaultSnippets.length;
16925 if (propertySchema.enum) {
16926 if (!value && propertySchema.enum.length === 1) {
16927 value = this.getInsertTextForGuessedValue(propertySchema.enum[0], '');
16929 nValueProposals += propertySchema.enum.length;
16931 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(propertySchema.default)) {
16933 value = this.getInsertTextForGuessedValue(propertySchema.default, '');
16937 if (nValueProposals === 0) {
16938 var type = Array.isArray(propertySchema.type) ? propertySchema.type[0] : propertySchema.type;
16940 if (propertySchema.properties) {
16943 else if (propertySchema.items) {
16965 value = '${1:null}';
16968 return propertyText;
16972 if (!value || nValueProposals > 1) {
16975 return resultText + value + separatorAfter;
16977 JSONCompletion.prototype.getCurrentWord = function (document, offset) {
16978 var i = offset - 1;
16979 var text = document.getText();
16980 while (i >= 0 && ' \t\n\r\v":{[,]}'.indexOf(text.charAt(i)) === -1) {
16983 return text.substring(i + 1, offset);
16985 JSONCompletion.prototype.evaluateSeparatorAfter = function (document, offset) {
16986 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), true);
16987 scanner.setPosition(offset);
16988 var token = scanner.scan();
16990 case 5 /* CommaToken */:
16991 case 2 /* CloseBraceToken */:
16992 case 4 /* CloseBracketToken */:
16999 JSONCompletion.prototype.findItemAtOffset = function (node, document, offset) {
17000 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), true);
17001 var children = node.items;
17002 for (var i = children.length - 1; i >= 0; i--) {
17003 var child = children[i];
17004 if (offset > child.offset + child.length) {
17005 scanner.setPosition(child.offset + child.length);
17006 var token = scanner.scan();
17007 if (token === 5 /* CommaToken */ && offset >= scanner.getTokenOffset() + scanner.getTokenLength()) {
17012 else if (offset >= child.offset) {
17018 JSONCompletion.prototype.isInComment = function (document, start, offset) {
17019 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"](document.getText(), false);
17020 scanner.setPosition(start);
17021 var token = scanner.scan();
17022 while (token !== 17 /* EOF */ && (scanner.getTokenOffset() + scanner.getTokenLength() < offset)) {
17023 token = scanner.scan();
17025 return (token === 12 /* LineCommentTrivia */ || token === 13 /* BlockCommentTrivia */) && scanner.getTokenOffset() <= offset;
17027 JSONCompletion.prototype.fromMarkup = function (markupString) {
17028 if (markupString && this.doesSupportMarkdown()) {
17030 kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["MarkupKind"].Markdown,
17031 value: markupString
17036 JSONCompletion.prototype.doesSupportMarkdown = function () {
17037 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_4__["isDefined"])(this.supportsMarkdown)) {
17038 var completion = this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.completion;
17039 this.supportsMarkdown = completion && completion.completionItem && Array.isArray(completion.completionItem.documentationFormat) && completion.completionItem.documentationFormat.indexOf(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_5__["MarkupKind"].Markdown) !== -1;
17041 return this.supportsMarkdown;
17043 return JSONCompletion;
17050 /***/ (function(module, __webpack_exports__, __webpack_require__) {
17053 __webpack_require__.r(__webpack_exports__);
17054 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ASTNodeImpl", function() { return ASTNodeImpl; });
17055 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullASTNodeImpl", function() { return NullASTNodeImpl; });
17056 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BooleanASTNodeImpl", function() { return BooleanASTNodeImpl; });
17057 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrayASTNodeImpl", function() { return ArrayASTNodeImpl; });
17058 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NumberASTNodeImpl", function() { return NumberASTNodeImpl; });
17059 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringASTNodeImpl", function() { return StringASTNodeImpl; });
17060 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PropertyASTNodeImpl", function() { return PropertyASTNodeImpl; });
17061 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectASTNodeImpl", function() { return ObjectASTNodeImpl; });
17062 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asSchema", function() { return asSchema; });
17063 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnumMatch", function() { return EnumMatch; });
17064 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValidationResult", function() { return ValidationResult; });
17065 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "newJSONDocument", function() { return newJSONDocument; });
17066 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
17067 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
17068 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
17069 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONDocument", function() { return JSONDocument; });
17070 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
17071 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(83);
17072 /* harmony import */ var _utils_objects__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(88);
17073 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89);
17074 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(76);
17075 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_3__);
17076 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(80);
17077 /*---------------------------------------------------------------------------------------------
17078 * Copyright (c) Microsoft Corporation. All rights reserved.
17079 * Licensed under the MIT License. See License.txt in the project root for license information.
17080 *--------------------------------------------------------------------------------------------*/
17081 var __extends = (undefined && undefined.__extends) || (function () {
17082 var extendStatics = function (d, b) {
17083 extendStatics = Object.setPrototypeOf ||
17084 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17085 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
17086 return extendStatics(d, b);
17088 return function (d, b) {
17089 extendStatics(d, b);
17090 function __() { this.constructor = d; }
17091 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
17099 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_3__["loadMessageBundle"]();
17100 var colorHexPattern = /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/;
17101 var emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
17102 var ASTNodeImpl = /** @class */ (function () {
17103 function ASTNodeImpl(parent, offset, length) {
17104 this.offset = offset;
17105 this.length = length;
17106 this.parent = parent;
17108 Object.defineProperty(ASTNodeImpl.prototype, "children", {
17115 ASTNodeImpl.prototype.toString = function () {
17116 return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : '');
17118 return ASTNodeImpl;
17121 var NullASTNodeImpl = /** @class */ (function (_super) {
17122 __extends(NullASTNodeImpl, _super);
17123 function NullASTNodeImpl(parent, offset) {
17124 var _this = _super.call(this, parent, offset) || this;
17125 _this.type = 'null';
17126 _this.value = null;
17129 return NullASTNodeImpl;
17132 var BooleanASTNodeImpl = /** @class */ (function (_super) {
17133 __extends(BooleanASTNodeImpl, _super);
17134 function BooleanASTNodeImpl(parent, boolValue, offset) {
17135 var _this = _super.call(this, parent, offset) || this;
17136 _this.type = 'boolean';
17137 _this.value = boolValue;
17140 return BooleanASTNodeImpl;
17143 var ArrayASTNodeImpl = /** @class */ (function (_super) {
17144 __extends(ArrayASTNodeImpl, _super);
17145 function ArrayASTNodeImpl(parent, offset) {
17146 var _this = _super.call(this, parent, offset) || this;
17147 _this.type = 'array';
17151 Object.defineProperty(ArrayASTNodeImpl.prototype, "children", {
17158 return ArrayASTNodeImpl;
17161 var NumberASTNodeImpl = /** @class */ (function (_super) {
17162 __extends(NumberASTNodeImpl, _super);
17163 function NumberASTNodeImpl(parent, offset) {
17164 var _this = _super.call(this, parent, offset) || this;
17165 _this.type = 'number';
17166 _this.isInteger = true;
17167 _this.value = Number.NaN;
17170 return NumberASTNodeImpl;
17173 var StringASTNodeImpl = /** @class */ (function (_super) {
17174 __extends(StringASTNodeImpl, _super);
17175 function StringASTNodeImpl(parent, offset, length) {
17176 var _this = _super.call(this, parent, offset, length) || this;
17177 _this.type = 'string';
17181 return StringASTNodeImpl;
17184 var PropertyASTNodeImpl = /** @class */ (function (_super) {
17185 __extends(PropertyASTNodeImpl, _super);
17186 function PropertyASTNodeImpl(parent, offset) {
17187 var _this = _super.call(this, parent, offset) || this;
17188 _this.type = 'property';
17189 _this.colonOffset = -1;
17192 Object.defineProperty(PropertyASTNodeImpl.prototype, "children", {
17194 return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode];
17199 return PropertyASTNodeImpl;
17202 var ObjectASTNodeImpl = /** @class */ (function (_super) {
17203 __extends(ObjectASTNodeImpl, _super);
17204 function ObjectASTNodeImpl(parent, offset) {
17205 var _this = _super.call(this, parent, offset) || this;
17206 _this.type = 'object';
17207 _this.properties = [];
17210 Object.defineProperty(ObjectASTNodeImpl.prototype, "children", {
17212 return this.properties;
17217 return ObjectASTNodeImpl;
17220 function asSchema(schema) {
17221 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(schema)) {
17222 return schema ? {} : { "not": {} };
17227 (function (EnumMatch) {
17228 EnumMatch[EnumMatch["Key"] = 0] = "Key";
17229 EnumMatch[EnumMatch["Enum"] = 1] = "Enum";
17230 })(EnumMatch || (EnumMatch = {}));
17231 var SchemaCollector = /** @class */ (function () {
17232 function SchemaCollector(focusOffset, exclude) {
17233 if (focusOffset === void 0) { focusOffset = -1; }
17234 if (exclude === void 0) { exclude = null; }
17235 this.focusOffset = focusOffset;
17236 this.exclude = exclude;
17239 SchemaCollector.prototype.add = function (schema) {
17240 this.schemas.push(schema);
17242 SchemaCollector.prototype.merge = function (other) {
17244 (_a = this.schemas).push.apply(_a, other.schemas);
17246 SchemaCollector.prototype.include = function (node) {
17247 return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude);
17249 SchemaCollector.prototype.newSub = function () {
17250 return new SchemaCollector(-1, this.exclude);
17252 return SchemaCollector;
17254 var NoOpSchemaCollector = /** @class */ (function () {
17255 function NoOpSchemaCollector() {
17257 Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", {
17258 get: function () { return []; },
17262 NoOpSchemaCollector.prototype.add = function (schema) { };
17263 NoOpSchemaCollector.prototype.merge = function (other) { };
17264 NoOpSchemaCollector.prototype.include = function (node) { return true; };
17265 NoOpSchemaCollector.prototype.newSub = function () { return this; };
17266 NoOpSchemaCollector.instance = new NoOpSchemaCollector();
17267 return NoOpSchemaCollector;
17269 var ValidationResult = /** @class */ (function () {
17270 function ValidationResult() {
17271 this.problems = [];
17272 this.propertiesMatches = 0;
17273 this.propertiesValueMatches = 0;
17274 this.primaryValueMatches = 0;
17275 this.enumValueMatch = false;
17276 this.enumValues = null;
17278 ValidationResult.prototype.hasProblems = function () {
17279 return !!this.problems.length;
17281 ValidationResult.prototype.mergeAll = function (validationResults) {
17282 for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) {
17283 var validationResult = validationResults_1[_i];
17284 this.merge(validationResult);
17287 ValidationResult.prototype.merge = function (validationResult) {
17288 this.problems = this.problems.concat(validationResult.problems);
17290 ValidationResult.prototype.mergeEnumValues = function (validationResult) {
17291 if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) {
17292 this.enumValues = this.enumValues.concat(validationResult.enumValues);
17293 for (var _i = 0, _a = this.problems; _i < _a.length; _i++) {
17294 var error = _a[_i];
17295 if (error.code === _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch) {
17296 error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', '));
17301 ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) {
17302 this.merge(propertyValidationResult);
17303 this.propertiesMatches++;
17304 if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) {
17305 this.propertiesValueMatches++;
17307 if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) {
17308 this.primaryValueMatches++;
17311 ValidationResult.prototype.compare = function (other) {
17312 var hasProblems = this.hasProblems();
17313 if (hasProblems !== other.hasProblems()) {
17314 return hasProblems ? -1 : 1;
17316 if (this.enumValueMatch !== other.enumValueMatch) {
17317 return other.enumValueMatch ? -1 : 1;
17319 if (this.primaryValueMatches !== other.primaryValueMatches) {
17320 return this.primaryValueMatches - other.primaryValueMatches;
17322 if (this.propertiesValueMatches !== other.propertiesValueMatches) {
17323 return this.propertiesValueMatches - other.propertiesValueMatches;
17325 return this.propertiesMatches - other.propertiesMatches;
17327 return ValidationResult;
17330 function newJSONDocument(root, diagnostics) {
17331 if (diagnostics === void 0) { diagnostics = []; }
17332 return new JSONDocument(root, diagnostics, []);
17334 function getNodeValue(node) {
17335 return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](node);
17337 function getNodePath(node) {
17338 return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
17340 function contains(node, offset, includeRightBound) {
17341 if (includeRightBound === void 0) { includeRightBound = false; }
17342 return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length);
17344 var JSONDocument = /** @class */ (function () {
17345 function JSONDocument(root, syntaxErrors, comments) {
17346 if (syntaxErrors === void 0) { syntaxErrors = []; }
17347 if (comments === void 0) { comments = []; }
17349 this.syntaxErrors = syntaxErrors;
17350 this.comments = comments;
17352 JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) {
17353 if (includeRightBound === void 0) { includeRightBound = false; }
17355 return jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["findNodeAtOffset"](this.root, offset, includeRightBound);
17359 JSONDocument.prototype.visit = function (visitor) {
17361 var doVisit_1 = function (node) {
17362 var ctn = visitor(node);
17363 var children = node.children;
17364 if (Array.isArray(children)) {
17365 for (var i = 0; i < children.length && ctn; i++) {
17366 ctn = doVisit_1(children[i]);
17371 doVisit_1(this.root);
17374 JSONDocument.prototype.validate = function (textDocument, schema) {
17375 if (this.root && schema) {
17376 var validationResult = new ValidationResult();
17377 validate(this.root, schema, validationResult, NoOpSchemaCollector.instance);
17378 return validationResult.problems.map(function (p) {
17379 var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Range"].create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length));
17380 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Diagnostic"].create(range, p.message, p.severity, p.code);
17385 JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) {
17386 if (focusOffset === void 0) { focusOffset = -1; }
17387 if (exclude === void 0) { exclude = null; }
17388 var matchingSchemas = new SchemaCollector(focusOffset, exclude);
17389 if (this.root && schema) {
17390 validate(this.root, schema, new ValidationResult(), matchingSchemas);
17392 return matchingSchemas.schemas;
17394 return JSONDocument;
17397 function validate(node, schema, validationResult, matchingSchemas) {
17398 if (!node || !matchingSchemas.include(node)) {
17401 switch (node.type) {
17403 _validateObjectNode(node, schema, validationResult, matchingSchemas);
17406 _validateArrayNode(node, schema, validationResult, matchingSchemas);
17409 _validateStringNode(node, schema, validationResult, matchingSchemas);
17412 _validateNumberNode(node, schema, validationResult, matchingSchemas);
17415 return validate(node.valueNode, schema, validationResult, matchingSchemas);
17418 matchingSchemas.add({ node: node, schema: schema });
17419 function _validateNode() {
17420 function matchesType(type) {
17421 return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger);
17423 if (Array.isArray(schema.type)) {
17424 if (!schema.type.some(matchesType)) {
17425 validationResult.problems.push({
17426 location: { offset: node.offset, length: node.length },
17427 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17428 message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', '))
17432 else if (schema.type) {
17433 if (!matchesType(schema.type)) {
17434 validationResult.problems.push({
17435 location: { offset: node.offset, length: node.length },
17436 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17437 message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type)
17441 if (Array.isArray(schema.allOf)) {
17442 for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) {
17443 var subSchemaRef = _a[_i];
17444 validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas);
17447 var notSchema = asSchema(schema.not);
17449 var subValidationResult = new ValidationResult();
17450 var subMatchingSchemas = matchingSchemas.newSub();
17451 validate(node, notSchema, subValidationResult, subMatchingSchemas);
17452 if (!subValidationResult.hasProblems()) {
17453 validationResult.problems.push({
17454 location: { offset: node.offset, length: node.length },
17455 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17456 message: localize('notSchemaWarning', "Matches a schema that is not allowed.")
17459 for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) {
17461 ms.inverted = !ms.inverted;
17462 matchingSchemas.add(ms);
17465 var testAlternatives = function (alternatives, maxOneMatch) {
17467 // remember the best match that is used for error messages
17468 var bestMatch = null;
17469 for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
17470 var subSchemaRef = alternatives_1[_i];
17471 var subSchema = asSchema(subSchemaRef);
17472 var subValidationResult = new ValidationResult();
17473 var subMatchingSchemas = matchingSchemas.newSub();
17474 validate(node, subSchema, subValidationResult, subMatchingSchemas);
17475 if (!subValidationResult.hasProblems()) {
17476 matches.push(subSchema);
17479 bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
17482 if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
17483 // no errors, both are equally good matches
17484 bestMatch.matchingSchemas.merge(subMatchingSchemas);
17485 bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
17486 bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
17489 var compareResult = subValidationResult.compare(bestMatch.validationResult);
17490 if (compareResult > 0) {
17491 // our node is the best matching so far
17492 bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas };
17494 else if (compareResult === 0) {
17495 // there's already a best matching but we are as good
17496 bestMatch.matchingSchemas.merge(subMatchingSchemas);
17497 bestMatch.validationResult.mergeEnumValues(subValidationResult);
17502 if (matches.length > 1 && maxOneMatch) {
17503 validationResult.problems.push({
17504 location: { offset: node.offset, length: 1 },
17505 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17506 message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.")
17509 if (bestMatch !== null) {
17510 validationResult.merge(bestMatch.validationResult);
17511 validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
17512 validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
17513 matchingSchemas.merge(bestMatch.matchingSchemas);
17515 return matches.length;
17517 if (Array.isArray(schema.anyOf)) {
17518 testAlternatives(schema.anyOf, false);
17520 if (Array.isArray(schema.oneOf)) {
17521 testAlternatives(schema.oneOf, true);
17523 var testBranch = function (schema) {
17524 var subValidationResult = new ValidationResult();
17525 var subMatchingSchemas = matchingSchemas.newSub();
17526 validate(node, asSchema(schema), subValidationResult, subMatchingSchemas);
17527 validationResult.merge(subValidationResult);
17528 validationResult.propertiesMatches += subValidationResult.propertiesMatches;
17529 validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
17530 matchingSchemas.merge(subMatchingSchemas);
17532 var testCondition = function (ifSchema, thenSchema, elseSchema) {
17533 var subSchema = asSchema(ifSchema);
17534 var subValidationResult = new ValidationResult();
17535 var subMatchingSchemas = matchingSchemas.newSub();
17536 validate(node, subSchema, subValidationResult, subMatchingSchemas);
17537 matchingSchemas.merge(subMatchingSchemas);
17538 if (!subValidationResult.hasProblems()) {
17540 testBranch(thenSchema);
17543 else if (elseSchema) {
17544 testBranch(elseSchema);
17547 var ifSchema = asSchema(schema.if);
17549 testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else));
17551 if (Array.isArray(schema.enum)) {
17552 var val = getNodeValue(node);
17553 var enumValueMatch = false;
17554 for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) {
17556 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["equals"])(val, e)) {
17557 enumValueMatch = true;
17561 validationResult.enumValues = schema.enum;
17562 validationResult.enumValueMatch = enumValueMatch;
17563 if (!enumValueMatch) {
17564 validationResult.problems.push({
17565 location: { offset: node.offset, length: node.length },
17566 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17567 code: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch,
17568 message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', '))
17572 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isDefined"])(schema.const)) {
17573 var val = getNodeValue(node);
17574 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["equals"])(val, schema.const)) {
17575 validationResult.problems.push({
17576 location: { offset: node.offset, length: node.length },
17577 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17578 code: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].EnumValueMismatch,
17579 message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const))
17581 validationResult.enumValueMatch = false;
17584 validationResult.enumValueMatch = true;
17586 validationResult.enumValues = [schema.const];
17588 if (schema.deprecationMessage && node.parent) {
17589 validationResult.problems.push({
17590 location: { offset: node.parent.offset, length: node.parent.length },
17591 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17592 message: schema.deprecationMessage
17596 function _validateNumberNode(node, schema, validationResult, matchingSchemas) {
17597 var val = node.value;
17598 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.multipleOf)) {
17599 if (val % schema.multipleOf !== 0) {
17600 validationResult.problems.push({
17601 location: { offset: node.offset, length: node.length },
17602 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17603 message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf)
17607 function getExclusiveLimit(limit, exclusive) {
17608 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusive)) {
17611 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(exclusive) && exclusive) {
17616 function getLimit(limit, exclusive) {
17617 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(exclusive) || !exclusive) {
17622 var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
17623 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusiveMinimum) && val <= exclusiveMinimum) {
17624 validationResult.problems.push({
17625 location: { offset: node.offset, length: node.length },
17626 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17627 message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum)
17630 var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
17631 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(exclusiveMaximum) && val >= exclusiveMaximum) {
17632 validationResult.problems.push({
17633 location: { offset: node.offset, length: node.length },
17634 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17635 message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum)
17638 var minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
17639 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(minimum) && val < minimum) {
17640 validationResult.problems.push({
17641 location: { offset: node.offset, length: node.length },
17642 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17643 message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum)
17646 var maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
17647 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(maximum) && val > maximum) {
17648 validationResult.problems.push({
17649 location: { offset: node.offset, length: node.length },
17650 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17651 message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum)
17655 function _validateStringNode(node, schema, validationResult, matchingSchemas) {
17656 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minLength) && node.value.length < schema.minLength) {
17657 validationResult.problems.push({
17658 location: { offset: node.offset, length: node.length },
17659 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17660 message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength)
17663 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxLength) && node.value.length > schema.maxLength) {
17664 validationResult.problems.push({
17665 location: { offset: node.offset, length: node.length },
17666 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17667 message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength)
17670 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isString"])(schema.pattern)) {
17671 var regex = new RegExp(schema.pattern);
17672 if (!regex.test(node.value)) {
17673 validationResult.problems.push({
17674 location: { offset: node.offset, length: node.length },
17675 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17676 message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern)
17680 if (schema.format) {
17681 switch (schema.format) {
17683 case 'uri-reference':
17685 var errorMessage = void 0;
17687 errorMessage = localize('uriEmpty', 'URI expected.');
17690 var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value);
17692 errorMessage = localize('uriMissing', 'URI is expected.');
17694 else if (!match[2] && schema.format === 'uri') {
17695 errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
17698 if (errorMessage) {
17699 validationResult.problems.push({
17700 location: { offset: node.offset, length: node.length },
17701 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17702 message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage)
17709 if (!node.value.match(emailPattern)) {
17710 validationResult.problems.push({
17711 location: { offset: node.offset, length: node.length },
17712 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17713 message: schema.patternErrorMessage || schema.errorMessage || localize('emailFormatWarning', 'String is not an e-mail address.')
17720 if (!node.value.match(colorHexPattern)) {
17721 validationResult.problems.push({
17722 location: { offset: node.offset, length: node.length },
17723 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17724 message: schema.patternErrorMessage || schema.errorMessage || localize('colorHexFormatWarning', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.')
17733 function _validateArrayNode(node, schema, validationResult, matchingSchemas) {
17734 if (Array.isArray(schema.items)) {
17735 var subSchemas = schema.items;
17736 for (var index = 0; index < subSchemas.length; index++) {
17737 var subSchemaRef = subSchemas[index];
17738 var subSchema = asSchema(subSchemaRef);
17739 var itemValidationResult = new ValidationResult();
17740 var item = node.items[index];
17742 validate(item, subSchema, itemValidationResult, matchingSchemas);
17743 validationResult.mergePropertyMatch(itemValidationResult);
17745 else if (node.items.length >= subSchemas.length) {
17746 validationResult.propertiesValueMatches++;
17749 if (node.items.length > subSchemas.length) {
17750 if (typeof schema.additionalItems === 'object') {
17751 for (var i = subSchemas.length; i < node.items.length; i++) {
17752 var itemValidationResult = new ValidationResult();
17753 validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas);
17754 validationResult.mergePropertyMatch(itemValidationResult);
17757 else if (schema.additionalItems === false) {
17758 validationResult.problems.push({
17759 location: { offset: node.offset, length: node.length },
17760 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17761 message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length)
17767 var itemSchema = asSchema(schema.items);
17769 for (var _i = 0, _a = node.items; _i < _a.length; _i++) {
17771 var itemValidationResult = new ValidationResult();
17772 validate(item, itemSchema, itemValidationResult, matchingSchemas);
17773 validationResult.mergePropertyMatch(itemValidationResult);
17777 var containsSchema = asSchema(schema.contains);
17778 if (containsSchema) {
17779 var doesContain = node.items.some(function (item) {
17780 var itemValidationResult = new ValidationResult();
17781 validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance);
17782 return !itemValidationResult.hasProblems();
17784 if (!doesContain) {
17785 validationResult.problems.push({
17786 location: { offset: node.offset, length: node.length },
17787 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17788 message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.')
17792 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minItems) && node.items.length < schema.minItems) {
17793 validationResult.problems.push({
17794 location: { offset: node.offset, length: node.length },
17795 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17796 message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems)
17799 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxItems) && node.items.length > schema.maxItems) {
17800 validationResult.problems.push({
17801 location: { offset: node.offset, length: node.length },
17802 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17803 message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems)
17806 if (schema.uniqueItems === true) {
17807 var values_1 = getNodeValue(node);
17808 var duplicates = values_1.some(function (value, index) {
17809 return index !== values_1.lastIndexOf(value);
17812 validationResult.problems.push({
17813 location: { offset: node.offset, length: node.length },
17814 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17815 message: localize('uniqueItemsWarning', 'Array has duplicate items.')
17820 function _validateObjectNode(node, schema, validationResult, matchingSchemas) {
17821 var seenKeys = Object.create(null);
17822 var unprocessedProperties = [];
17823 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
17824 var propertyNode = _a[_i];
17825 var key = propertyNode.keyNode.value;
17826 seenKeys[key] = propertyNode.valueNode;
17827 unprocessedProperties.push(key);
17829 if (Array.isArray(schema.required)) {
17830 for (var _b = 0, _c = schema.required; _b < _c.length; _b++) {
17831 var propertyName = _c[_b];
17832 if (!seenKeys[propertyName]) {
17833 var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode;
17834 var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 };
17835 validationResult.problems.push({
17836 location: location,
17837 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17838 message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName)
17843 var propertyProcessed = function (prop) {
17844 var index = unprocessedProperties.indexOf(prop);
17845 while (index >= 0) {
17846 unprocessedProperties.splice(index, 1);
17847 index = unprocessedProperties.indexOf(prop);
17850 if (schema.properties) {
17851 for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) {
17852 var propertyName = _e[_d];
17853 propertyProcessed(propertyName);
17854 var propertySchema = schema.properties[propertyName];
17855 var child = seenKeys[propertyName];
17857 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(propertySchema)) {
17858 if (!propertySchema) {
17859 var propertyNode = child.parent;
17860 validationResult.problems.push({
17861 location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
17862 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17863 message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
17867 validationResult.propertiesMatches++;
17868 validationResult.propertiesValueMatches++;
17872 var propertyValidationResult = new ValidationResult();
17873 validate(child, propertySchema, propertyValidationResult, matchingSchemas);
17874 validationResult.mergePropertyMatch(propertyValidationResult);
17879 if (schema.patternProperties) {
17880 for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) {
17881 var propertyPattern = _g[_f];
17882 var regex = new RegExp(propertyPattern);
17883 for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) {
17884 var propertyName = _j[_h];
17885 if (regex.test(propertyName)) {
17886 propertyProcessed(propertyName);
17887 var child = seenKeys[propertyName];
17889 var propertySchema = schema.patternProperties[propertyPattern];
17890 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isBoolean"])(propertySchema)) {
17891 if (!propertySchema) {
17892 var propertyNode = child.parent;
17893 validationResult.problems.push({
17894 location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
17895 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17896 message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
17900 validationResult.propertiesMatches++;
17901 validationResult.propertiesValueMatches++;
17905 var propertyValidationResult = new ValidationResult();
17906 validate(child, propertySchema, propertyValidationResult, matchingSchemas);
17907 validationResult.mergePropertyMatch(propertyValidationResult);
17914 if (typeof schema.additionalProperties === 'object') {
17915 for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) {
17916 var propertyName = unprocessedProperties_1[_k];
17917 var child = seenKeys[propertyName];
17919 var propertyValidationResult = new ValidationResult();
17920 validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas);
17921 validationResult.mergePropertyMatch(propertyValidationResult);
17925 else if (schema.additionalProperties === false) {
17926 if (unprocessedProperties.length > 0) {
17927 for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) {
17928 var propertyName = unprocessedProperties_2[_l];
17929 var child = seenKeys[propertyName];
17931 var propertyNode = child.parent;
17932 validationResult.problems.push({
17933 location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length },
17934 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17935 message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName)
17941 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.maxProperties)) {
17942 if (node.properties.length > schema.maxProperties) {
17943 validationResult.problems.push({
17944 location: { offset: node.offset, length: node.length },
17945 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17946 message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties)
17950 if (Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(schema.minProperties)) {
17951 if (node.properties.length < schema.minProperties) {
17952 validationResult.problems.push({
17953 location: { offset: node.offset, length: node.length },
17954 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17955 message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties)
17959 if (schema.dependencies) {
17960 for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) {
17962 var prop = seenKeys[key];
17964 var propertyDep = schema.dependencies[key];
17965 if (Array.isArray(propertyDep)) {
17966 for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) {
17967 var requiredProp = propertyDep_1[_p];
17968 if (!seenKeys[requiredProp]) {
17969 validationResult.problems.push({
17970 location: { offset: node.offset, length: node.length },
17971 severity: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning,
17972 message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key)
17976 validationResult.propertiesValueMatches++;
17981 var propertySchema = asSchema(propertyDep);
17982 if (propertySchema) {
17983 var propertyValidationResult = new ValidationResult();
17984 validate(node, propertySchema, propertyValidationResult, matchingSchemas);
17985 validationResult.mergePropertyMatch(propertyValidationResult);
17991 var propertyNames = asSchema(schema.propertyNames);
17992 if (propertyNames) {
17993 for (var _q = 0, _r = node.properties; _q < _r.length; _q++) {
17995 var key = f.keyNode;
17997 validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance);
18003 function parse(textDocument, config) {
18005 var lastProblemOffset = -1;
18006 var text = textDocument.getText();
18007 var scanner = jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["createScanner"](text, false);
18008 var commentRanges = config && config.collectComments ? [] : void 0;
18009 function _scanNext() {
18011 var token_1 = scanner.scan();
18014 case 12 /* LineCommentTrivia */:
18015 case 13 /* BlockCommentTrivia */:
18016 if (Array.isArray(commentRanges)) {
18017 commentRanges.push(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Range"].create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength())));
18020 case 15 /* Trivia */:
18021 case 14 /* LineBreakTrivia */:
18028 function _accept(token) {
18029 if (scanner.getToken() === token) {
18035 function _errorAtRange(message, code, startOffset, endOffset, severity) {
18036 if (severity === void 0) { severity = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Error; }
18037 if (problems.length === 0 || startOffset !== lastProblemOffset) {
18038 var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Range"].create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset));
18039 problems.push(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["Diagnostic"].create(range, message, severity, code, textDocument.languageId));
18040 lastProblemOffset = startOffset;
18043 function _error(message, code, node, skipUntilAfter, skipUntil) {
18044 if (node === void 0) { node = null; }
18045 if (skipUntilAfter === void 0) { skipUntilAfter = []; }
18046 if (skipUntil === void 0) { skipUntil = []; }
18047 var start = scanner.getTokenOffset();
18048 var end = scanner.getTokenOffset() + scanner.getTokenLength();
18049 if (start === end && start > 0) {
18051 while (start > 0 && /\s/.test(text.charAt(start))) {
18056 _errorAtRange(message, code, start, end);
18058 _finalize(node, false);
18060 if (skipUntilAfter.length + skipUntil.length > 0) {
18061 var token_2 = scanner.getToken();
18062 while (token_2 !== 17 /* EOF */) {
18063 if (skipUntilAfter.indexOf(token_2) !== -1) {
18067 else if (skipUntil.indexOf(token_2) !== -1) {
18070 token_2 = _scanNext();
18075 function _checkScanError() {
18076 switch (scanner.getTokenError()) {
18077 case 4 /* InvalidUnicode */:
18078 _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidUnicode);
18080 case 5 /* InvalidEscapeCharacter */:
18081 _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidEscapeCharacter);
18083 case 3 /* UnexpectedEndOfNumber */:
18084 _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfNumber);
18086 case 1 /* UnexpectedEndOfComment */:
18087 _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfComment);
18089 case 2 /* UnexpectedEndOfString */:
18090 _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].UnexpectedEndOfString);
18092 case 6 /* InvalidCharacter */:
18093 _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].InvalidCharacter);
18098 function _finalize(node, scanNext) {
18099 node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset;
18105 function _parseArray(parent) {
18106 if (scanner.getToken() !== 3 /* OpenBracketToken */) {
18109 var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset());
18110 _scanNext(); // consume OpenBracketToken
18112 var needsComma = false;
18113 while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) {
18114 if (scanner.getToken() === 5 /* CommaToken */) {
18116 _error(localize('ValueExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected);
18118 var commaOffset = scanner.getTokenOffset();
18119 _scanNext(); // consume comma
18120 if (scanner.getToken() === 4 /* CloseBracketToken */) {
18122 _errorAtRange(localize('TrailingComma', 'Trailing comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma, commaOffset, commaOffset + 1);
18127 else if (needsComma) {
18128 _error(localize('ExpectedComma', 'Expected comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaExpected);
18130 var item = _parseValue(node, count++);
18132 _error(localize('PropertyExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected, null, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
18135 node.items.push(item);
18139 if (scanner.getToken() !== 4 /* CloseBracketToken */) {
18140 return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaOrCloseBacketExpected, node);
18142 return _finalize(node, true);
18144 function _parseProperty(parent, keysSeen) {
18145 var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset());
18146 var key = _parseString(node);
18148 if (scanner.getToken() === 16 /* Unknown */) {
18149 // give a more helpful error message
18150 _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
18151 var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength());
18152 keyNode.value = scanner.getTokenValue();
18154 _scanNext(); // consume Unknown
18160 node.keyNode = key;
18161 var seen = keysSeen[key.value];
18163 _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning);
18164 if (typeof seen === 'object') {
18165 _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_4__["DiagnosticSeverity"].Warning);
18167 keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting
18170 keysSeen[key.value] = node;
18172 if (scanner.getToken() === 6 /* ColonToken */) {
18173 node.colonOffset = scanner.getTokenOffset();
18174 _scanNext(); // consume ColonToken
18177 _error(localize('ColonExpected', 'Colon expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ColonExpected);
18178 if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) {
18179 node.length = key.length;
18183 var value = _parseValue(node, key.value);
18185 return _error(localize('ValueExpected', 'Value expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
18187 node.valueNode = value;
18188 node.length = value.offset + value.length - node.offset;
18191 function _parseObject(parent) {
18192 if (scanner.getToken() !== 1 /* OpenBraceToken */) {
18195 var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset());
18196 var keysSeen = Object.create(null);
18197 _scanNext(); // consume OpenBraceToken
18198 var needsComma = false;
18199 while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) {
18200 if (scanner.getToken() === 5 /* CommaToken */) {
18202 _error(localize('PropertyExpected', 'Property expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].PropertyExpected);
18204 var commaOffset = scanner.getTokenOffset();
18205 _scanNext(); // consume comma
18206 if (scanner.getToken() === 2 /* CloseBraceToken */) {
18208 _errorAtRange(localize('TrailingComma', 'Trailing comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma, commaOffset, commaOffset + 1);
18213 else if (needsComma) {
18214 _error(localize('ExpectedComma', 'Expected comma'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaExpected);
18216 var property = _parseProperty(node, keysSeen);
18218 _error(localize('PropertyExpected', 'Property expected'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].PropertyExpected, null, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
18221 node.properties.push(property);
18225 if (scanner.getToken() !== 2 /* CloseBraceToken */) {
18226 return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommaOrCloseBraceExpected, node);
18228 return _finalize(node, true);
18230 function _parseString(parent) {
18231 if (scanner.getToken() !== 10 /* StringLiteral */) {
18234 var node = new StringASTNodeImpl(parent, scanner.getTokenOffset());
18235 node.value = scanner.getTokenValue();
18236 return _finalize(node, true);
18238 function _parseNumber(parent) {
18239 if (scanner.getToken() !== 11 /* NumericLiteral */) {
18242 var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset());
18243 if (scanner.getTokenError() === 0 /* None */) {
18244 var tokenValue = scanner.getTokenValue();
18246 var numberValue = JSON.parse(tokenValue);
18247 if (!Object(_utils_objects__WEBPACK_IMPORTED_MODULE_1__["isNumber"])(numberValue)) {
18248 return _error(localize('InvalidNumberFormat', 'Invalid number format.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined, node);
18250 node.value = numberValue;
18253 return _error(localize('InvalidNumberFormat', 'Invalid number format.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined, node);
18255 node.isInteger = tokenValue.indexOf('.') === -1;
18257 return _finalize(node, true);
18259 function _parseLiteral(parent) {
18261 switch (scanner.getToken()) {
18262 case 7 /* NullKeyword */:
18263 return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true);
18264 case 8 /* TrueKeyword */:
18265 return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true);
18266 case 9 /* FalseKeyword */:
18267 return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true);
18272 function _parseValue(parent, name) {
18273 return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent);
18276 var token = _scanNext();
18277 if (token !== 17 /* EOF */) {
18278 _root = _parseValue(null, null);
18280 _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
18282 else if (scanner.getToken() !== 17 /* EOF */) {
18283 _error(localize('End of file expected', 'End of file expected.'), _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].Undefined);
18286 return new JSONDocument(_root, problems, commentRanges);
18292 /***/ (function(module, __webpack_exports__, __webpack_require__) {
18295 __webpack_require__.r(__webpack_exports__);
18296 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
18297 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
18298 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
18299 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
18300 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
18301 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
18302 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
18303 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
18304 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
18305 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
18306 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printParseErrorCode", function() { return printParseErrorCode; });
18307 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
18308 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modify", function() { return modify; });
18309 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdits", function() { return applyEdits; });
18310 /* harmony import */ var _impl_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(84);
18311 /* harmony import */ var _impl_edit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86);
18312 /* harmony import */ var _impl_scanner__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(85);
18313 /* harmony import */ var _impl_parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(87);
18314 /*---------------------------------------------------------------------------------------------
18315 * Copyright (c) Microsoft Corporation. All rights reserved.
18316 * Licensed under the MIT License. See License.txt in the project root for license information.
18317 *--------------------------------------------------------------------------------------------*/
18324 * Creates a JSON scanner on the given text.
18325 * If ignoreTrivia is set, whitespaces or comments are ignored.
18327 var createScanner = _impl_scanner__WEBPACK_IMPORTED_MODULE_2__["createScanner"];
18329 * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
18331 var getLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getLocation"];
18333 * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
18334 * Therefore, always check the errors list to find out if the input was valid.
18336 var parse = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parse"];
18338 * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
18340 var parseTree = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["parseTree"];
18342 * Finds the node at the given path in a JSON DOM.
18344 var findNodeAtLocation = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtLocation"];
18346 * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
18348 var findNodeAtOffset = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["findNodeAtOffset"];
18350 * Gets the JSON path of the given JSON DOM node
18352 var getNodePath = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodePath"];
18354 * Evaluates the JavaScript object of the given JSON DOM node
18356 var getNodeValue = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"];
18358 * Parses the given text and invokes the visitor functions for each object, array and literal reached.
18360 var visit = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["visit"];
18362 * Takes JSON with JavaScript-style comments and remove
18363 * them. Optionally replaces every none-newline character
18364 * of comments with a replaceCharacter
18366 var stripComments = _impl_parser__WEBPACK_IMPORTED_MODULE_3__["stripComments"];
18367 function printParseErrorCode(code) {
18369 case 1 /* InvalidSymbol */: return 'InvalidSymbol';
18370 case 2 /* InvalidNumberFormat */: return 'InvalidNumberFormat';
18371 case 3 /* PropertyNameExpected */: return 'PropertyNameExpected';
18372 case 4 /* ValueExpected */: return 'ValueExpected';
18373 case 5 /* ColonExpected */: return 'ColonExpected';
18374 case 6 /* CommaExpected */: return 'CommaExpected';
18375 case 7 /* CloseBraceExpected */: return 'CloseBraceExpected';
18376 case 8 /* CloseBracketExpected */: return 'CloseBracketExpected';
18377 case 9 /* EndOfFileExpected */: return 'EndOfFileExpected';
18378 case 10 /* InvalidCommentToken */: return 'InvalidCommentToken';
18379 case 11 /* UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';
18380 case 12 /* UnexpectedEndOfString */: return 'UnexpectedEndOfString';
18381 case 13 /* UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';
18382 case 14 /* InvalidUnicode */: return 'InvalidUnicode';
18383 case 15 /* InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';
18384 case 16 /* InvalidCharacter */: return 'InvalidCharacter';
18386 return '<unknown ParseErrorCode>';
18389 * Computes the edits needed to format a JSON document.
18391 * @param documentText The input text
18392 * @param range The range to format or `undefined` to format the full content
18393 * @param options The formatting options
18394 * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
18395 * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
18396 * text in the original document. However, multiple edits can have
18397 * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
18398 * To apply edits to an input, you can use `applyEdits`.
18400 function format(documentText, range, options) {
18401 return _impl_format__WEBPACK_IMPORTED_MODULE_0__["format"](documentText, range, options);
18404 * Computes the edits needed to modify a value in the JSON document.
18406 * @param documentText The input text
18407 * @param path The path of the value to change. The path represents either to the document root, a property or an array item.
18408 * If the path points to an non-existing property or item, it will be created.
18409 * @param value The new value for the specified property or item. If the value is undefined,
18410 * the property or item will be removed.
18411 * @param options Options
18412 * @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
18413 * removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
18414 * text in the original document. However, multiple edits can have
18415 * the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
18416 * To apply edits to an input, you can use `applyEdits`.
18418 function modify(text, path, value, options) {
18419 return _impl_edit__WEBPACK_IMPORTED_MODULE_1__["setProperty"](text, path, value, options.formattingOptions, options.getInsertionIndex);
18422 * Applies edits to a input string.
18424 function applyEdits(text, edits) {
18425 for (var i = edits.length - 1; i >= 0; i--) {
18426 text = _impl_edit__WEBPACK_IMPORTED_MODULE_1__["applyEdit"](text, edits[i]);
18430 //# sourceMappingURL=main.js.map
18434 /***/ (function(module, __webpack_exports__, __webpack_require__) {
18437 __webpack_require__.r(__webpack_exports__);
18438 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; });
18439 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEOL", function() { return isEOL; });
18440 /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85);
18441 /*---------------------------------------------------------------------------------------------
18442 * Copyright (c) Microsoft Corporation. All rights reserved.
18443 * Licensed under the MIT License. See License.txt in the project root for license information.
18444 *--------------------------------------------------------------------------------------------*/
18447 function format(documentText, range, options) {
18448 var initialIndentLevel;
18450 var formatTextStart;
18454 rangeStart = range.offset;
18455 rangeEnd = rangeStart + range.length;
18456 formatTextStart = rangeStart;
18457 while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
18460 var endOffset = rangeEnd;
18461 while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
18464 formatText = documentText.substring(formatTextStart, endOffset);
18465 initialIndentLevel = computeIndentLevel(formatText, options);
18468 formatText = documentText;
18469 initialIndentLevel = 0;
18470 formatTextStart = 0;
18472 rangeEnd = documentText.length;
18474 var eol = getEOL(options, documentText);
18475 var lineBreak = false;
18476 var indentLevel = 0;
18478 if (options.insertSpaces) {
18479 indentValue = repeat(' ', options.tabSize || 4);
18482 indentValue = '\t';
18484 var scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(formatText, false);
18485 var hasError = false;
18486 function newLineAndIndent() {
18487 return eol + repeat(indentValue, initialIndentLevel + indentLevel);
18489 function scanNext() {
18490 var token = scanner.scan();
18492 while (token === 15 /* Trivia */ || token === 14 /* LineBreakTrivia */) {
18493 lineBreak = lineBreak || (token === 14 /* LineBreakTrivia */);
18494 token = scanner.scan();
18496 hasError = token === 16 /* Unknown */ || scanner.getTokenError() !== 0 /* None */;
18499 var editOperations = [];
18500 function addEdit(text, startOffset, endOffset) {
18501 if (!hasError && startOffset < rangeEnd && endOffset > rangeStart && documentText.substring(startOffset, endOffset) !== text) {
18502 editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
18505 var firstToken = scanNext();
18506 if (firstToken !== 17 /* EOF */) {
18507 var firstTokenStart = scanner.getTokenOffset() + formatTextStart;
18508 var initialIndent = repeat(indentValue, initialIndentLevel);
18509 addEdit(initialIndent, formatTextStart, firstTokenStart);
18511 while (firstToken !== 17 /* EOF */) {
18512 var firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
18513 var secondToken = scanNext();
18514 var replaceContent = '';
18515 while (!lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
18516 // comments on the same line: keep them on the same line, but ignore them otherwise
18517 var commentTokenStart = scanner.getTokenOffset() + formatTextStart;
18518 addEdit(' ', firstTokenEnd, commentTokenStart);
18519 firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
18520 replaceContent = secondToken === 12 /* LineCommentTrivia */ ? newLineAndIndent() : '';
18521 secondToken = scanNext();
18523 if (secondToken === 2 /* CloseBraceToken */) {
18524 if (firstToken !== 1 /* OpenBraceToken */) {
18526 replaceContent = newLineAndIndent();
18529 else if (secondToken === 4 /* CloseBracketToken */) {
18530 if (firstToken !== 3 /* OpenBracketToken */) {
18532 replaceContent = newLineAndIndent();
18536 switch (firstToken) {
18537 case 3 /* OpenBracketToken */:
18538 case 1 /* OpenBraceToken */:
18540 replaceContent = newLineAndIndent();
18542 case 5 /* CommaToken */:
18543 case 12 /* LineCommentTrivia */:
18544 replaceContent = newLineAndIndent();
18546 case 13 /* BlockCommentTrivia */:
18548 replaceContent = newLineAndIndent();
18551 // symbol following comment on the same line: keep on same line, separate with ' '
18552 replaceContent = ' ';
18555 case 6 /* ColonToken */:
18556 replaceContent = ' ';
18558 case 10 /* StringLiteral */:
18559 if (secondToken === 6 /* ColonToken */) {
18560 replaceContent = '';
18564 case 7 /* NullKeyword */:
18565 case 8 /* TrueKeyword */:
18566 case 9 /* FalseKeyword */:
18567 case 11 /* NumericLiteral */:
18568 case 2 /* CloseBraceToken */:
18569 case 4 /* CloseBracketToken */:
18570 if (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */) {
18571 replaceContent = ' ';
18573 else if (secondToken !== 5 /* CommaToken */ && secondToken !== 17 /* EOF */) {
18577 case 16 /* Unknown */:
18581 if (lineBreak && (secondToken === 12 /* LineCommentTrivia */ || secondToken === 13 /* BlockCommentTrivia */)) {
18582 replaceContent = newLineAndIndent();
18585 var secondTokenStart = scanner.getTokenOffset() + formatTextStart;
18586 addEdit(replaceContent, firstTokenEnd, secondTokenStart);
18587 firstToken = secondToken;
18589 return editOperations;
18591 function repeat(s, count) {
18593 for (var i = 0; i < count; i++) {
18598 function computeIndentLevel(content, options) {
18601 var tabSize = options.tabSize || 4;
18602 while (i < content.length) {
18603 var ch = content.charAt(i);
18607 else if (ch === '\t') {
18615 return Math.floor(nChars / tabSize);
18617 function getEOL(options, text) {
18618 for (var i = 0; i < text.length; i++) {
18619 var ch = text.charAt(i);
18621 if (i + 1 < text.length && text.charAt(i + 1) === '\n') {
18626 else if (ch === '\n') {
18630 return (options && options.eol) || '\n';
18632 function isEOL(text, offset) {
18633 return '\r\n'.indexOf(text.charAt(offset)) !== -1;
18635 //# sourceMappingURL=format.js.map
18639 /***/ (function(module, __webpack_exports__, __webpack_require__) {
18642 __webpack_require__.r(__webpack_exports__);
18643 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createScanner", function() { return createScanner; });
18644 /*---------------------------------------------------------------------------------------------
18645 * Copyright (c) Microsoft Corporation. All rights reserved.
18646 * Licensed under the MIT License. See License.txt in the project root for license information.
18647 *--------------------------------------------------------------------------------------------*/
18650 * Creates a JSON scanner on the given text.
18651 * If ignoreTrivia is set, whitespaces or comments are ignored.
18653 function createScanner(text, ignoreTrivia) {
18654 if (ignoreTrivia === void 0) { ignoreTrivia = false; }
18655 var pos = 0, len = text.length, value = '', tokenOffset = 0, token = 16 /* Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* None */;
18656 function scanHexDigits(count, exact) {
18659 while (digits < count || !exact) {
18660 var ch = text.charCodeAt(pos);
18661 if (ch >= 48 /* _0 */ && ch <= 57 /* _9 */) {
18662 value = value * 16 + ch - 48 /* _0 */;
18664 else if (ch >= 65 /* A */ && ch <= 70 /* F */) {
18665 value = value * 16 + ch - 65 /* A */ + 10;
18667 else if (ch >= 97 /* a */ && ch <= 102 /* f */) {
18668 value = value * 16 + ch - 97 /* a */ + 10;
18676 if (digits < count) {
18681 function setPosition(newPosition) {
18685 token = 16 /* Unknown */;
18686 scanError = 0 /* None */;
18688 function scanNumber() {
18690 if (text.charCodeAt(pos) === 48 /* _0 */) {
18695 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
18699 if (pos < text.length && text.charCodeAt(pos) === 46 /* dot */) {
18701 if (pos < text.length && isDigit(text.charCodeAt(pos))) {
18703 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
18708 scanError = 3 /* UnexpectedEndOfNumber */;
18709 return text.substring(start, pos);
18713 if (pos < text.length && (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */)) {
18715 if (pos < text.length && text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) {
18718 if (pos < text.length && isDigit(text.charCodeAt(pos))) {
18720 while (pos < text.length && isDigit(text.charCodeAt(pos))) {
18726 scanError = 3 /* UnexpectedEndOfNumber */;
18729 return text.substring(start, end);
18731 function scanString() {
18732 var result = '', start = pos;
18735 result += text.substring(start, pos);
18736 scanError = 2 /* UnexpectedEndOfString */;
18739 var ch = text.charCodeAt(pos);
18740 if (ch === 34 /* doubleQuote */) {
18741 result += text.substring(start, pos);
18745 if (ch === 92 /* backslash */) {
18746 result += text.substring(start, pos);
18749 scanError = 2 /* UnexpectedEndOfString */;
18752 ch = text.charCodeAt(pos++);
18754 case 34 /* doubleQuote */:
18757 case 92 /* backslash */:
18760 case 47 /* slash */:
18779 var ch_1 = scanHexDigits(4, true);
18781 result += String.fromCharCode(ch_1);
18784 scanError = 4 /* InvalidUnicode */;
18788 scanError = 5 /* InvalidEscapeCharacter */;
18793 if (ch >= 0 && ch <= 0x1f) {
18794 if (isLineBreak(ch)) {
18795 result += text.substring(start, pos);
18796 scanError = 2 /* UnexpectedEndOfString */;
18800 scanError = 6 /* InvalidCharacter */;
18801 // mark as error but continue with string
18808 function scanNext() {
18810 scanError = 0 /* None */;
18812 lineStartOffset = lineNumber;
18813 prevTokenLineStartOffset = tokenLineStartOffset;
18817 return token = 17 /* EOF */;
18819 var code = text.charCodeAt(pos);
18820 // trivia: whitespace
18821 if (isWhiteSpace(code)) {
18824 value += String.fromCharCode(code);
18825 code = text.charCodeAt(pos);
18826 } while (isWhiteSpace(code));
18827 return token = 15 /* Trivia */;
18829 // trivia: newlines
18830 if (isLineBreak(code)) {
18832 value += String.fromCharCode(code);
18833 if (code === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
18838 tokenLineStartOffset = pos;
18839 return token = 14 /* LineBreakTrivia */;
18843 case 123 /* openBrace */:
18845 return token = 1 /* OpenBraceToken */;
18846 case 125 /* closeBrace */:
18848 return token = 2 /* CloseBraceToken */;
18849 case 91 /* openBracket */:
18851 return token = 3 /* OpenBracketToken */;
18852 case 93 /* closeBracket */:
18854 return token = 4 /* CloseBracketToken */;
18855 case 58 /* colon */:
18857 return token = 6 /* ColonToken */;
18858 case 44 /* comma */:
18860 return token = 5 /* CommaToken */;
18862 case 34 /* doubleQuote */:
18864 value = scanString();
18865 return token = 10 /* StringLiteral */;
18867 case 47 /* slash */:
18868 var start = pos - 1;
18869 // Single-line comment
18870 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
18872 while (pos < len) {
18873 if (isLineBreak(text.charCodeAt(pos))) {
18878 value = text.substring(start, pos);
18879 return token = 12 /* LineCommentTrivia */;
18881 // Multi-line comment
18882 if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
18884 var safeLength = len - 1; // For lookahead.
18885 var commentClosed = false;
18886 while (pos < safeLength) {
18887 var ch = text.charCodeAt(pos);
18888 if (ch === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
18890 commentClosed = true;
18894 if (isLineBreak(ch)) {
18895 if (ch === 13 /* carriageReturn */ && text.charCodeAt(pos) === 10 /* lineFeed */) {
18899 tokenLineStartOffset = pos;
18902 if (!commentClosed) {
18904 scanError = 1 /* UnexpectedEndOfComment */;
18906 value = text.substring(start, pos);
18907 return token = 13 /* BlockCommentTrivia */;
18909 // just a single slash
18910 value += String.fromCharCode(code);
18912 return token = 16 /* Unknown */;
18914 case 45 /* minus */:
18915 value += String.fromCharCode(code);
18917 if (pos === len || !isDigit(text.charCodeAt(pos))) {
18918 return token = 16 /* Unknown */;
18920 // found a minus, followed by a number so
18921 // we fall through to proceed with scanning
18933 value += scanNumber();
18934 return token = 11 /* NumericLiteral */;
18935 // literals and unknown symbols
18937 // is a literal? Read the full word.
18938 while (pos < len && isUnknownContentCharacter(code)) {
18940 code = text.charCodeAt(pos);
18942 if (tokenOffset !== pos) {
18943 value = text.substring(tokenOffset, pos);
18944 // keywords: true, false, null
18946 case 'true': return token = 8 /* TrueKeyword */;
18947 case 'false': return token = 9 /* FalseKeyword */;
18948 case 'null': return token = 7 /* NullKeyword */;
18950 return token = 16 /* Unknown */;
18953 value += String.fromCharCode(code);
18955 return token = 16 /* Unknown */;
18958 function isUnknownContentCharacter(code) {
18959 if (isWhiteSpace(code) || isLineBreak(code)) {
18963 case 125 /* closeBrace */:
18964 case 93 /* closeBracket */:
18965 case 123 /* openBrace */:
18966 case 91 /* openBracket */:
18967 case 34 /* doubleQuote */:
18968 case 58 /* colon */:
18969 case 44 /* comma */:
18970 case 47 /* slash */:
18975 function scanNextNonTrivia() {
18978 result = scanNext();
18979 } while (result >= 12 /* LineCommentTrivia */ && result <= 15 /* Trivia */);
18983 setPosition: setPosition,
18984 getPosition: function () { return pos; },
18985 scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
18986 getToken: function () { return token; },
18987 getTokenValue: function () { return value; },
18988 getTokenOffset: function () { return tokenOffset; },
18989 getTokenLength: function () { return pos - tokenOffset; },
18990 getTokenStartLine: function () { return lineStartOffset; },
18991 getTokenStartCharacter: function () { return tokenOffset - prevTokenLineStartOffset; },
18992 getTokenError: function () { return scanError; },
18995 function isWhiteSpace(ch) {
18996 return ch === 32 /* space */ || ch === 9 /* tab */ || ch === 11 /* verticalTab */ || ch === 12 /* formFeed */ ||
18997 ch === 160 /* nonBreakingSpace */ || ch === 5760 /* ogham */ || ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
18998 ch === 8239 /* narrowNoBreakSpace */ || ch === 8287 /* mathematicalSpace */ || ch === 12288 /* ideographicSpace */ || ch === 65279 /* byteOrderMark */;
19000 function isLineBreak(ch) {
19001 return ch === 10 /* lineFeed */ || ch === 13 /* carriageReturn */ || ch === 8232 /* lineSeparator */ || ch === 8233 /* paragraphSeparator */;
19003 function isDigit(ch) {
19004 return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
19006 //# sourceMappingURL=scanner.js.map
19010 /***/ (function(module, __webpack_exports__, __webpack_require__) {
19013 __webpack_require__.r(__webpack_exports__);
19014 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeProperty", function() { return removeProperty; });
19015 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setProperty", function() { return setProperty; });
19016 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyEdit", function() { return applyEdit; });
19017 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWS", function() { return isWS; });
19018 /* harmony import */ var _format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(84);
19019 /* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(87);
19020 /*---------------------------------------------------------------------------------------------
19021 * Copyright (c) Microsoft Corporation. All rights reserved.
19022 * Licensed under the MIT License. See License.txt in the project root for license information.
19023 *--------------------------------------------------------------------------------------------*/
19027 function removeProperty(text, path, formattingOptions) {
19028 return setProperty(text, path, void 0, formattingOptions);
19030 function setProperty(text, originalPath, value, formattingOptions, getInsertionIndex) {
19032 var path = originalPath.slice();
19034 var root = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["parseTree"])(text, errors);
19035 var parent = void 0;
19036 var lastSegment = void 0;
19037 while (path.length > 0) {
19038 lastSegment = path.pop();
19039 parent = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(root, path);
19040 if (parent === void 0 && value !== void 0) {
19041 if (typeof lastSegment === 'string') {
19042 value = (_a = {}, _a[lastSegment] = value, _a);
19054 if (value === void 0) { // delete
19055 throw new Error('Can not delete in empty document');
19057 return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
19059 else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {
19060 var existing = Object(_parser__WEBPACK_IMPORTED_MODULE_1__["findNodeAtLocation"])(parent, [lastSegment]);
19061 if (existing !== void 0) {
19062 if (value === void 0) { // delete
19063 if (!existing.parent) {
19064 throw new Error('Malformed AST');
19066 var propertyIndex = parent.children.indexOf(existing.parent);
19067 var removeBegin = void 0;
19068 var removeEnd = existing.parent.offset + existing.parent.length;
19069 if (propertyIndex > 0) {
19070 // remove the comma of the previous node
19071 var previous = parent.children[propertyIndex - 1];
19072 removeBegin = previous.offset + previous.length;
19075 removeBegin = parent.offset + 1;
19076 if (parent.children.length > 1) {
19077 // remove the comma of the next node
19078 var next = parent.children[1];
19079 removeEnd = next.offset;
19082 return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions);
19085 // set value of existing property
19086 return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
19090 if (value === void 0) { // delete
19091 return []; // property does not exist, nothing to do
19093 var newProperty = JSON.stringify(lastSegment) + ": " + JSON.stringify(value);
19094 var index = getInsertionIndex ? getInsertionIndex(parent.children.map(function (p) { return p.children[0].value; })) : parent.children.length;
19097 var previous = parent.children[index - 1];
19098 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
19100 else if (parent.children.length === 0) {
19101 edit = { offset: parent.offset + 1, length: 0, content: newProperty };
19104 edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };
19106 return withFormatting(text, edit, formattingOptions);
19109 else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {
19110 var insertIndex = lastSegment;
19111 if (insertIndex === -1) {
19113 var newProperty = "" + JSON.stringify(value);
19115 if (parent.children.length === 0) {
19116 edit = { offset: parent.offset + 1, length: 0, content: newProperty };
19119 var previous = parent.children[parent.children.length - 1];
19120 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
19122 return withFormatting(text, edit, formattingOptions);
19125 if (value === void 0 && parent.children.length >= 0) {
19127 var removalIndex = lastSegment;
19128 var toRemove = parent.children[removalIndex];
19130 if (parent.children.length === 1) {
19132 edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };
19134 else if (parent.children.length - 1 === removalIndex) {
19136 var previous = parent.children[removalIndex - 1];
19137 var offset = previous.offset + previous.length;
19138 var parentEndOffset = parent.offset + parent.length;
19139 edit = { offset: offset, length: parentEndOffset - 2 - offset, content: '' };
19142 edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };
19144 return withFormatting(text, edit, formattingOptions);
19147 throw new Error('Array modification not supported yet');
19152 throw new Error("Can not add " + (typeof lastSegment !== 'number' ? 'index' : 'property') + " to parent of type " + parent.type);
19155 function withFormatting(text, edit, formattingOptions) {
19157 var newText = applyEdit(text, edit);
19158 // format the new text
19159 var begin = edit.offset;
19160 var end = edit.offset + edit.content.length;
19161 if (edit.length === 0 || edit.content.length === 0) { // insert or remove
19162 while (begin > 0 && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, begin - 1)) {
19165 while (end < newText.length && !Object(_format__WEBPACK_IMPORTED_MODULE_0__["isEOL"])(newText, end)) {
19169 var edits = Object(_format__WEBPACK_IMPORTED_MODULE_0__["format"])(newText, { offset: begin, length: end - begin }, formattingOptions);
19170 // apply the formatting edits and track the begin and end offsets of the changes
19171 for (var i = edits.length - 1; i >= 0; i--) {
19172 var edit_1 = edits[i];
19173 newText = applyEdit(newText, edit_1);
19174 begin = Math.min(begin, edit_1.offset);
19175 end = Math.max(end, edit_1.offset + edit_1.length);
19176 end += edit_1.content.length - edit_1.length;
19178 // create a single edit with all changes
19179 var editLength = text.length - (newText.length - end) - begin;
19180 return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
19182 function applyEdit(text, edit) {
19183 return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
19185 function isWS(text, offset) {
19186 return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;
19188 //# sourceMappingURL=edit.js.map
19192 /***/ (function(module, __webpack_exports__, __webpack_require__) {
19195 __webpack_require__.r(__webpack_exports__);
19196 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocation", function() { return getLocation; });
19197 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; });
19198 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTree", function() { return parseTree; });
19199 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtLocation", function() { return findNodeAtLocation; });
19200 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodePath", function() { return getNodePath; });
19201 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNodeValue", function() { return getNodeValue; });
19202 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return contains; });
19203 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findNodeAtOffset", function() { return findNodeAtOffset; });
19204 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "visit", function() { return visit; });
19205 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripComments", function() { return stripComments; });
19206 /* harmony import */ var _scanner__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85);
19207 /*---------------------------------------------------------------------------------------------
19208 * Copyright (c) Microsoft Corporation. All rights reserved.
19209 * Licensed under the MIT License. See License.txt in the project root for license information.
19210 *--------------------------------------------------------------------------------------------*/
19214 (function (ParseOptions) {
19215 ParseOptions.DEFAULT = {
19216 allowTrailingComma: false
19218 })(ParseOptions || (ParseOptions = {}));
19220 * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
19222 function getLocation(text, position) {
19223 var segments = []; // strings or numbers
19224 var earlyReturnException = new Object();
19225 var previousNode = void 0;
19226 var previousNodeInst = {
19233 var isAtPropertyKey = false;
19234 function setPreviousNode(value, offset, length, type) {
19235 previousNodeInst.value = value;
19236 previousNodeInst.offset = offset;
19237 previousNodeInst.length = length;
19238 previousNodeInst.type = type;
19239 previousNodeInst.colonOffset = void 0;
19240 previousNode = previousNodeInst;
19244 onObjectBegin: function (offset, length) {
19245 if (position <= offset) {
19246 throw earlyReturnException;
19248 previousNode = void 0;
19249 isAtPropertyKey = position > offset;
19250 segments.push(''); // push a placeholder (will be replaced)
19252 onObjectProperty: function (name, offset, length) {
19253 if (position < offset) {
19254 throw earlyReturnException;
19256 setPreviousNode(name, offset, length, 'property');
19257 segments[segments.length - 1] = name;
19258 if (position <= offset + length) {
19259 throw earlyReturnException;
19262 onObjectEnd: function (offset, length) {
19263 if (position <= offset) {
19264 throw earlyReturnException;
19266 previousNode = void 0;
19269 onArrayBegin: function (offset, length) {
19270 if (position <= offset) {
19271 throw earlyReturnException;
19273 previousNode = void 0;
19276 onArrayEnd: function (offset, length) {
19277 if (position <= offset) {
19278 throw earlyReturnException;
19280 previousNode = void 0;
19283 onLiteralValue: function (value, offset, length) {
19284 if (position < offset) {
19285 throw earlyReturnException;
19287 setPreviousNode(value, offset, length, getLiteralNodeType(value));
19288 if (position <= offset + length) {
19289 throw earlyReturnException;
19292 onSeparator: function (sep, offset, length) {
19293 if (position <= offset) {
19294 throw earlyReturnException;
19296 if (sep === ':' && previousNode && previousNode.type === 'property') {
19297 previousNode.colonOffset = offset;
19298 isAtPropertyKey = false;
19299 previousNode = void 0;
19301 else if (sep === ',') {
19302 var last = segments[segments.length - 1];
19303 if (typeof last === 'number') {
19304 segments[segments.length - 1] = last + 1;
19307 isAtPropertyKey = true;
19308 segments[segments.length - 1] = '';
19310 previousNode = void 0;
19316 if (e !== earlyReturnException) {
19322 previousNode: previousNode,
19323 isAtPropertyKey: isAtPropertyKey,
19324 matches: function (pattern) {
19326 for (var i = 0; k < pattern.length && i < segments.length; i++) {
19327 if (pattern[k] === segments[i] || pattern[k] === '*') {
19330 else if (pattern[k] !== '**') {
19334 return k === pattern.length;
19339 * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
19340 * Therefore always check the errors list to find out if the input was valid.
19342 function parse(text, errors, options) {
19343 if (errors === void 0) { errors = []; }
19344 if (options === void 0) { options = ParseOptions.DEFAULT; }
19345 var currentProperty = null;
19346 var currentParent = [];
19347 var previousParents = [];
19348 function onValue(value) {
19349 if (Array.isArray(currentParent)) {
19350 currentParent.push(value);
19352 else if (currentProperty) {
19353 currentParent[currentProperty] = value;
19357 onObjectBegin: function () {
19360 previousParents.push(currentParent);
19361 currentParent = object;
19362 currentProperty = null;
19364 onObjectProperty: function (name) {
19365 currentProperty = name;
19367 onObjectEnd: function () {
19368 currentParent = previousParents.pop();
19370 onArrayBegin: function () {
19373 previousParents.push(currentParent);
19374 currentParent = array;
19375 currentProperty = null;
19377 onArrayEnd: function () {
19378 currentParent = previousParents.pop();
19380 onLiteralValue: onValue,
19381 onError: function (error, offset, length) {
19382 errors.push({ error: error, offset: offset, length: length });
19385 visit(text, visitor, options);
19386 return currentParent[0];
19389 * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
19391 function parseTree(text, errors, options) {
19392 if (errors === void 0) { errors = []; }
19393 if (options === void 0) { options = ParseOptions.DEFAULT; }
19394 var currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: void 0 }; // artificial root
19395 function ensurePropertyComplete(endOffset) {
19396 if (currentParent.type === 'property') {
19397 currentParent.length = endOffset - currentParent.offset;
19398 currentParent = currentParent.parent;
19401 function onValue(valueNode) {
19402 currentParent.children.push(valueNode);
19406 onObjectBegin: function (offset) {
19407 currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });
19409 onObjectProperty: function (name, offset, length) {
19410 currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });
19411 currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });
19413 onObjectEnd: function (offset, length) {
19414 currentParent.length = offset + length - currentParent.offset;
19415 currentParent = currentParent.parent;
19416 ensurePropertyComplete(offset + length);
19418 onArrayBegin: function (offset, length) {
19419 currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });
19421 onArrayEnd: function (offset, length) {
19422 currentParent.length = offset + length - currentParent.offset;
19423 currentParent = currentParent.parent;
19424 ensurePropertyComplete(offset + length);
19426 onLiteralValue: function (value, offset, length) {
19427 onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });
19428 ensurePropertyComplete(offset + length);
19430 onSeparator: function (sep, offset, length) {
19431 if (currentParent.type === 'property') {
19433 currentParent.colonOffset = offset;
19435 else if (sep === ',') {
19436 ensurePropertyComplete(offset);
19440 onError: function (error, offset, length) {
19441 errors.push({ error: error, offset: offset, length: length });
19444 visit(text, visitor, options);
19445 var result = currentParent.children[0];
19447 delete result.parent;
19452 * Finds the node at the given path in a JSON DOM.
19454 function findNodeAtLocation(root, path) {
19459 for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
19460 var segment = path_1[_i];
19461 if (typeof segment === 'string') {
19462 if (node.type !== 'object' || !Array.isArray(node.children)) {
19466 for (var _a = 0, _b = node.children; _a < _b.length; _a++) {
19467 var propertyNode = _b[_a];
19468 if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
19469 node = propertyNode.children[1];
19479 var index = segment;
19480 if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
19483 node = node.children[index];
19489 * Gets the JSON path of the given JSON DOM node
19491 function getNodePath(node) {
19492 if (!node.parent || !node.parent.children) {
19495 var path = getNodePath(node.parent);
19496 if (node.parent.type === 'property') {
19497 var key = node.parent.children[0].value;
19500 else if (node.parent.type === 'array') {
19501 var index = node.parent.children.indexOf(node);
19502 if (index !== -1) {
19509 * Evaluates the JavaScript object of the given JSON DOM node
19511 function getNodeValue(node) {
19512 switch (node.type) {
19514 return node.children.map(getNodeValue);
19516 var obj = Object.create(null);
19517 for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
19519 var valueNode = prop.children[1];
19521 obj[prop.children[0].value] = getNodeValue(valueNode);
19534 function contains(node, offset, includeRightBound) {
19535 if (includeRightBound === void 0) { includeRightBound = false; }
19536 return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
19539 * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
19541 function findNodeAtOffset(node, offset, includeRightBound) {
19542 if (includeRightBound === void 0) { includeRightBound = false; }
19543 if (contains(node, offset, includeRightBound)) {
19544 var children = node.children;
19545 if (Array.isArray(children)) {
19546 for (var i = 0; i < children.length && children[i].offset <= offset; i++) {
19547 var item = findNodeAtOffset(children[i], offset, includeRightBound);
19558 * Parses the given text and invokes the visitor functions for each object, array and literal reached.
19560 function visit(text, visitor, options) {
19561 if (options === void 0) { options = ParseOptions.DEFAULT; }
19562 var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text, false);
19563 function toNoArgVisit(visitFunction) {
19564 return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
19566 function toOneArgVisit(visitFunction) {
19567 return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()); } : function () { return true; };
19569 var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
19570 var disallowComments = options && options.disallowComments;
19571 var allowTrailingComma = options && options.allowTrailingComma;
19572 function scanNext() {
19574 var token = _scanner.scan();
19575 switch (_scanner.getTokenError()) {
19576 case 4 /* InvalidUnicode */:
19577 handleError(14 /* InvalidUnicode */);
19579 case 5 /* InvalidEscapeCharacter */:
19580 handleError(15 /* InvalidEscapeCharacter */);
19582 case 3 /* UnexpectedEndOfNumber */:
19583 handleError(13 /* UnexpectedEndOfNumber */);
19585 case 1 /* UnexpectedEndOfComment */:
19586 if (!disallowComments) {
19587 handleError(11 /* UnexpectedEndOfComment */);
19590 case 2 /* UnexpectedEndOfString */:
19591 handleError(12 /* UnexpectedEndOfString */);
19593 case 6 /* InvalidCharacter */:
19594 handleError(16 /* InvalidCharacter */);
19598 case 12 /* LineCommentTrivia */:
19599 case 13 /* BlockCommentTrivia */:
19600 if (disallowComments) {
19601 handleError(10 /* InvalidCommentToken */);
19607 case 16 /* Unknown */:
19608 handleError(1 /* InvalidSymbol */);
19610 case 15 /* Trivia */:
19611 case 14 /* LineBreakTrivia */:
19618 function handleError(error, skipUntilAfter, skipUntil) {
19619 if (skipUntilAfter === void 0) { skipUntilAfter = []; }
19620 if (skipUntil === void 0) { skipUntil = []; }
19622 if (skipUntilAfter.length + skipUntil.length > 0) {
19623 var token = _scanner.getToken();
19624 while (token !== 17 /* EOF */) {
19625 if (skipUntilAfter.indexOf(token) !== -1) {
19629 else if (skipUntil.indexOf(token) !== -1) {
19632 token = scanNext();
19636 function parseString(isValue) {
19637 var value = _scanner.getTokenValue();
19639 onLiteralValue(value);
19642 onObjectProperty(value);
19647 function parseLiteral() {
19648 switch (_scanner.getToken()) {
19649 case 11 /* NumericLiteral */:
19652 value = JSON.parse(_scanner.getTokenValue());
19653 if (typeof value !== 'number') {
19654 handleError(2 /* InvalidNumberFormat */);
19659 handleError(2 /* InvalidNumberFormat */);
19661 onLiteralValue(value);
19663 case 7 /* NullKeyword */:
19664 onLiteralValue(null);
19666 case 8 /* TrueKeyword */:
19667 onLiteralValue(true);
19669 case 9 /* FalseKeyword */:
19670 onLiteralValue(false);
19678 function parseProperty() {
19679 if (_scanner.getToken() !== 10 /* StringLiteral */) {
19680 handleError(3 /* PropertyNameExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
19683 parseString(false);
19684 if (_scanner.getToken() === 6 /* ColonToken */) {
19686 scanNext(); // consume colon
19687 if (!parseValue()) {
19688 handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
19692 handleError(5 /* ColonExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
19696 function parseObject() {
19698 scanNext(); // consume open brace
19699 var needsComma = false;
19700 while (_scanner.getToken() !== 2 /* CloseBraceToken */ && _scanner.getToken() !== 17 /* EOF */) {
19701 if (_scanner.getToken() === 5 /* CommaToken */) {
19703 handleError(4 /* ValueExpected */, [], []);
19706 scanNext(); // consume comma
19707 if (_scanner.getToken() === 2 /* CloseBraceToken */ && allowTrailingComma) {
19711 else if (needsComma) {
19712 handleError(6 /* CommaExpected */, [], []);
19714 if (!parseProperty()) {
19715 handleError(4 /* ValueExpected */, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]);
19720 if (_scanner.getToken() !== 2 /* CloseBraceToken */) {
19721 handleError(7 /* CloseBraceExpected */, [2 /* CloseBraceToken */], []);
19724 scanNext(); // consume close brace
19728 function parseArray() {
19730 scanNext(); // consume open bracket
19731 var needsComma = false;
19732 while (_scanner.getToken() !== 4 /* CloseBracketToken */ && _scanner.getToken() !== 17 /* EOF */) {
19733 if (_scanner.getToken() === 5 /* CommaToken */) {
19735 handleError(4 /* ValueExpected */, [], []);
19738 scanNext(); // consume comma
19739 if (_scanner.getToken() === 4 /* CloseBracketToken */ && allowTrailingComma) {
19743 else if (needsComma) {
19744 handleError(6 /* CommaExpected */, [], []);
19746 if (!parseValue()) {
19747 handleError(4 /* ValueExpected */, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]);
19752 if (_scanner.getToken() !== 4 /* CloseBracketToken */) {
19753 handleError(8 /* CloseBracketExpected */, [4 /* CloseBracketToken */], []);
19756 scanNext(); // consume close bracket
19760 function parseValue() {
19761 switch (_scanner.getToken()) {
19762 case 3 /* OpenBracketToken */:
19763 return parseArray();
19764 case 1 /* OpenBraceToken */:
19765 return parseObject();
19766 case 10 /* StringLiteral */:
19767 return parseString(true);
19769 return parseLiteral();
19773 if (_scanner.getToken() === 17 /* EOF */) {
19776 if (!parseValue()) {
19777 handleError(4 /* ValueExpected */, [], []);
19780 if (_scanner.getToken() !== 17 /* EOF */) {
19781 handleError(9 /* EndOfFileExpected */, [], []);
19786 * Takes JSON with JavaScript-style comments and remove
19787 * them. Optionally replaces every none-newline character
19788 * of comments with a replaceCharacter
19790 function stripComments(text, replaceCh) {
19791 var _scanner = Object(_scanner__WEBPACK_IMPORTED_MODULE_0__["createScanner"])(text), parts = [], kind, offset = 0, pos;
19793 pos = _scanner.getPosition();
19794 kind = _scanner.scan();
19796 case 12 /* LineCommentTrivia */:
19797 case 13 /* BlockCommentTrivia */:
19799 if (offset !== pos) {
19800 parts.push(text.substring(offset, pos));
19802 if (replaceCh !== void 0) {
19803 parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh));
19805 offset = _scanner.getPosition();
19808 } while (kind !== 17 /* EOF */);
19809 return parts.join('');
19811 function getLiteralNodeType(value) {
19812 switch (typeof value) {
19813 case 'boolean': return 'boolean';
19814 case 'number': return 'number';
19815 case 'string': return 'string';
19816 default: return 'null';
19819 //# sourceMappingURL=parser.js.map
19823 /***/ (function(module, __webpack_exports__, __webpack_require__) {
19826 __webpack_require__.r(__webpack_exports__);
19827 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equals", function() { return equals; });
19828 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return isNumber; });
19829 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDefined", function() { return isDefined; });
19830 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return isBoolean; });
19831 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return isString; });
19832 /*---------------------------------------------------------------------------------------------
19833 * Copyright (c) Microsoft Corporation. All rights reserved.
19834 * Licensed under the MIT License. See License.txt in the project root for license information.
19835 *--------------------------------------------------------------------------------------------*/
19836 function equals(one, other) {
19837 if (one === other) {
19840 if (one === null || one === undefined || other === null || other === undefined) {
19843 if (typeof one !== typeof other) {
19846 if (typeof one !== 'object') {
19849 if ((Array.isArray(one)) !== (Array.isArray(other))) {
19853 if (Array.isArray(one)) {
19854 if (one.length !== other.length) {
19857 for (i = 0; i < one.length; i++) {
19858 if (!equals(one[i], other[i])) {
19869 var otherKeys = [];
19870 for (key in other) {
19871 otherKeys.push(key);
19874 if (!equals(oneKeys, otherKeys)) {
19877 for (i = 0; i < oneKeys.length; i++) {
19878 if (!equals(one[oneKeys[i]], other[oneKeys[i]])) {
19885 function isNumber(val) {
19886 return typeof val === 'number';
19888 function isDefined(val) {
19889 return typeof val !== 'undefined';
19891 function isBoolean(val) {
19892 return typeof val === 'boolean';
19894 function isString(val) {
19895 return typeof val === 'string';
19901 /***/ (function(module, __webpack_exports__, __webpack_require__) {
19904 __webpack_require__.r(__webpack_exports__);
19905 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorCode", function() { return ErrorCode; });
19906 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClientCapabilities", function() { return ClientCapabilities; });
19907 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
19908 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Range", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"]; });
19910 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextEdit", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["TextEdit"]; });
19912 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Color"]; });
19914 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorInformation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["ColorInformation"]; });
19916 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorPresentation", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["ColorPresentation"]; });
19918 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRange", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FoldingRange"]; });
19920 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FoldingRangeKind", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["FoldingRangeKind"]; });
19922 /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SelectionRange", function() { return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"]; });
19927 * Error codes used by diagnostics
19930 (function (ErrorCode) {
19931 ErrorCode[ErrorCode["Undefined"] = 0] = "Undefined";
19932 ErrorCode[ErrorCode["EnumValueMismatch"] = 1] = "EnumValueMismatch";
19933 ErrorCode[ErrorCode["UnexpectedEndOfComment"] = 257] = "UnexpectedEndOfComment";
19934 ErrorCode[ErrorCode["UnexpectedEndOfString"] = 258] = "UnexpectedEndOfString";
19935 ErrorCode[ErrorCode["UnexpectedEndOfNumber"] = 259] = "UnexpectedEndOfNumber";
19936 ErrorCode[ErrorCode["InvalidUnicode"] = 260] = "InvalidUnicode";
19937 ErrorCode[ErrorCode["InvalidEscapeCharacter"] = 261] = "InvalidEscapeCharacter";
19938 ErrorCode[ErrorCode["InvalidCharacter"] = 262] = "InvalidCharacter";
19939 ErrorCode[ErrorCode["PropertyExpected"] = 513] = "PropertyExpected";
19940 ErrorCode[ErrorCode["CommaExpected"] = 514] = "CommaExpected";
19941 ErrorCode[ErrorCode["ColonExpected"] = 515] = "ColonExpected";
19942 ErrorCode[ErrorCode["ValueExpected"] = 516] = "ValueExpected";
19943 ErrorCode[ErrorCode["CommaOrCloseBacketExpected"] = 517] = "CommaOrCloseBacketExpected";
19944 ErrorCode[ErrorCode["CommaOrCloseBraceExpected"] = 518] = "CommaOrCloseBraceExpected";
19945 ErrorCode[ErrorCode["TrailingComma"] = 519] = "TrailingComma";
19946 ErrorCode[ErrorCode["DuplicateKey"] = 520] = "DuplicateKey";
19947 ErrorCode[ErrorCode["CommentNotPermitted"] = 521] = "CommentNotPermitted";
19948 ErrorCode[ErrorCode["SchemaResolveError"] = 768] = "SchemaResolveError";
19949 })(ErrorCode || (ErrorCode = {}));
19950 var ClientCapabilities;
19951 (function (ClientCapabilities) {
19952 ClientCapabilities.LATEST = {
19956 documentationFormat: [vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupKind"].Markdown, vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["MarkupKind"].PlainText]
19961 })(ClientCapabilities || (ClientCapabilities = {}));
19966 /***/ (function(module, __webpack_exports__, __webpack_require__) {
19969 __webpack_require__.r(__webpack_exports__);
19970 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stringifyObject", function() { return stringifyObject; });
19971 /*---------------------------------------------------------------------------------------------
19972 * Copyright (c) Microsoft Corporation. All rights reserved.
19973 * Licensed under the MIT License. See License.txt in the project root for license information.
19974 *--------------------------------------------------------------------------------------------*/
19975 function stringifyObject(obj, indent, stringifyLiteral) {
19976 if (obj !== null && typeof obj === 'object') {
19977 var newIndent = indent + '\t';
19978 if (Array.isArray(obj)) {
19979 if (obj.length === 0) {
19982 var result = '[\n';
19983 for (var i = 0; i < obj.length; i++) {
19984 result += newIndent + stringifyObject(obj[i], newIndent, stringifyLiteral);
19985 if (i < obj.length - 1) {
19990 result += indent + ']';
19994 var keys = Object.keys(obj);
19995 if (keys.length === 0) {
19998 var result = '{\n';
19999 for (var i = 0; i < keys.length; i++) {
20001 result += newIndent + JSON.stringify(key) + ': ' + stringifyObject(obj[key], newIndent, stringifyLiteral);
20002 if (i < keys.length - 1) {
20007 result += indent + '}';
20011 return stringifyLiteral(obj);
20017 /***/ (function(module, __webpack_exports__, __webpack_require__) {
20020 __webpack_require__.r(__webpack_exports__);
20021 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "startsWith", function() { return startsWith; });
20022 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "endsWith", function() { return endsWith; });
20023 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "convertSimple2RegExpPattern", function() { return convertSimple2RegExpPattern; });
20024 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "repeat", function() { return repeat; });
20025 /*---------------------------------------------------------------------------------------------
20026 * Copyright (c) Microsoft Corporation. All rights reserved.
20027 * Licensed under the MIT License. See License.txt in the project root for license information.
20028 *--------------------------------------------------------------------------------------------*/
20029 function startsWith(haystack, needle) {
20030 if (haystack.length < needle.length) {
20033 for (var i = 0; i < needle.length; i++) {
20034 if (haystack[i] !== needle[i]) {
20041 * Determines if haystack ends with needle.
20043 function endsWith(haystack, needle) {
20044 var diff = haystack.length - needle.length;
20046 return haystack.lastIndexOf(needle) === diff;
20048 else if (diff === 0) {
20049 return haystack === needle;
20055 function convertSimple2RegExpPattern(pattern) {
20056 return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
20058 function repeat(value, count) {
20060 while (count > 0) {
20061 if ((count & 1) === 1) {
20065 count = count >>> 1;
20073 /***/ (function(module, __webpack_exports__, __webpack_require__) {
20076 __webpack_require__.r(__webpack_exports__);
20077 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONHover", function() { return JSONHover; });
20078 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82);
20079 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(80);
20080 /*---------------------------------------------------------------------------------------------
20081 * Copyright (c) Microsoft Corporation. All rights reserved.
20082 * Licensed under the MIT License. See License.txt in the project root for license information.
20083 *--------------------------------------------------------------------------------------------*/
20086 var JSONHover = /** @class */ (function () {
20087 function JSONHover(schemaService, contributions, promiseConstructor) {
20088 if (contributions === void 0) { contributions = []; }
20089 this.schemaService = schemaService;
20090 this.contributions = contributions;
20091 this.promise = promiseConstructor || Promise;
20093 JSONHover.prototype.doHover = function (document, position, doc) {
20094 var offset = document.offsetAt(position);
20095 var node = doc.getNodeFromOffset(offset);
20096 if (!node || (node.type === 'object' || node.type === 'array') && offset > node.offset + 1 && offset < node.offset + node.length - 1) {
20097 return this.promise.resolve(null);
20099 var hoverRangeNode = node;
20100 // use the property description when hovering over an object key
20101 if (node.type === 'string') {
20102 var parent = node.parent;
20103 if (parent && parent.type === 'property' && parent.keyNode === node) {
20104 node = parent.valueNode;
20106 return this.promise.resolve(null);
20110 var hoverRange = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Range"].create(document.positionAt(hoverRangeNode.offset), document.positionAt(hoverRangeNode.offset + hoverRangeNode.length));
20111 var createHover = function (contents) {
20113 contents: contents,
20118 var location = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodePath"](node);
20119 for (var i = this.contributions.length - 1; i >= 0; i--) {
20120 var contribution = this.contributions[i];
20121 var promise = contribution.getInfoContribution(document.uri, location);
20123 return promise.then(function (htmlContent) { return createHover(htmlContent); });
20126 return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
20128 var matchingSchemas = doc.getMatchingSchemas(schema.schema, node.offset);
20129 var title_1 = null;
20130 var markdownDescription_1 = null;
20131 var markdownEnumValueDescription_1 = null, enumValue_1 = null;
20132 matchingSchemas.every(function (s) {
20133 if (s.node === node && !s.inverted && s.schema) {
20134 title_1 = title_1 || s.schema.title;
20135 markdownDescription_1 = markdownDescription_1 || s.schema.markdownDescription || toMarkdown(s.schema.description);
20136 if (s.schema.enum) {
20137 var idx = s.schema.enum.indexOf(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](node));
20138 if (s.schema.markdownEnumDescriptions) {
20139 markdownEnumValueDescription_1 = s.schema.markdownEnumDescriptions[idx];
20141 else if (s.schema.enumDescriptions) {
20142 markdownEnumValueDescription_1 = toMarkdown(s.schema.enumDescriptions[idx]);
20144 if (markdownEnumValueDescription_1) {
20145 enumValue_1 = s.schema.enum[idx];
20146 if (typeof enumValue_1 !== 'string') {
20147 enumValue_1 = JSON.stringify(enumValue_1);
20156 result = toMarkdown(title_1);
20158 if (markdownDescription_1) {
20159 if (result.length > 0) {
20162 result += markdownDescription_1;
20164 if (markdownEnumValueDescription_1) {
20165 if (result.length > 0) {
20168 result += "`" + toMarkdownCodeBlock(enumValue_1) + "`: " + markdownEnumValueDescription_1;
20170 return createHover([result]);
20178 function toMarkdown(plain) {
20180 var res = plain.replace(/([^\n\r])(\r?\n)([^\n\r])/gm, '$1\n\n$3'); // single new lines to \n\n (Markdown paragraph)
20181 return res.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&"); // escape markdown syntax tokens: http://daringfireball.net/projects/markdown/syntax#backslash
20185 function toMarkdownCodeBlock(content) {
20186 // see https://daringfireball.net/projects/markdown/syntax#precode
20187 if (content.indexOf('`') !== -1) {
20188 return '`` ' + content + ' ``';
20196 /***/ (function(module, __webpack_exports__, __webpack_require__) {
20199 __webpack_require__.r(__webpack_exports__);
20200 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONValidation", function() { return JSONValidation; });
20201 /* harmony import */ var _jsonSchemaService__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(94);
20202 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(80);
20203 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89);
20204 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(76);
20205 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_3__);
20206 /*---------------------------------------------------------------------------------------------
20207 * Copyright (c) Microsoft Corporation. All rights reserved.
20208 * Licensed under the MIT License. See License.txt in the project root for license information.
20209 *--------------------------------------------------------------------------------------------*/
20214 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_3__["loadMessageBundle"]();
20215 var JSONValidation = /** @class */ (function () {
20216 function JSONValidation(jsonSchemaService, promiseConstructor) {
20217 this.jsonSchemaService = jsonSchemaService;
20218 this.promise = promiseConstructor;
20219 this.validationEnabled = true;
20221 JSONValidation.prototype.configure = function (raw) {
20223 this.validationEnabled = raw.validate;
20224 this.commentSeverity = raw.allowComments ? void 0 : vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
20227 JSONValidation.prototype.doValidation = function (textDocument, jsonDocument, documentSettings, schema) {
20229 if (!this.validationEnabled) {
20230 return this.promise.resolve([]);
20232 var diagnostics = [];
20234 var addProblem = function (problem) {
20235 // remove duplicated messages
20236 var signature = problem.range.start.line + ' ' + problem.range.start.character + ' ' + problem.message;
20237 if (!added[signature]) {
20238 added[signature] = true;
20239 diagnostics.push(problem);
20242 var getDiagnostics = function (schema) {
20243 var trailingCommaSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.trailingCommas) : vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
20244 var commentSeverity = documentSettings ? toDiagnosticSeverity(documentSettings.comments) : _this.commentSeverity;
20246 if (schema.errors.length && jsonDocument.root) {
20247 var astRoot = jsonDocument.root;
20248 var property = astRoot.type === 'object' ? astRoot.properties[0] : null;
20249 if (property && property.keyNode.value === '$schema') {
20250 var node = property.valueNode || property;
20251 var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Range"].create(textDocument.positionAt(node.offset), textDocument.positionAt(node.offset + node.length));
20252 addProblem(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(range, schema.errors[0], vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].SchemaResolveError));
20255 var range = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Range"].create(textDocument.positionAt(astRoot.offset), textDocument.positionAt(astRoot.offset + 1));
20256 addProblem(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(range, schema.errors[0], vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].SchemaResolveError));
20260 var semanticErrors = jsonDocument.validate(textDocument, schema.schema);
20261 if (semanticErrors) {
20262 semanticErrors.forEach(addProblem);
20265 if (schemaAllowsComments(schema.schema)) {
20266 trailingCommaSeverity = commentSeverity = void 0;
20269 for (var _i = 0, _a = jsonDocument.syntaxErrors; _i < _a.length; _i++) {
20271 if (p.code === _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].TrailingComma) {
20272 if (typeof trailingCommaSeverity !== 'number') {
20275 p.severity = trailingCommaSeverity;
20279 if (typeof commentSeverity === 'number') {
20280 var message_1 = localize('InvalidCommentToken', 'Comments are not permitted in JSON.');
20281 jsonDocument.comments.forEach(function (c) {
20282 addProblem(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["Diagnostic"].create(c, message_1, commentSeverity, _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["ErrorCode"].CommentNotPermitted));
20285 return diagnostics;
20288 var id = schema.id || ('schemaservice://untitled/' + idCounter++);
20289 return this.jsonSchemaService.resolveSchemaContent(new _jsonSchemaService__WEBPACK_IMPORTED_MODULE_0__["UnresolvedSchema"](schema), id, {}).then(function (resolvedSchema) {
20290 return getDiagnostics(resolvedSchema);
20293 return this.jsonSchemaService.getSchemaForResource(textDocument.uri, jsonDocument).then(function (schema) {
20294 return getDiagnostics(schema);
20297 return JSONValidation;
20301 function schemaAllowsComments(schemaRef) {
20302 if (schemaRef && typeof schemaRef === 'object') {
20303 if (schemaRef.allowComments) {
20306 if (schemaRef.allOf) {
20307 return schemaRef.allOf.some(schemaAllowsComments);
20312 function toDiagnosticSeverity(severityLevel) {
20313 switch (severityLevel) {
20314 case 'error': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Error;
20315 case 'warning': return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_1__["DiagnosticSeverity"].Warning;
20316 case 'ignore': return void 0;
20324 /***/ (function(module, __webpack_exports__, __webpack_require__) {
20327 __webpack_require__.r(__webpack_exports__);
20328 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnresolvedSchema", function() { return UnresolvedSchema; });
20329 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ResolvedSchema", function() { return ResolvedSchema; });
20330 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONSchemaService", function() { return JSONSchemaService; });
20331 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(83);
20332 /* harmony import */ var vscode_uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(95);
20333 /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(91);
20334 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(82);
20335 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(76);
20336 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_4__);
20337 /*---------------------------------------------------------------------------------------------
20338 * Copyright (c) Microsoft Corporation. All rights reserved.
20339 * Licensed under the MIT License. See License.txt in the project root for license information.
20340 *--------------------------------------------------------------------------------------------*/
20346 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_4__["loadMessageBundle"]();
20347 var FilePatternAssociation = /** @class */ (function () {
20348 function FilePatternAssociation(pattern) {
20350 this.patternRegExp = new RegExp(_utils_strings__WEBPACK_IMPORTED_MODULE_2__["convertSimple2RegExpPattern"](pattern) + '$');
20354 this.patternRegExp = null;
20358 FilePatternAssociation.prototype.addSchema = function (id) {
20359 this.schemas.push(id);
20361 FilePatternAssociation.prototype.matchesPattern = function (fileName) {
20362 return this.patternRegExp && this.patternRegExp.test(fileName);
20364 FilePatternAssociation.prototype.getSchemas = function () {
20365 return this.schemas;
20367 return FilePatternAssociation;
20369 var SchemaHandle = /** @class */ (function () {
20370 function SchemaHandle(service, url, unresolvedSchemaContent) {
20371 this.service = service;
20373 this.dependencies = {};
20374 if (unresolvedSchemaContent) {
20375 this.unresolvedSchema = this.service.promise.resolve(new UnresolvedSchema(unresolvedSchemaContent));
20378 SchemaHandle.prototype.getUnresolvedSchema = function () {
20379 if (!this.unresolvedSchema) {
20380 this.unresolvedSchema = this.service.loadSchema(this.url);
20382 return this.unresolvedSchema;
20384 SchemaHandle.prototype.getResolvedSchema = function () {
20386 if (!this.resolvedSchema) {
20387 this.resolvedSchema = this.getUnresolvedSchema().then(function (unresolved) {
20388 return _this.service.resolveSchemaContent(unresolved, _this.url, _this.dependencies);
20391 return this.resolvedSchema;
20393 SchemaHandle.prototype.clearSchema = function () {
20394 this.resolvedSchema = null;
20395 this.unresolvedSchema = null;
20396 this.dependencies = {};
20398 return SchemaHandle;
20400 var UnresolvedSchema = /** @class */ (function () {
20401 function UnresolvedSchema(schema, errors) {
20402 if (errors === void 0) { errors = []; }
20403 this.schema = schema;
20404 this.errors = errors;
20406 return UnresolvedSchema;
20409 var ResolvedSchema = /** @class */ (function () {
20410 function ResolvedSchema(schema, errors) {
20411 if (errors === void 0) { errors = []; }
20412 this.schema = schema;
20413 this.errors = errors;
20415 ResolvedSchema.prototype.getSection = function (path) {
20416 return _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__["asSchema"](this.getSectionRecursive(path, this.schema));
20418 ResolvedSchema.prototype.getSectionRecursive = function (path, schema) {
20419 if (!schema || typeof schema === 'boolean' || path.length === 0) {
20422 var next = path.shift();
20423 if (schema.properties && typeof schema.properties[next]) {
20424 return this.getSectionRecursive(path, schema.properties[next]);
20426 else if (schema.patternProperties) {
20427 for (var _i = 0, _a = Object.keys(schema.patternProperties); _i < _a.length; _i++) {
20428 var pattern = _a[_i];
20429 var regex = new RegExp(pattern);
20430 if (regex.test(next)) {
20431 return this.getSectionRecursive(path, schema.patternProperties[pattern]);
20435 else if (typeof schema.additionalProperties === 'object') {
20436 return this.getSectionRecursive(path, schema.additionalProperties);
20438 else if (next.match('[0-9]+')) {
20439 if (Array.isArray(schema.items)) {
20440 var index = parseInt(next, 10);
20441 if (!isNaN(index) && schema.items[index]) {
20442 return this.getSectionRecursive(path, schema.items[index]);
20445 else if (schema.items) {
20446 return this.getSectionRecursive(path, schema.items);
20451 return ResolvedSchema;
20454 var JSONSchemaService = /** @class */ (function () {
20455 function JSONSchemaService(requestService, contextService, promiseConstructor) {
20456 this.contextService = contextService;
20457 this.requestService = requestService;
20458 this.promiseConstructor = promiseConstructor || Promise;
20459 this.callOnDispose = [];
20460 this.contributionSchemas = {};
20461 this.contributionAssociations = {};
20462 this.schemasById = {};
20463 this.filePatternAssociations = [];
20464 this.filePatternAssociationById = {};
20465 this.registeredSchemasIds = {};
20467 JSONSchemaService.prototype.getRegisteredSchemaIds = function (filter) {
20468 return Object.keys(this.registeredSchemasIds).filter(function (id) {
20469 var scheme = vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(id).scheme;
20470 return scheme !== 'schemaservice' && (!filter || filter(scheme));
20473 Object.defineProperty(JSONSchemaService.prototype, "promise", {
20475 return this.promiseConstructor;
20480 JSONSchemaService.prototype.dispose = function () {
20481 while (this.callOnDispose.length > 0) {
20482 this.callOnDispose.pop()();
20485 JSONSchemaService.prototype.onResourceChange = function (uri) {
20487 var hasChanges = false;
20488 uri = this.normalizeId(uri);
20489 var toWalk = [uri];
20490 var all = Object.keys(this.schemasById).map(function (key) { return _this.schemasById[key]; });
20491 while (toWalk.length) {
20492 var curr = toWalk.pop();
20493 for (var i = 0; i < all.length; i++) {
20494 var handle = all[i];
20495 if (handle && (handle.url === curr || handle.dependencies[curr])) {
20496 if (handle.url !== curr) {
20497 toWalk.push(handle.url);
20499 handle.clearSchema();
20500 all[i] = undefined;
20507 JSONSchemaService.prototype.normalizeId = function (id) {
20508 // remove trailing '#', normalize drive capitalization
20510 return vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(id).toString();
20516 JSONSchemaService.prototype.setSchemaContributions = function (schemaContributions) {
20517 if (schemaContributions.schemas) {
20518 var schemas = schemaContributions.schemas;
20519 for (var id in schemas) {
20520 var normalizedId = this.normalizeId(id);
20521 this.contributionSchemas[normalizedId] = this.addSchemaHandle(normalizedId, schemas[id]);
20524 if (schemaContributions.schemaAssociations) {
20525 var schemaAssociations = schemaContributions.schemaAssociations;
20526 for (var pattern in schemaAssociations) {
20527 var associations = schemaAssociations[pattern];
20528 this.contributionAssociations[pattern] = associations;
20529 var fpa = this.getOrAddFilePatternAssociation(pattern);
20530 for (var _i = 0, associations_1 = associations; _i < associations_1.length; _i++) {
20531 var schemaId = associations_1[_i];
20532 var id = this.normalizeId(schemaId);
20538 JSONSchemaService.prototype.addSchemaHandle = function (id, unresolvedSchemaContent) {
20539 var schemaHandle = new SchemaHandle(this, id, unresolvedSchemaContent);
20540 this.schemasById[id] = schemaHandle;
20541 return schemaHandle;
20543 JSONSchemaService.prototype.getOrAddSchemaHandle = function (id, unresolvedSchemaContent) {
20544 return this.schemasById[id] || this.addSchemaHandle(id, unresolvedSchemaContent);
20546 JSONSchemaService.prototype.getOrAddFilePatternAssociation = function (pattern) {
20547 var fpa = this.filePatternAssociationById[pattern];
20549 fpa = new FilePatternAssociation(pattern);
20550 this.filePatternAssociationById[pattern] = fpa;
20551 this.filePatternAssociations.push(fpa);
20555 JSONSchemaService.prototype.registerExternalSchema = function (uri, filePatterns, unresolvedSchemaContent) {
20556 if (filePatterns === void 0) { filePatterns = null; }
20557 var id = this.normalizeId(uri);
20558 this.registeredSchemasIds[id] = true;
20559 if (filePatterns) {
20560 for (var _i = 0, filePatterns_1 = filePatterns; _i < filePatterns_1.length; _i++) {
20561 var pattern = filePatterns_1[_i];
20562 this.getOrAddFilePatternAssociation(pattern).addSchema(id);
20565 return unresolvedSchemaContent ? this.addSchemaHandle(id, unresolvedSchemaContent) : this.getOrAddSchemaHandle(id);
20567 JSONSchemaService.prototype.clearExternalSchemas = function () {
20568 this.schemasById = {};
20569 this.filePatternAssociations = [];
20570 this.filePatternAssociationById = {};
20571 this.registeredSchemasIds = {};
20572 for (var id in this.contributionSchemas) {
20573 this.schemasById[id] = this.contributionSchemas[id];
20574 this.registeredSchemasIds[id] = true;
20576 for (var pattern in this.contributionAssociations) {
20577 var fpa = this.getOrAddFilePatternAssociation(pattern);
20578 for (var _i = 0, _a = this.contributionAssociations[pattern]; _i < _a.length; _i++) {
20579 var schemaId = _a[_i];
20580 var id = this.normalizeId(schemaId);
20585 JSONSchemaService.prototype.getResolvedSchema = function (schemaId) {
20586 var id = this.normalizeId(schemaId);
20587 var schemaHandle = this.schemasById[id];
20588 if (schemaHandle) {
20589 return schemaHandle.getResolvedSchema();
20591 return this.promise.resolve(null);
20593 JSONSchemaService.prototype.loadSchema = function (url) {
20594 if (!this.requestService) {
20595 var errorMessage = localize('json.schema.norequestservice', 'Unable to load schema from \'{0}\'. No schema request service available', toDisplayString(url));
20596 return this.promise.resolve(new UnresolvedSchema({}, [errorMessage]));
20598 return this.requestService(url).then(function (content) {
20600 var errorMessage = localize('json.schema.nocontent', 'Unable to load schema from \'{0}\': No content.', toDisplayString(url));
20601 return new UnresolvedSchema({}, [errorMessage]);
20603 var schemaContent = {};
20604 var jsonErrors = [];
20605 schemaContent = jsonc_parser__WEBPACK_IMPORTED_MODULE_0__["parse"](content, jsonErrors);
20606 var errors = jsonErrors.length ? [localize('json.schema.invalidFormat', 'Unable to parse content from \'{0}\': Parse error at offset {1}.', toDisplayString(url), jsonErrors[0].offset)] : [];
20607 return new UnresolvedSchema(schemaContent, errors);
20608 }, function (error) {
20609 var errorMessage = error.toString();
20610 var errorSplit = error.toString().split('Error: ');
20611 if (errorSplit.length > 1) {
20612 // more concise error message, URL and context are attached by caller anyways
20613 errorMessage = errorSplit[1];
20615 return new UnresolvedSchema({}, [errorMessage]);
20618 JSONSchemaService.prototype.resolveSchemaContent = function (schemaToResolve, schemaURL, dependencies) {
20620 var resolveErrors = schemaToResolve.errors.slice(0);
20621 var schema = schemaToResolve.schema;
20622 var contextService = this.contextService;
20623 var findSection = function (schema, path) {
20627 var current = schema;
20628 if (path[0] === '/') {
20629 path = path.substr(1);
20631 path.split('/').some(function (part) {
20632 current = current[part];
20637 var merge = function (target, sourceRoot, sourceURI, path) {
20638 var section = findSection(sourceRoot, path);
20640 for (var key in section) {
20641 if (section.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
20642 target[key] = section[key];
20647 resolveErrors.push(localize('json.schema.invalidref', '$ref \'{0}\' in \'{1}\' can not be resolved.', path, sourceURI));
20650 var resolveExternalLink = function (node, uri, linkPath, parentSchemaURL, parentSchemaDependencies) {
20651 if (contextService && !/^\w+:\/\/.*/.test(uri)) {
20652 uri = contextService.resolveRelativePath(uri, parentSchemaURL);
20654 uri = _this.normalizeId(uri);
20655 var referencedHandle = _this.getOrAddSchemaHandle(uri);
20656 return referencedHandle.getUnresolvedSchema().then(function (unresolvedSchema) {
20657 parentSchemaDependencies[uri] = true;
20658 if (unresolvedSchema.errors.length) {
20659 var loc = linkPath ? uri + '#' + linkPath : uri;
20660 resolveErrors.push(localize('json.schema.problemloadingref', 'Problems loading reference \'{0}\': {1}', loc, unresolvedSchema.errors[0]));
20662 merge(node, unresolvedSchema.schema, uri, linkPath);
20663 return resolveRefs(node, unresolvedSchema.schema, uri, referencedHandle.dependencies);
20666 var resolveRefs = function (node, parentSchema, parentSchemaURL, parentSchemaDependencies) {
20667 if (!node || typeof node !== 'object') {
20668 return Promise.resolve(null);
20670 var toWalk = [node];
20672 var openPromises = [];
20673 var collectEntries = function () {
20675 for (var _i = 0; _i < arguments.length; _i++) {
20676 entries[_i] = arguments[_i];
20678 for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
20679 var entry = entries_1[_a];
20680 if (typeof entry === 'object') {
20681 toWalk.push(entry);
20685 var collectMapEntries = function () {
20687 for (var _i = 0; _i < arguments.length; _i++) {
20688 maps[_i] = arguments[_i];
20690 for (var _a = 0, maps_1 = maps; _a < maps_1.length; _a++) {
20691 var map = maps_1[_a];
20692 if (typeof map === 'object') {
20693 for (var key in map) {
20694 var entry = map[key];
20695 if (typeof entry === 'object') {
20696 toWalk.push(entry);
20702 var collectArrayEntries = function () {
20704 for (var _i = 0; _i < arguments.length; _i++) {
20705 arrays[_i] = arguments[_i];
20707 for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
20708 var array = arrays_1[_a];
20709 if (Array.isArray(array)) {
20710 for (var _b = 0, array_1 = array; _b < array_1.length; _b++) {
20711 var entry = array_1[_b];
20712 if (typeof entry === 'object') {
20713 toWalk.push(entry);
20719 var handleRef = function (next) {
20721 while (next.$ref) {
20722 var ref = next.$ref;
20723 var segments = ref.split('#', 2);
20725 if (segments[0].length > 0) {
20726 openPromises.push(resolveExternalLink(next, segments[0], segments[1], parentSchemaURL, parentSchemaDependencies));
20730 if (seenRefs.indexOf(ref) === -1) {
20731 merge(next, parentSchema, parentSchemaURL, segments[1]); // can set next.$ref again, use seenRefs to avoid circle
20732 seenRefs.push(ref);
20736 collectEntries(next.items, next.additionalProperties, next.not, next.contains, next.propertyNames, next.if, next.then, next.else);
20737 collectMapEntries(next.definitions, next.properties, next.patternProperties, next.dependencies);
20738 collectArrayEntries(next.anyOf, next.allOf, next.oneOf, next.items);
20740 while (toWalk.length) {
20741 var next = toWalk.pop();
20742 if (seen.indexOf(next) >= 0) {
20748 return _this.promise.all(openPromises);
20750 return resolveRefs(schema, schema, schemaURL, dependencies).then(function (_) { return new ResolvedSchema(schema, resolveErrors); });
20752 JSONSchemaService.prototype.getSchemaForResource = function (resource, document) {
20753 // first use $schema if present
20754 if (document && document.root && document.root.type === 'object') {
20755 var schemaProperties = document.root.properties.filter(function (p) { return (p.keyNode.value === '$schema') && p.valueNode && p.valueNode.type === 'string'; });
20756 if (schemaProperties.length > 0) {
20757 var schemeId = _parser_jsonParser__WEBPACK_IMPORTED_MODULE_3__["getNodeValue"](schemaProperties[0].valueNode);
20758 if (schemeId && _utils_strings__WEBPACK_IMPORTED_MODULE_2__["startsWith"](schemeId, '.') && this.contextService) {
20759 schemeId = this.contextService.resolveRelativePath(schemeId, resource);
20762 var id = this.normalizeId(schemeId);
20763 return this.getOrAddSchemaHandle(id).getResolvedSchema();
20767 var seen = Object.create(null);
20769 for (var _i = 0, _a = this.filePatternAssociations; _i < _a.length; _i++) {
20770 var entry = _a[_i];
20771 if (entry.matchesPattern(resource)) {
20772 for (var _b = 0, _c = entry.getSchemas(); _b < _c.length; _b++) {
20773 var schemaId = _c[_b];
20774 if (!seen[schemaId]) {
20775 schemas.push(schemaId);
20776 seen[schemaId] = true;
20781 if (schemas.length > 0) {
20782 return this.createCombinedSchema(resource, schemas).getResolvedSchema();
20784 return this.promise.resolve(null);
20786 JSONSchemaService.prototype.createCombinedSchema = function (resource, schemaIds) {
20787 if (schemaIds.length === 1) {
20788 return this.getOrAddSchemaHandle(schemaIds[0]);
20791 var combinedSchemaId = 'schemaservice://combinedSchema/' + encodeURIComponent(resource);
20792 var combinedSchema = {
20793 allOf: schemaIds.map(function (schemaId) { return ({ $ref: schemaId }); })
20795 return this.addSchemaHandle(combinedSchemaId, combinedSchema);
20798 return JSONSchemaService;
20801 function toDisplayString(url) {
20803 var uri = vscode_uri__WEBPACK_IMPORTED_MODULE_1__["URI"].parse(url);
20804 if (uri.scheme === 'file') {
20817 /***/ (function(module, __webpack_exports__, __webpack_require__) {
20820 __webpack_require__.r(__webpack_exports__);
20821 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setUriThrowOnMissingScheme", function() { return setUriThrowOnMissingScheme; });
20822 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URI", function() { return URI; });
20823 /*---------------------------------------------------------------------------------------------
20824 * Copyright (c) Microsoft Corporation. All rights reserved.
20825 * Licensed under the MIT License. See License.txt in the project root for license information.
20826 *--------------------------------------------------------------------------------------------*/
20828 var __extends = (undefined && undefined.__extends) || (function () {
20829 var extendStatics = Object.setPrototypeOf ||
20830 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20831 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20832 return function (d, b) {
20833 extendStatics(d, b);
20834 function __() { this.constructor = d; }
20835 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20839 if (typeof process === 'object') {
20840 isWindows = process.platform === 'win32';
20842 else if (typeof navigator === 'object') {
20843 var userAgent = navigator.userAgent;
20844 isWindows = userAgent.indexOf('Windows') >= 0;
20847 var _schemePattern = /^\w[\w\d+.-]*$/;
20848 var _singleSlashStart = /^\//;
20849 var _doubleSlashStart = /^\/\//;
20850 var _throwOnMissingSchema = true;
20854 function setUriThrowOnMissingScheme(value) {
20855 var old = _throwOnMissingSchema;
20856 _throwOnMissingSchema = value;
20859 function _validateUri(ret, _strict) {
20860 // scheme, must be set
20862 if (_strict || _throwOnMissingSchema) {
20863 throw new Error("[UriError]: Scheme is missing: {scheme: \"\", authority: \"" + ret.authority + "\", path: \"" + ret.path + "\", query: \"" + ret.query + "\", fragment: \"" + ret.fragment + "\"}");
20866 // console.warn(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
20869 // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
20870 // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
20871 if (ret.scheme && !_schemePattern.test(ret.scheme)) {
20872 throw new Error('[UriError]: Scheme contains illegal characters.');
20874 // path, http://tools.ietf.org/html/rfc3986#section-3.3
20875 // If a URI contains an authority component, then the path component
20876 // must either be empty or begin with a slash ("/") character. If a URI
20877 // does not contain an authority component, then the path cannot begin
20878 // with two slash characters ("//").
20880 if (ret.authority) {
20881 if (!_singleSlashStart.test(ret.path)) {
20882 throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
20886 if (_doubleSlashStart.test(ret.path)) {
20887 throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
20892 // for a while we allowed uris *without* schemes and this is the migration
20893 // for them, e.g. an uri without scheme and without strict-mode warns and falls
20894 // back to the file-scheme. that should cause the least carnage and still be a
20896 function _schemeFix(scheme, _strict) {
20897 if (_strict || _throwOnMissingSchema) {
20898 return scheme || _empty;
20901 // console.trace('BAD uri lacks scheme, falling back to file-scheme.');
20906 // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
20907 function _referenceResolution(scheme, path) {
20908 // the slash-character is our 'default base' as we don't
20909 // support constructing URIs relative to other URIs. This
20910 // also means that we alter and potentially break paths.
20911 // see https://tools.ietf.org/html/rfc3986#section-5.1.4
20919 else if (path[0] !== _slash) {
20920 path = _slash + path;
20928 var _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
20929 function _isQueryStringScheme(scheme) {
20933 switch (scheme.toLowerCase()) {
20942 * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
20943 * This class is a simple parser which creates the basic component parts
20944 * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
20947 * foo://example.com:8042/over/there?name=ferret#nose
20948 * \_/ \______________/\_________/ \_________/ \__/
20950 * scheme authority path query fragment
20951 * | _____________________|__
20953 * urn:example:animal:ferret:nose
20955 var URI = (function () {
20959 function URI(schemeOrData, authority, path, query, fragment, _strict) {
20960 if (_strict === void 0) { _strict = false; }
20961 if (typeof schemeOrData === 'object') {
20962 this.scheme = schemeOrData.scheme || _empty;
20963 this.authority = schemeOrData.authority || _empty;
20964 this.path = schemeOrData.path || _empty;
20965 this.query = schemeOrData.query || _empty;
20966 this.fragment = schemeOrData.fragment || _empty;
20967 // no validation because it's this URI
20968 // that creates uri components.
20969 // _validateUri(this);
20972 this.scheme = _schemeFix(schemeOrData, _strict);
20973 this.authority = authority || _empty;
20974 this.path = _referenceResolution(this.scheme, path || _empty);
20975 this.query = query || _empty;
20976 this.fragment = fragment || _empty;
20977 _validateUri(this, _strict);
20980 URI.isUri = function (thing) {
20981 if (thing instanceof URI) {
20987 return typeof thing.authority === 'string'
20988 && typeof thing.fragment === 'string'
20989 && typeof thing.path === 'string'
20990 && typeof thing.query === 'string'
20991 && typeof thing.scheme === 'string'
20992 && typeof thing.fsPath === 'function'
20993 && typeof thing.with === 'function'
20994 && typeof thing.toString === 'function';
20996 Object.defineProperty(URI.prototype, "fsPath", {
20997 // ---- filesystem path -----------------------
20999 * Returns a string representing the corresponding file system path of this URI.
21000 * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
21001 * platform specific path separator.
21003 * * Will *not* validate the path for invalid characters and semantics.
21004 * * Will *not* look at the scheme of this URI.
21005 * * The result shall *not* be used for display purposes but for accessing a file on disk.
21008 * The *difference* to `URI#path` is the use of the platform specific separator and the handling
21009 * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
21012 const u = URI.parse('file://server/c$/folder/file.txt')
21013 u.authority === 'server'
21014 u.path === '/shares/c$/file.txt'
21015 u.fsPath === '\\server\c$\folder\file.txt'
21018 * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
21019 * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
21020 * with URIs that represent files on disk (`file` scheme).
21023 // if (this.scheme !== 'file') {
21024 // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
21026 return _makeFsPath(this);
21031 // ---- modify to new -------------------------
21032 URI.prototype.with = function (change) {
21036 var scheme = change.scheme, authority = change.authority, path = change.path, query = change.query, fragment = change.fragment;
21037 if (scheme === undefined) {
21038 scheme = this.scheme;
21040 else if (scheme === null) {
21043 if (authority === undefined) {
21044 authority = this.authority;
21046 else if (authority === null) {
21047 authority = _empty;
21049 if (path === undefined) {
21052 else if (path === null) {
21055 if (query === undefined) {
21056 query = this.query;
21058 else if (query === null) {
21061 if (fragment === undefined) {
21062 fragment = this.fragment;
21064 else if (fragment === null) {
21067 if (scheme === this.scheme
21068 && authority === this.authority
21069 && path === this.path
21070 && query === this.query
21071 && fragment === this.fragment) {
21074 return new _URI(scheme, authority, path, query, fragment);
21076 // ---- parse & validate ------------------------
21078 * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
21079 * `file:///usr/home`, or `scheme:with/path`.
21081 * @param value A string which represents an URI (see `URI#toString`).
21083 URI.parse = function (value, _strict) {
21084 if (_strict === void 0) { _strict = false; }
21085 var match = _regexp.exec(value);
21087 return new _URI(_empty, _empty, _empty, _empty, _empty, _strict);
21089 return new _URI(match[2] || _empty, decodeURIComponentFast(match[4] || _empty, false, false), decodeURIComponentFast(match[5] || _empty, true, false), decodeURIComponentFast(match[7] || _empty, false, _isQueryStringScheme(match[2])), decodeURIComponentFast(match[9] || _empty, false, false), _strict);
21092 * Creates a new URI from a file system path, e.g. `c:\my\files`,
21093 * `/usr/home`, or `\\server\share\some\path`.
21095 * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
21096 * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
21097 * `URI.parse('file://' + path)` because the path might contain characters that are
21098 * interpreted (# and ?). See the following sample:
21100 const good = URI.file('/coding/c#/project1');
21101 good.scheme === 'file';
21102 good.path === '/coding/c#/project1';
21103 good.fragment === '';
21104 const bad = URI.parse('file://' + '/coding/c#/project1');
21105 bad.scheme === 'file';
21106 bad.path === '/coding/c'; // path is now broken
21107 bad.fragment === '/project1';
21110 * @param path A file system path (see `URI#fsPath`)
21112 URI.file = function (path) {
21113 var authority = _empty;
21114 // normalize to fwd-slashes on windows,
21115 // on other systems bwd-slashes are valid
21116 // filename character, e.g. /f\oo/ba\r.txt
21118 path = path.replace(/\\/g, _slash);
21120 // check for authority as used in UNC shares
21121 // or use the path as given
21122 if (path[0] === _slash && path[1] === _slash) {
21123 var idx = path.indexOf(_slash, 2);
21125 authority = path.substring(2);
21129 authority = path.substring(2, idx);
21130 path = path.substring(idx) || _slash;
21133 return new _URI('file', authority, path, _empty, _empty);
21135 URI.from = function (components) {
21136 return new _URI(components.scheme, components.authority, components.path, components.query, components.fragment);
21138 // ---- printing/externalize ---------------------------
21140 * Creates a string representation for this URI. It's guaranteed that calling
21141 * `URI.parse` with the result of this function creates an URI which is equal
21144 * * The result shall *not* be used for display purposes but for externalization or transport.
21145 * * The result will be encoded using the percentage encoding and encoding happens mostly
21146 * ignore the scheme-specific encoding rules.
21148 * @param skipEncoding Do not encode the result, default is `false`
21150 URI.prototype.toString = function (skipEncoding) {
21151 if (skipEncoding === void 0) { skipEncoding = false; }
21152 return _asFormatted(this, skipEncoding);
21154 URI.prototype.toJSON = function () {
21157 URI.revive = function (data) {
21161 else if (data instanceof URI) {
21165 var result = new _URI(data);
21166 result._formatted = data.external;
21167 result._fsPath = data._sep === _pathSepMarker ? data.fsPath : null;
21174 var _pathSepMarker = isWindows ? 1 : undefined;
21175 // tslint:disable-next-line:class-name
21176 var _URI = (function (_super) {
21177 __extends(_URI, _super);
21179 var _this = _super !== null && _super.apply(this, arguments) || this;
21180 _this._formatted = null;
21181 _this._fsPath = null;
21184 Object.defineProperty(_URI.prototype, "fsPath", {
21186 if (!this._fsPath) {
21187 this._fsPath = _makeFsPath(this);
21189 return this._fsPath;
21194 _URI.prototype.toString = function (skipEncoding) {
21195 if (skipEncoding === void 0) { skipEncoding = false; }
21196 if (!skipEncoding) {
21197 if (!this._formatted) {
21198 this._formatted = _asFormatted(this, false);
21200 return this._formatted;
21203 // we don't cache that
21204 return _asFormatted(this, true);
21207 _URI.prototype.toJSON = function () {
21212 if (this._fsPath) {
21213 res.fsPath = this._fsPath;
21214 res._sep = _pathSepMarker;
21216 if (this._formatted) {
21217 res.external = this._formatted;
21221 res.path = this.path;
21224 res.scheme = this.scheme;
21226 if (this.authority) {
21227 res.authority = this.authority;
21230 res.query = this.query;
21232 if (this.fragment) {
21233 res.fragment = this.fragment;
21239 function isHex(value, pos) {
21240 if (pos >= value.length) {
21243 var code = value.charCodeAt(pos);
21244 return (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */) // 0-9
21245 || (code >= 97 /* a */ && code <= 102 /* f */) //a-f
21246 || (code >= 65 /* A */ && code <= 70 /* F */); //A-F
21248 function decodeURIComponentFast(uriComponent, isPath, isQueryString) {
21250 var nativeDecodePos = -1;
21251 for (var pos = 0; pos < uriComponent.length; pos++) {
21252 var code = uriComponent.charCodeAt(pos);
21254 if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
21255 var chA = uriComponent.charCodeAt(pos + 1);
21256 var chB = uriComponent.charCodeAt(pos + 2);
21257 // when in a path -> check and accept %2f and %2F (fwd slash)
21258 // when in a query string -> check and accept %3D, %26, and %3B (equals, ampersand, semi-colon)
21259 if ((isPath && chA === 50 /* Digit2 */ && (chB === 70 /* F */ || chB === 102 /* f */))
21261 (isQueryString && ((chA === 50 /* Digit2 */ && chB === 54 /* Digit6 */) // %26
21263 (chA === 51 /* Digit3 */ && (chB === 66 /* B */ || chB === 98 /* b */ || chB === 68 /* D */ || chB === 100 /* d */)) // %3D, %3D
21265 if (nativeDecodePos !== -1) {
21266 res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
21267 nativeDecodePos = -1;
21269 if (res !== undefined) {
21270 res += uriComponent.substr(pos, 3);
21275 if (res === undefined) {
21276 res = uriComponent.substring(0, pos);
21278 if (nativeDecodePos === -1) {
21279 nativeDecodePos = pos;
21284 if (nativeDecodePos !== -1) {
21285 res += decodeURIComponent(uriComponent.substring(nativeDecodePos, pos));
21286 nativeDecodePos = -1;
21288 if (res !== undefined) {
21289 res += String.fromCharCode(code);
21293 if (nativeDecodePos !== -1) {
21294 res += decodeURIComponent(uriComponent.substr(nativeDecodePos));
21296 return res !== undefined ? res : uriComponent;
21298 // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
21299 var encodeTable = (_a = {},
21300 _a[58 /* Colon */] = '%3A',
21301 _a[47 /* Slash */] = '%2F',
21302 _a[63 /* QuestionMark */] = '%3F',
21303 _a[35 /* Hash */] = '%23',
21304 _a[91 /* OpenSquareBracket */] = '%5B',
21305 _a[93 /* CloseSquareBracket */] = '%5D',
21306 _a[64 /* AtSign */] = '%40',
21307 _a[33 /* ExclamationMark */] = '%21',
21308 _a[36 /* DollarSign */] = '%24',
21309 _a[38 /* Ampersand */] = '%26',
21310 _a[39 /* SingleQuote */] = '%27',
21311 _a[40 /* OpenParen */] = '%28',
21312 _a[41 /* CloseParen */] = '%29',
21313 _a[42 /* Asterisk */] = '%2A',
21314 _a[43 /* Plus */] = '%2B',
21315 _a[44 /* Comma */] = '%2C',
21316 _a[59 /* Semicolon */] = '%3B',
21317 _a[61 /* Equals */] = '%3D',
21318 _a[32 /* Space */] = '%20',
21320 function encodeURIComponentFast(uriComponent, isPath, isQueryString) {
21321 var res = undefined;
21322 var nativeEncodePos = -1;
21323 for (var pos = 0; pos < uriComponent.length; pos++) {
21324 var code = uriComponent.charCodeAt(pos);
21325 // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
21326 if ((code >= 97 /* a */ && code <= 122 /* z */)
21327 || (code >= 65 /* A */ && code <= 90 /* Z */)
21328 || (code >= 48 /* Digit0 */ && code <= 57 /* Digit9 */)
21329 || code === 45 /* Dash */
21330 || code === 46 /* Period */
21331 || code === 95 /* Underline */
21332 || code === 126 /* Tilde */
21333 || (isPath && code === 47 /* Slash */) // path => allow slash AS-IS
21334 || (isQueryString && (code === 61 /* Equals */ || code === 38 /* Ampersand */ || code === 59 /* Semicolon */)) // query string => allow &=;
21336 // check if we are delaying native encode
21337 if (nativeEncodePos !== -1) {
21338 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
21339 nativeEncodePos = -1;
21341 // check if we write into a new string (by default we try to return the param)
21342 if (res !== undefined) {
21343 res += uriComponent.charAt(pos);
21346 else if (code === 37 /* PercentSign */ && isHex(uriComponent, pos + 1) && isHex(uriComponent, pos + 2)) {
21347 // at percentage encoded value
21348 // check if we are delaying native encode
21349 if (nativeEncodePos !== -1) {
21350 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
21351 nativeEncodePos = -1;
21353 // check if we write into a new string (by default we try to return the param)
21354 if (res !== undefined) {
21355 res += uriComponent.substr(pos, 3);
21360 // encoding needed, we need to allocate a new string
21361 if (res === undefined) {
21362 res = uriComponent.substr(0, pos);
21364 // check with default table first
21365 var escaped = encodeTable[code];
21366 if (escaped !== undefined) {
21367 // check if we are delaying native encode
21368 if (nativeEncodePos !== -1) {
21369 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
21370 nativeEncodePos = -1;
21372 // append escaped variant to result
21375 else if (nativeEncodePos === -1) {
21376 // use native encode only when needed
21377 nativeEncodePos = pos;
21381 if (nativeEncodePos !== -1) {
21382 res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
21384 return res !== undefined ? res : uriComponent;
21386 function encodeURIComponentMinimal(path) {
21387 var res = undefined;
21388 for (var pos = 0; pos < path.length; pos++) {
21389 var code = path.charCodeAt(pos);
21390 if (code === 35 /* Hash */ || code === 63 /* QuestionMark */) {
21391 if (res === undefined) {
21392 res = path.substr(0, pos);
21394 res += encodeTable[code];
21397 if (res !== undefined) {
21402 return res !== undefined ? res : path;
21405 * Compute `fsPath` for the given uri
21407 function _makeFsPath(uri) {
21409 if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') {
21410 // unc path: file://shares/c$/far/boo
21411 value = "//" + uri.authority + uri.path;
21413 else if (uri.path.charCodeAt(0) === 47 /* Slash */
21414 && (uri.path.charCodeAt(1) >= 65 /* A */ && uri.path.charCodeAt(1) <= 90 /* Z */ || uri.path.charCodeAt(1) >= 97 /* a */ && uri.path.charCodeAt(1) <= 122 /* z */)
21415 && uri.path.charCodeAt(2) === 58 /* Colon */) {
21416 // windows drive letter: file:///c:/far/boo
21417 value = uri.path[1].toLowerCase() + uri.path.substr(2);
21424 value = value.replace(/\//g, '\\');
21429 * Create the external version of a uri
21431 function _asFormatted(uri, skipEncoding) {
21432 var encoder = !skipEncoding
21433 ? encodeURIComponentFast
21434 : encodeURIComponentMinimal;
21436 var scheme = uri.scheme, authority = uri.authority, path = uri.path, query = uri.query, fragment = uri.fragment;
21441 if (authority || scheme === 'file') {
21446 var idx = authority.indexOf('@');
21449 var userinfo = authority.substr(0, idx);
21450 authority = authority.substr(idx + 1);
21451 idx = userinfo.indexOf(':');
21453 res += encoder(userinfo, false, false);
21456 // <user>:<pass>@<auth>
21457 res += encoder(userinfo.substr(0, idx), false, false);
21459 res += encoder(userinfo.substr(idx + 1), false, false);
21463 authority = authority.toLowerCase();
21464 idx = authority.indexOf(':');
21466 res += encoder(authority, false, false);
21470 res += encoder(authority.substr(0, idx), false, false);
21471 res += authority.substr(idx);
21475 // lower-case windows drive letters in /C:/fff or C:/fff
21476 if (path.length >= 3 && path.charCodeAt(0) === 47 /* Slash */ && path.charCodeAt(2) === 58 /* Colon */) {
21477 var code = path.charCodeAt(1);
21478 if (code >= 65 /* A */ && code <= 90 /* Z */) {
21479 path = "/" + String.fromCharCode(code + 32) + ":" + path.substr(3); // "/c:".length === 3
21482 else if (path.length >= 2 && path.charCodeAt(1) === 58 /* Colon */) {
21483 var code = path.charCodeAt(0);
21484 if (code >= 65 /* A */ && code <= 90 /* Z */) {
21485 path = String.fromCharCode(code + 32) + ":" + path.substr(2); // "/c:".length === 3
21488 // encode the rest of the path
21489 res += encoder(path, true, false);
21493 res += encoder(query, false, _isQueryStringScheme(scheme));
21497 res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
21506 /***/ (function(module, __webpack_exports__, __webpack_require__) {
21509 __webpack_require__.r(__webpack_exports__);
21510 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSONDocumentSymbols", function() { return JSONDocumentSymbols; });
21511 /* harmony import */ var _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82);
21512 /* harmony import */ var _utils_strings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(91);
21513 /* harmony import */ var _utils_colors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97);
21514 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(80);
21515 /*---------------------------------------------------------------------------------------------
21516 * Copyright (c) Microsoft Corporation. All rights reserved.
21517 * Licensed under the MIT License. See License.txt in the project root for license information.
21518 *--------------------------------------------------------------------------------------------*/
21523 var JSONDocumentSymbols = /** @class */ (function () {
21524 function JSONDocumentSymbols(schemaService) {
21525 this.schemaService = schemaService;
21527 JSONDocumentSymbols.prototype.findDocumentSymbols = function (document, doc) {
21529 var root = doc.root;
21533 // special handling for key bindings
21534 var resourceString = document.uri;
21535 if ((resourceString === 'vscode://defaultsettings/keybindings.json') || _utils_strings__WEBPACK_IMPORTED_MODULE_1__["endsWith"](resourceString.toLowerCase(), '/user/keybindings.json')) {
21536 if (root.type === 'array') {
21538 root.items.forEach(function (item) {
21539 if (item.type === 'object') {
21540 for (var _i = 0, _a = item.properties; _i < _a.length; _i++) {
21541 var property = _a[_i];
21542 if (property.keyNode.value === 'key') {
21543 if (property.valueNode) {
21544 if (property.valueNode) {
21545 var location = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["Location"].create(document.uri, getRange(document, item));
21546 result_1.push({ name: _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](property.valueNode), kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Function, location: location });
21557 var collectOutlineEntries = function (result, node, containerName) {
21558 if (node.type === 'array') {
21559 node.items.forEach(function (node) { return collectOutlineEntries(result, node, containerName); });
21561 else if (node.type === 'object') {
21562 node.properties.forEach(function (property) {
21563 var location = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["Location"].create(document.uri, getRange(document, property));
21564 var valueNode = property.valueNode;
21566 var childContainerName = containerName ? containerName + '.' + property.keyNode.value : property.keyNode.value;
21567 result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), location: location, containerName: containerName });
21568 collectOutlineEntries(result, valueNode, childContainerName);
21574 var result = collectOutlineEntries([], root, void 0);
21577 JSONDocumentSymbols.prototype.findDocumentSymbols2 = function (document, doc) {
21579 var root = doc.root;
21583 // special handling for key bindings
21584 var resourceString = document.uri;
21585 if ((resourceString === 'vscode://defaultsettings/keybindings.json') || _utils_strings__WEBPACK_IMPORTED_MODULE_1__["endsWith"](resourceString.toLowerCase(), '/user/keybindings.json')) {
21586 if (root.type === 'array') {
21588 root.items.forEach(function (item) {
21589 if (item.type === 'object') {
21590 for (var _i = 0, _a = item.properties; _i < _a.length; _i++) {
21591 var property = _a[_i];
21592 if (property.keyNode.value === 'key') {
21593 if (property.valueNode) {
21594 var range = getRange(document, item);
21595 var selectionRange = getRange(document, property.keyNode);
21596 result_2.push({ name: _parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](property.valueNode), kind: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Function, range: range, selectionRange: selectionRange });
21606 var collectOutlineEntries = function (result, node) {
21607 if (node.type === 'array') {
21608 node.items.forEach(function (node, index) {
21610 var range = getRange(document, node);
21611 var selectionRange = range;
21612 var name = String(index);
21613 var children = collectOutlineEntries([], node);
21614 result.push({ name: name, kind: _this.getSymbolKind(node.type), range: range, selectionRange: selectionRange, children: children });
21618 else if (node.type === 'object') {
21619 node.properties.forEach(function (property) {
21620 var valueNode = property.valueNode;
21622 var range = getRange(document, property);
21623 var selectionRange = getRange(document, property.keyNode);
21624 var children = collectOutlineEntries([], valueNode);
21625 result.push({ name: _this.getKeyLabel(property), kind: _this.getSymbolKind(valueNode.type), range: range, selectionRange: selectionRange, children: children });
21631 var result = collectOutlineEntries([], root);
21634 JSONDocumentSymbols.prototype.getSymbolKind = function (nodeType) {
21635 switch (nodeType) {
21637 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Module;
21639 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].String;
21641 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Number;
21643 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Array;
21645 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Boolean;
21647 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["SymbolKind"].Variable;
21650 JSONDocumentSymbols.prototype.getKeyLabel = function (property) {
21651 var name = property.keyNode.value;
21653 name = name.replace(/[\n]/g, '↵');
21655 if (name && name.trim()) {
21658 return "\"" + name + "\"";
21660 JSONDocumentSymbols.prototype.findDocumentColors = function (document, doc) {
21661 return this.schemaService.getSchemaForResource(document.uri, doc).then(function (schema) {
21664 var matchingSchemas = doc.getMatchingSchemas(schema.schema);
21665 var visitedNode = {};
21666 for (var _i = 0, matchingSchemas_1 = matchingSchemas; _i < matchingSchemas_1.length; _i++) {
21667 var s = matchingSchemas_1[_i];
21668 if (!s.inverted && s.schema && (s.schema.format === 'color' || s.schema.format === 'color-hex') && s.node && s.node.type === 'string') {
21669 var nodeId = String(s.node.offset);
21670 if (!visitedNode[nodeId]) {
21671 var color = Object(_utils_colors__WEBPACK_IMPORTED_MODULE_2__["colorFromHex"])(_parser_jsonParser__WEBPACK_IMPORTED_MODULE_0__["getNodeValue"](s.node));
21673 var range = getRange(document, s.node);
21674 result.push({ color: color, range: range });
21676 visitedNode[nodeId] = true;
21684 JSONDocumentSymbols.prototype.getColorPresentations = function (document, doc, color, range) {
21686 var red256 = Math.round(color.red * 255), green256 = Math.round(color.green * 255), blue256 = Math.round(color.blue * 255);
21687 function toTwoDigitHex(n) {
21688 var r = n.toString(16);
21689 return r.length !== 2 ? '0' + r : r;
21692 if (color.alpha === 1) {
21693 label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256);
21696 label = "#" + toTwoDigitHex(red256) + toTwoDigitHex(green256) + toTwoDigitHex(blue256) + toTwoDigitHex(Math.round(color.alpha * 255));
21698 result.push({ label: label, textEdit: vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["TextEdit"].replace(range, JSON.stringify(label)) });
21701 return JSONDocumentSymbols;
21704 function getRange(document, node) {
21705 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_3__["Range"].create(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
21711 /***/ (function(module, __webpack_exports__, __webpack_require__) {
21714 __webpack_require__.r(__webpack_exports__);
21715 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hexDigit", function() { return hexDigit; });
21716 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorFromHex", function() { return colorFromHex; });
21717 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorFrom256RGB", function() { return colorFrom256RGB; });
21718 /*---------------------------------------------------------------------------------------------
21719 * Copyright (c) Microsoft Corporation. All rights reserved.
21720 * Licensed under the MIT License. See License.txt in the project root for license information.
21721 *--------------------------------------------------------------------------------------------*/
21727 function hexDigit(charCode) {
21728 if (charCode < Digit0) {
21731 if (charCode <= Digit9) {
21732 return charCode - Digit0;
21734 if (charCode < a) {
21735 charCode += (a - A);
21737 if (charCode >= a && charCode <= f) {
21738 return charCode - a + 10;
21742 function colorFromHex(text) {
21743 if (text[0] !== '#') {
21746 switch (text.length) {
21749 red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
21750 green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
21751 blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
21756 red: (hexDigit(text.charCodeAt(1)) * 0x11) / 255.0,
21757 green: (hexDigit(text.charCodeAt(2)) * 0x11) / 255.0,
21758 blue: (hexDigit(text.charCodeAt(3)) * 0x11) / 255.0,
21759 alpha: (hexDigit(text.charCodeAt(4)) * 0x11) / 255.0,
21763 red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
21764 green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
21765 blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
21770 red: (hexDigit(text.charCodeAt(1)) * 0x10 + hexDigit(text.charCodeAt(2))) / 255.0,
21771 green: (hexDigit(text.charCodeAt(3)) * 0x10 + hexDigit(text.charCodeAt(4))) / 255.0,
21772 blue: (hexDigit(text.charCodeAt(5)) * 0x10 + hexDigit(text.charCodeAt(6))) / 255.0,
21773 alpha: (hexDigit(text.charCodeAt(7)) * 0x10 + hexDigit(text.charCodeAt(8))) / 255.0
21778 function colorFrom256RGB(red, green, blue, alpha) {
21779 if (alpha === void 0) { alpha = 1.0; }
21782 green: green / 255.0,
21783 blue: blue / 255.0,
21791 /***/ (function(module, __webpack_exports__, __webpack_require__) {
21794 __webpack_require__.r(__webpack_exports__);
21795 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schemaContributions", function() { return schemaContributions; });
21796 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(76);
21797 /* harmony import */ var vscode_nls__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vscode_nls__WEBPACK_IMPORTED_MODULE_0__);
21798 /*---------------------------------------------------------------------------------------------
21799 * Copyright (c) Microsoft Corporation. All rights reserved.
21800 * Licensed under the MIT License. See License.txt in the project root for license information.
21801 *--------------------------------------------------------------------------------------------*/
21803 var localize = vscode_nls__WEBPACK_IMPORTED_MODULE_0__["loadMessageBundle"]();
21804 var schemaContributions = {
21805 schemaAssociations: {},
21807 // bundle the schema-schema to include (localized) descriptions
21808 'http://json-schema.org/draft-04/schema#': {
21809 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
21810 '$schema': 'http://json-schema.org/draft-04/schema#',
21819 'positiveInteger': {
21823 'positiveIntegerDefault0': {
21826 '$ref': '#/definitions/positiveInteger'
21851 'uniqueItems': true
21874 'exclusiveMinimum': true
21879 'exclusiveMaximum': {
21886 'exclusiveMinimum': {
21893 '$ref': '#/definitions/positiveInteger'
21900 '$ref': '#/definitions/positiveIntegerDefault0'
21908 'additionalItems': {
21925 '$ref': '#/definitions/schemaArray'
21933 '$ref': '#/definitions/positiveInteger'
21940 '$ref': '#/definitions/positiveIntegerDefault0'
21951 '$ref': '#/definitions/positiveInteger'
21958 '$ref': '#/definitions/positiveIntegerDefault0'
21965 '$ref': '#/definitions/stringArray'
21969 'additionalProperties': {
21982 'additionalProperties': {
21989 'additionalProperties': {
21994 'patternProperties': {
21996 'additionalProperties': {
22003 'additionalProperties': {
22009 '$ref': '#/definitions/stringArray'
22017 'uniqueItems': true
22022 '$ref': '#/definitions/simpleTypes'
22027 '$ref': '#/definitions/simpleTypes'
22030 'uniqueItems': true
22056 '$ref': '#/definitions/schemaArray'
22063 '$ref': '#/definitions/schemaArray'
22070 '$ref': '#/definitions/schemaArray'
22083 'exclusiveMaximum': [
22086 'exclusiveMinimum': [
22092 'http://json-schema.org/draft-07/schema#': {
22093 'title': localize('schema.json', 'Describes a JSON file using a schema. See json-schema.org for more info.'),
22098 'items': { '$ref': '#' }
22100 'nonNegativeInteger': {
22104 'nonNegativeIntegerDefault0': {
22106 { '$ref': '#/definitions/nonNegativeInteger' },
22123 'items': { 'type': 'string' },
22124 'uniqueItems': true,
22128 'type': ['object', 'boolean'],
22132 'format': 'uri-reference'
22140 'format': 'uri-reference'
22162 'exclusiveMinimum': 0
22167 'exclusiveMaximum': {
22173 'exclusiveMinimum': {
22176 'maxLength': { '$ref': '#/definitions/nonNegativeInteger' },
22177 'minLength': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
22182 'additionalItems': { '$ref': '#' },
22186 { '$ref': '#/definitions/schemaArray' }
22190 'maxItems': { '$ref': '#/definitions/nonNegativeInteger' },
22191 'minItems': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
22196 'contains': { '$ref': '#' },
22197 'maxProperties': { '$ref': '#/definitions/nonNegativeInteger' },
22198 'minProperties': { '$ref': '#/definitions/nonNegativeIntegerDefault0' },
22199 'required': { '$ref': '#/definitions/stringArray' },
22200 'additionalProperties': { '$ref': '#' },
22203 'additionalProperties': { '$ref': '#' },
22208 'additionalProperties': { '$ref': '#' },
22211 'patternProperties': {
22213 'additionalProperties': { '$ref': '#' },
22214 'propertyNames': { 'format': 'regex' },
22219 'additionalProperties': {
22222 { '$ref': '#/definitions/stringArray' }
22226 'propertyNames': { '$ref': '#' },
22232 'uniqueItems': true
22236 { '$ref': '#/definitions/simpleTypes' },
22239 'items': { '$ref': '#/definitions/simpleTypes' },
22241 'uniqueItems': true
22245 'format': { 'type': 'string' },
22246 'contentMediaType': { 'type': 'string' },
22247 'contentEncoding': { 'type': 'string' },
22248 'if': { '$ref': '#' },
22249 'then': { '$ref': '#' },
22250 'else': { '$ref': '#' },
22251 'allOf': { '$ref': '#/definitions/schemaArray' },
22252 'anyOf': { '$ref': '#/definitions/schemaArray' },
22253 'oneOf': { '$ref': '#/definitions/schemaArray' },
22254 'not': { '$ref': '#' }
22260 var descriptions = {
22261 id: localize('schema.json.id', "A unique identifier for the schema."),
22262 $schema: localize('schema.json.$schema', "The schema to verify this document against."),
22263 title: localize('schema.json.title', "A descriptive title of the element."),
22264 description: localize('schema.json.description', "A long description of the element. Used in hover menus and suggestions."),
22265 default: localize('schema.json.default', "A default value. Used by suggestions."),
22266 multipleOf: localize('schema.json.multipleOf', "A number that should cleanly divide the current value (i.e. have no remainder)."),
22267 maximum: localize('schema.json.maximum', "The maximum numerical value, inclusive by default."),
22268 exclusiveMaximum: localize('schema.json.exclusiveMaximum', "Makes the maximum property exclusive."),
22269 minimum: localize('schema.json.minimum', "The minimum numerical value, inclusive by default."),
22270 exclusiveMinimum: localize('schema.json.exclusiveMininum', "Makes the minimum property exclusive."),
22271 maxLength: localize('schema.json.maxLength', "The maximum length of a string."),
22272 minLength: localize('schema.json.minLength', "The minimum length of a string."),
22273 pattern: localize('schema.json.pattern', "A regular expression to match the string against. It is not implicitly anchored."),
22274 additionalItems: localize('schema.json.additionalItems', "For arrays, only when items is set as an array. If it is a schema, then this schema validates items after the ones specified by the items array. If it is false, then additional items will cause validation to fail."),
22275 items: localize('schema.json.items', "For arrays. Can either be a schema to validate every element against or an array of schemas to validate each item against in order (the first schema will validate the first element, the second schema will validate the second element, and so on."),
22276 maxItems: localize('schema.json.maxItems', "The maximum number of items that can be inside an array. Inclusive."),
22277 minItems: localize('schema.json.minItems', "The minimum number of items that can be inside an array. Inclusive."),
22278 uniqueItems: localize('schema.json.uniqueItems', "If all of the items in the array must be unique. Defaults to false."),
22279 maxProperties: localize('schema.json.maxProperties', "The maximum number of properties an object can have. Inclusive."),
22280 minProperties: localize('schema.json.minProperties', "The minimum number of properties an object can have. Inclusive."),
22281 required: localize('schema.json.required', "An array of strings that lists the names of all properties required on this object."),
22282 additionalProperties: localize('schema.json.additionalProperties', "Either a schema or a boolean. If a schema, then used to validate all properties not matched by 'properties' or 'patternProperties'. If false, then any properties not matched by either will cause this schema to fail."),
22283 definitions: localize('schema.json.definitions', "Not used for validation. Place subschemas here that you wish to reference inline with $ref."),
22284 properties: localize('schema.json.properties', "A map of property names to schemas for each property."),
22285 patternProperties: localize('schema.json.patternProperties', "A map of regular expressions on property names to schemas for matching properties."),
22286 dependencies: localize('schema.json.dependencies', "A map of property names to either an array of property names or a schema. An array of property names means the property named in the key depends on the properties in the array being present in the object in order to be valid. If the value is a schema, then the schema is only applied to the object if the property in the key exists on the object."),
22287 enum: localize('schema.json.enum', "The set of literal values that are valid."),
22288 type: localize('schema.json.type', "Either a string of one of the basic schema types (number, integer, null, array, object, boolean, string) or an array of strings specifying a subset of those types."),
22289 format: localize('schema.json.format', "Describes the format expected for the value."),
22290 allOf: localize('schema.json.allOf', "An array of schemas, all of which must match."),
22291 anyOf: localize('schema.json.anyOf', "An array of schemas, where at least one must match."),
22292 oneOf: localize('schema.json.oneOf', "An array of schemas, exactly one of which must match."),
22293 not: localize('schema.json.not', "A schema which must not match."),
22294 $id: localize('schema.json.$id', "A unique identifier for the schema."),
22295 $ref: localize('schema.json.$ref', "Reference a definition hosted on any location."),
22296 $comment: localize('schema.json.$comment', "Comments from schema authors to readers or maintainers of the schema."),
22297 readOnly: localize('schema.json.readOnly', "Indicates that the value of the instance is managed exclusively by the owning authority."),
22298 examples: localize('schema.json.examples', "Sample JSON values associated with a particular schema, for the purpose of illustrating usage."),
22299 contains: localize('schema.json.contains', "An array instance is valid against \"contains\" if at least one of its elements is valid against the given schema."),
22300 propertyNames: localize('schema.json.propertyNames', "If the instance is an object, this keyword validates if every property name in the instance validates against the provided schema."),
22301 const: localize('schema.json.const', "An instance validates successfully against this keyword if its value is equal to the value of the keyword."),
22302 contentMediaType: localize('schema.json.contentMediaType', "Describes the media type of a string property."),
22303 contentEncoding: localize('schema.json.contentEncoding', "Describes the content encoding of a string property."),
22304 if: localize('schema.json.if', "The validation outcome of the \"if\" subschema controls which of the \"then\" or \"else\" keywords are evaluated."),
22305 then: localize('schema.json.then', "The \"if\" subschema is used for validation when the \"if\" subschema succeeds."),
22306 else: localize('schema.json.else', "The \"else\" subschema is used for validation when the \"if\" subschema fails.")
22308 for (var schemaName in schemaContributions.schemas) {
22309 var schema = schemaContributions.schemas[schemaName];
22310 for (var property in schema.properties) {
22311 var propertyObject = schema.properties[property];
22312 if (propertyObject === true) {
22313 propertyObject = schema.properties[property] = {};
22315 var description = descriptions[property];
22317 propertyObject['description'] = description;
22320 console.log(property + ": localize('schema.json." + property + "', \"\")");
22328 /***/ (function(module, __webpack_exports__, __webpack_require__) {
22331 __webpack_require__.r(__webpack_exports__);
22332 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFoldingRanges", function() { return getFoldingRanges; });
22333 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
22334 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(83);
22335 /* harmony import */ var _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89);
22336 /*---------------------------------------------------------------------------------------------
22337 * Copyright (c) Microsoft Corporation. All rights reserved.
22338 * Licensed under the MIT License. See License.txt in the project root for license information.
22339 *--------------------------------------------------------------------------------------------*/
22343 function getFoldingRanges(document, context) {
22345 var nestingLevels = [];
22347 var prevStart = -1;
22348 var scanner = Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"])(document.getText(), false);
22349 var token = scanner.scan();
22350 function addRange(range) {
22351 ranges.push(range);
22352 nestingLevels.push(stack.length);
22354 while (token !== 17 /* EOF */) {
22356 case 1 /* OpenBraceToken */:
22357 case 3 /* OpenBracketToken */: {
22358 var startLine = document.positionAt(scanner.getTokenOffset()).line;
22359 var range = { startLine: startLine, endLine: startLine, kind: token === 1 /* OpenBraceToken */ ? 'object' : 'array' };
22363 case 2 /* CloseBraceToken */:
22364 case 4 /* CloseBracketToken */: {
22365 var kind = token === 2 /* CloseBraceToken */ ? 'object' : 'array';
22366 if (stack.length > 0 && stack[stack.length - 1].kind === kind) {
22367 var range = stack.pop();
22368 var line = document.positionAt(scanner.getTokenOffset()).line;
22369 if (range && line > range.startLine + 1 && prevStart !== range.startLine) {
22370 range.endLine = line - 1;
22372 prevStart = range.startLine;
22377 case 13 /* BlockCommentTrivia */: {
22378 var startLine = document.positionAt(scanner.getTokenOffset()).line;
22379 var endLine = document.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()).line;
22380 if (scanner.getTokenError() === 1 /* UnexpectedEndOfComment */ && startLine + 1 < document.lineCount) {
22381 scanner.setPosition(document.offsetAt(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Position"].create(startLine + 1, 0)));
22384 if (startLine < endLine) {
22385 addRange({ startLine: startLine, endLine: endLine, kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["FoldingRangeKind"].Comment });
22386 prevStart = startLine;
22391 case 12 /* LineCommentTrivia */: {
22392 var text = document.getText().substr(scanner.getTokenOffset(), scanner.getTokenLength());
22393 var m = text.match(/^\/\/\s*#(region\b)|(endregion\b)/);
22395 var line = document.positionAt(scanner.getTokenOffset()).line;
22396 if (m[1]) { // start pattern match
22397 var range = { startLine: line, endLine: line, kind: _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["FoldingRangeKind"].Region };
22401 var i = stack.length - 1;
22402 while (i >= 0 && stack[i].kind !== _jsonLanguageTypes__WEBPACK_IMPORTED_MODULE_2__["FoldingRangeKind"].Region) {
22406 var range = stack[i];
22408 if (line > range.startLine && prevStart !== range.startLine) {
22409 range.endLine = line;
22411 prevStart = range.startLine;
22419 token = scanner.scan();
22421 var rangeLimit = context && context.rangeLimit;
22422 if (typeof rangeLimit !== 'number' || ranges.length <= rangeLimit) {
22426 for (var _i = 0, nestingLevels_1 = nestingLevels; _i < nestingLevels_1.length; _i++) {
22427 var level = nestingLevels_1[_i];
22429 counts[level] = (counts[level] || 0) + 1;
22434 for (var i = 0; i < counts.length; i++) {
22437 if (n + entries > rangeLimit) {
22445 for (var i = 0; i < ranges.length; i++) {
22446 var level = nestingLevels[i];
22447 if (typeof level === 'number') {
22448 if (level < maxLevel || (level === maxLevel && entries++ < rangeLimit)) {
22449 result.push(ranges[i]);
22459 /***/ (function(module, __webpack_exports__, __webpack_require__) {
22462 __webpack_require__.r(__webpack_exports__);
22463 /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSelectionRanges", function() { return getSelectionRanges; });
22464 /* harmony import */ var vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(80);
22465 /* harmony import */ var jsonc_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(83);
22466 /*---------------------------------------------------------------------------------------------
22467 * Copyright (c) Microsoft Corporation. All rights reserved.
22468 * Licensed under the MIT License. See License.txt in the project root for license information.
22469 *--------------------------------------------------------------------------------------------*/
22472 function getSelectionRanges(document, positions, doc) {
22473 function getSelectionRange(position) {
22474 var offset = document.offsetAt(position);
22475 var node = doc.getNodeFromOffset(offset, true);
22478 switch (node.type) {
22482 // range without ", [ or {
22483 var cStart = node.offset + 1, cEnd = node.offset + node.length - 1;
22484 if (cStart < cEnd && offset >= cStart && offset <= cEnd) {
22485 result.push(newRange(cStart, cEnd));
22487 result.push(newRange(node.offset, node.offset + node.length));
22493 result.push(newRange(node.offset, node.offset + node.length));
22496 if (node.type === 'property' || node.parent && node.parent.type === 'array') {
22497 var afterCommaOffset = getOffsetAfterNextToken(node.offset + node.length, 5 /* CommaToken */);
22498 if (afterCommaOffset !== -1) {
22499 result.push(newRange(node.offset, afterCommaOffset));
22502 node = node.parent;
22504 var current = undefined;
22505 for (var index = result.length - 1; index >= 0; index--) {
22506 current = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"].create(result[index], current);
22509 current = vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["SelectionRange"].create(vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"].create(position, position));
22513 function newRange(start, end) {
22514 return vscode_languageserver_types__WEBPACK_IMPORTED_MODULE_0__["Range"].create(document.positionAt(start), document.positionAt(end));
22516 var scanner = Object(jsonc_parser__WEBPACK_IMPORTED_MODULE_1__["createScanner"])(document.getText(), true);
22517 function getOffsetAfterNextToken(offset, expectedToken) {
22518 scanner.setPosition(offset);
22519 var token = scanner.scan();
22520 if (token === expectedToken) {
22521 return scanner.getTokenOffset() + scanner.getTokenLength();
22525 return positions.map(getSelectionRange);
22531 /***/ (function(module, exports, __webpack_require__) {
22535 /*---------------------------------------------------------------------------------------------
22536 * Copyright (c) Microsoft Corporation. All rights reserved.
22537 * Licensed under the MIT License. See License.txt in the project root for license information.
22538 *--------------------------------------------------------------------------------------------*/
22539 Object.defineProperty(exports, "__esModule", { value: true });
22540 function getLanguageModelCache(maxEntries, cleanupIntervalTimeInSec, parse) {
22541 let languageModels = {};
22543 let cleanupInterval = undefined;
22544 if (cleanupIntervalTimeInSec > 0) {
22545 cleanupInterval = setInterval(() => {
22546 let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
22547 let uris = Object.keys(languageModels);
22548 for (let uri of uris) {
22549 let languageModelInfo = languageModels[uri];
22550 if (languageModelInfo.cTime < cutoffTime) {
22551 delete languageModels[uri];
22555 }, cleanupIntervalTimeInSec * 1000);
22559 let version = document.version;
22560 let languageId = document.languageId;
22561 let languageModelInfo = languageModels[document.uri];
22562 if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
22563 languageModelInfo.cTime = Date.now();
22564 return languageModelInfo.languageModel;
22566 let languageModel = parse(document);
22567 languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
22568 if (!languageModelInfo) {
22571 if (nModels === maxEntries) {
22572 let oldestTime = Number.MAX_VALUE;
22573 let oldestUri = null;
22574 for (let uri in languageModels) {
22575 let languageModelInfo = languageModels[uri];
22576 if (languageModelInfo.cTime < oldestTime) {
22578 oldestTime = languageModelInfo.cTime;
22582 delete languageModels[oldestUri];
22586 return languageModel;
22588 onDocumentRemoved(document) {
22589 let uri = document.uri;
22590 if (languageModels[uri]) {
22591 delete languageModels[uri];
22596 if (typeof cleanupInterval !== 'undefined') {
22597 clearInterval(cleanupInterval);
22598 cleanupInterval = undefined;
22599 languageModels = {};
22605 exports.getLanguageModelCache = getLanguageModelCache;