@codingame/monaco-vscode-rollup-vsix-plugin 1.81.8-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1305 @@
1
+ import { addExtension, createFilter } from '@rollup/pluginutils';
2
+ import * as yauzl from 'yauzl';
3
+ import * as path from 'path';
4
+ import * as mime from 'mime-types';
5
+
6
+ /*---------------------------------------------------------------------------------------------
7
+ * Copyright (c) Microsoft Corporation. All rights reserved.
8
+ * Licensed under the MIT License. See License.txt in the project root for license information.
9
+ *--------------------------------------------------------------------------------------------*/
10
+ /**
11
+ * @returns whether the provided parameter is a JavaScript String or not.
12
+ */
13
+ function isString(str) {
14
+ return (typeof str === 'string');
15
+ }
16
+ /**
17
+ * @returns whether the provided parameter is of type `object` but **not**
18
+ * `null`, an `array`, a `regexp`, nor a `date`.
19
+ */
20
+ function isObject(obj) {
21
+ // The method can't do a type cast since there are type (like strings) which
22
+ // are subclasses of any put not positvely matched by the function. Hence type
23
+ // narrowing results in wrong results.
24
+ return typeof obj === 'object'
25
+ && obj !== null
26
+ && !Array.isArray(obj)
27
+ && !(obj instanceof RegExp)
28
+ && !(obj instanceof Date);
29
+ }
30
+
31
+ /*---------------------------------------------------------------------------------------------
32
+ * Copyright (c) Microsoft Corporation. All rights reserved.
33
+ * Licensed under the MIT License. See License.txt in the project root for license information.
34
+ *--------------------------------------------------------------------------------------------*/
35
+ let isPseudo = (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0);
36
+ function _format(message, args) {
37
+ let result;
38
+ if (args.length === 0) {
39
+ result = message;
40
+ }
41
+ else {
42
+ result = message.replace(/\{(\d+)\}/g, (match, rest) => {
43
+ const index = rest[0];
44
+ const arg = args[index];
45
+ let result = match;
46
+ if (typeof arg === 'string') {
47
+ result = arg;
48
+ }
49
+ else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) {
50
+ result = String(arg);
51
+ }
52
+ return result;
53
+ });
54
+ }
55
+ if (isPseudo) {
56
+ // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
57
+ result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D';
58
+ }
59
+ return result;
60
+ }
61
+ /**
62
+ * @skipMangle
63
+ */
64
+ function localize(data, message, ...args) {
65
+ return _format(message, args);
66
+ }
67
+
68
+ /*---------------------------------------------------------------------------------------------
69
+ * Copyright (c) Microsoft Corporation. All rights reserved.
70
+ * Licensed under the MIT License. See License.txt in the project root for license information.
71
+ *--------------------------------------------------------------------------------------------*/
72
+ function localizeManifest(extensionManifest, translations, fallbackTranslations) {
73
+ try {
74
+ replaceNLStrings(extensionManifest, translations, fallbackTranslations);
75
+ }
76
+ catch (error) {
77
+ console.error(error?.message ?? error);
78
+ /*Ignore Error*/
79
+ }
80
+ return extensionManifest;
81
+ }
82
+ /**
83
+ * This routine makes the following assumptions:
84
+ * The root element is an object literal
85
+ */
86
+ function replaceNLStrings(extensionManifest, messages, originalMessages) {
87
+ const processEntry = (obj, key, command) => {
88
+ const value = obj[key];
89
+ if (isString(value)) {
90
+ const str = value;
91
+ const length = str.length;
92
+ if (length > 1 && str[0] === '%' && str[length - 1] === '%') {
93
+ const messageKey = str.substr(1, length - 2);
94
+ let translated = messages[messageKey];
95
+ // If the messages come from a language pack they might miss some keys
96
+ // Fill them from the original messages.
97
+ if (translated === undefined && originalMessages) {
98
+ translated = originalMessages[messageKey];
99
+ }
100
+ const message = typeof translated === 'string' ? translated : translated?.message;
101
+ // This branch returns ILocalizedString's instead of Strings so that the Command Palette can contain both the localized and the original value.
102
+ const original = originalMessages?.[messageKey];
103
+ const originalMessage = typeof original === 'string' ? original : original?.message;
104
+ if (!message) {
105
+ if (!originalMessage) {
106
+ console.warn(`[${extensionManifest.name}]: ${localize('missingNLSKey', "Couldn't find message for key {0}.", messageKey)}`);
107
+ }
108
+ return;
109
+ }
110
+ if (
111
+ // if we are translating the title or category of a command
112
+ command && (key === 'title' || key === 'category') &&
113
+ // and the original value is not the same as the translated value
114
+ originalMessage && originalMessage !== message) {
115
+ const localizedString = {
116
+ value: message,
117
+ original: originalMessage
118
+ };
119
+ obj[key] = localizedString;
120
+ }
121
+ else {
122
+ obj[key] = message;
123
+ }
124
+ }
125
+ }
126
+ else if (isObject(value)) {
127
+ for (const k in value) {
128
+ if (value.hasOwnProperty(k)) {
129
+ k === 'commands' ? processEntry(value, k, true) : processEntry(value, k, command);
130
+ }
131
+ }
132
+ }
133
+ else if (Array.isArray(value)) {
134
+ for (let i = 0; i < value.length; i++) {
135
+ processEntry(value, i, command);
136
+ }
137
+ }
138
+ };
139
+ for (const key in extensionManifest) {
140
+ if (extensionManifest.hasOwnProperty(key)) {
141
+ processEntry(extensionManifest, key);
142
+ }
143
+ }
144
+ }
145
+
146
+ /*---------------------------------------------------------------------------------------------
147
+ * Copyright (c) Microsoft Corporation. All rights reserved.
148
+ * Licensed under the MIT License. See License.txt in the project root for license information.
149
+ *--------------------------------------------------------------------------------------------*/
150
+ var ScanError;
151
+ (function (ScanError) {
152
+ ScanError[ScanError["None"] = 0] = "None";
153
+ ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
154
+ ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
155
+ ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
156
+ ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode";
157
+ ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
158
+ ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";
159
+ })(ScanError || (ScanError = {}));
160
+ var SyntaxKind;
161
+ (function (SyntaxKind) {
162
+ SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken";
163
+ SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken";
164
+ SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken";
165
+ SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken";
166
+ SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken";
167
+ SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken";
168
+ SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword";
169
+ SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword";
170
+ SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword";
171
+ SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
172
+ SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral";
173
+ SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia";
174
+ SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
175
+ SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia";
176
+ SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia";
177
+ SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown";
178
+ SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF";
179
+ })(SyntaxKind || (SyntaxKind = {}));
180
+ var ParseErrorCode;
181
+ (function (ParseErrorCode) {
182
+ ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol";
183
+ ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
184
+ ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected";
185
+ ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected";
186
+ ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected";
187
+ ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected";
188
+ ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected";
189
+ ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected";
190
+ ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected";
191
+ ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken";
192
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
193
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
194
+ ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
195
+ ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode";
196
+ ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
197
+ ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter";
198
+ })(ParseErrorCode || (ParseErrorCode = {}));
199
+ var ParseOptions;
200
+ (function (ParseOptions) {
201
+ ParseOptions.DEFAULT = {
202
+ allowTrailingComma: true
203
+ };
204
+ })(ParseOptions || (ParseOptions = {}));
205
+ /**
206
+ * Creates a JSON scanner on the given text.
207
+ * If ignoreTrivia is set, whitespaces or comments are ignored.
208
+ */
209
+ function createScanner(text, ignoreTrivia = false) {
210
+ let pos = 0;
211
+ const len = text.length;
212
+ let value = '';
213
+ let tokenOffset = 0;
214
+ let token = 16 /* SyntaxKind.Unknown */;
215
+ let scanError = 0 /* ScanError.None */;
216
+ function scanHexDigits(count) {
217
+ let digits = 0;
218
+ let hexValue = 0;
219
+ while (digits < count) {
220
+ const ch = text.charCodeAt(pos);
221
+ if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {
222
+ hexValue = hexValue * 16 + ch - 48 /* CharacterCodes._0 */;
223
+ }
224
+ else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {
225
+ hexValue = hexValue * 16 + ch - 65 /* CharacterCodes.A */ + 10;
226
+ }
227
+ else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {
228
+ hexValue = hexValue * 16 + ch - 97 /* CharacterCodes.a */ + 10;
229
+ }
230
+ else {
231
+ break;
232
+ }
233
+ pos++;
234
+ digits++;
235
+ }
236
+ if (digits < count) {
237
+ hexValue = -1;
238
+ }
239
+ return hexValue;
240
+ }
241
+ function setPosition(newPosition) {
242
+ pos = newPosition;
243
+ value = '';
244
+ tokenOffset = 0;
245
+ token = 16 /* SyntaxKind.Unknown */;
246
+ scanError = 0 /* ScanError.None */;
247
+ }
248
+ function scanNumber() {
249
+ const start = pos;
250
+ if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {
251
+ pos++;
252
+ }
253
+ else {
254
+ pos++;
255
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
256
+ pos++;
257
+ }
258
+ }
259
+ if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {
260
+ pos++;
261
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
262
+ pos++;
263
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
264
+ pos++;
265
+ }
266
+ }
267
+ else {
268
+ scanError = 3 /* ScanError.UnexpectedEndOfNumber */;
269
+ return text.substring(start, pos);
270
+ }
271
+ }
272
+ let end = pos;
273
+ if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {
274
+ pos++;
275
+ if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {
276
+ pos++;
277
+ }
278
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
279
+ pos++;
280
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
281
+ pos++;
282
+ }
283
+ end = pos;
284
+ }
285
+ else {
286
+ scanError = 3 /* ScanError.UnexpectedEndOfNumber */;
287
+ }
288
+ }
289
+ return text.substring(start, end);
290
+ }
291
+ function scanString() {
292
+ let result = '', start = pos;
293
+ while (true) {
294
+ if (pos >= len) {
295
+ result += text.substring(start, pos);
296
+ scanError = 2 /* ScanError.UnexpectedEndOfString */;
297
+ break;
298
+ }
299
+ const ch = text.charCodeAt(pos);
300
+ if (ch === 34 /* CharacterCodes.doubleQuote */) {
301
+ result += text.substring(start, pos);
302
+ pos++;
303
+ break;
304
+ }
305
+ if (ch === 92 /* CharacterCodes.backslash */) {
306
+ result += text.substring(start, pos);
307
+ pos++;
308
+ if (pos >= len) {
309
+ scanError = 2 /* ScanError.UnexpectedEndOfString */;
310
+ break;
311
+ }
312
+ const ch2 = text.charCodeAt(pos++);
313
+ switch (ch2) {
314
+ case 34 /* CharacterCodes.doubleQuote */:
315
+ result += '\"';
316
+ break;
317
+ case 92 /* CharacterCodes.backslash */:
318
+ result += '\\';
319
+ break;
320
+ case 47 /* CharacterCodes.slash */:
321
+ result += '/';
322
+ break;
323
+ case 98 /* CharacterCodes.b */:
324
+ result += '\b';
325
+ break;
326
+ case 102 /* CharacterCodes.f */:
327
+ result += '\f';
328
+ break;
329
+ case 110 /* CharacterCodes.n */:
330
+ result += '\n';
331
+ break;
332
+ case 114 /* CharacterCodes.r */:
333
+ result += '\r';
334
+ break;
335
+ case 116 /* CharacterCodes.t */:
336
+ result += '\t';
337
+ break;
338
+ case 117 /* CharacterCodes.u */: {
339
+ const ch3 = scanHexDigits(4);
340
+ if (ch3 >= 0) {
341
+ result += String.fromCharCode(ch3);
342
+ }
343
+ else {
344
+ scanError = 4 /* ScanError.InvalidUnicode */;
345
+ }
346
+ break;
347
+ }
348
+ default:
349
+ scanError = 5 /* ScanError.InvalidEscapeCharacter */;
350
+ }
351
+ start = pos;
352
+ continue;
353
+ }
354
+ if (ch >= 0 && ch <= 0x1F) {
355
+ if (isLineBreak(ch)) {
356
+ result += text.substring(start, pos);
357
+ scanError = 2 /* ScanError.UnexpectedEndOfString */;
358
+ break;
359
+ }
360
+ else {
361
+ scanError = 6 /* ScanError.InvalidCharacter */;
362
+ // mark as error but continue with string
363
+ }
364
+ }
365
+ pos++;
366
+ }
367
+ return result;
368
+ }
369
+ function scanNext() {
370
+ value = '';
371
+ scanError = 0 /* ScanError.None */;
372
+ tokenOffset = pos;
373
+ if (pos >= len) {
374
+ // at the end
375
+ tokenOffset = len;
376
+ return token = 17 /* SyntaxKind.EOF */;
377
+ }
378
+ let code = text.charCodeAt(pos);
379
+ // trivia: whitespace
380
+ if (isWhitespace(code)) {
381
+ do {
382
+ pos++;
383
+ value += String.fromCharCode(code);
384
+ code = text.charCodeAt(pos);
385
+ } while (isWhitespace(code));
386
+ return token = 15 /* SyntaxKind.Trivia */;
387
+ }
388
+ // trivia: newlines
389
+ if (isLineBreak(code)) {
390
+ pos++;
391
+ value += String.fromCharCode(code);
392
+ if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {
393
+ pos++;
394
+ value += '\n';
395
+ }
396
+ return token = 14 /* SyntaxKind.LineBreakTrivia */;
397
+ }
398
+ switch (code) {
399
+ // tokens: []{}:,
400
+ case 123 /* CharacterCodes.openBrace */:
401
+ pos++;
402
+ return token = 1 /* SyntaxKind.OpenBraceToken */;
403
+ case 125 /* CharacterCodes.closeBrace */:
404
+ pos++;
405
+ return token = 2 /* SyntaxKind.CloseBraceToken */;
406
+ case 91 /* CharacterCodes.openBracket */:
407
+ pos++;
408
+ return token = 3 /* SyntaxKind.OpenBracketToken */;
409
+ case 93 /* CharacterCodes.closeBracket */:
410
+ pos++;
411
+ return token = 4 /* SyntaxKind.CloseBracketToken */;
412
+ case 58 /* CharacterCodes.colon */:
413
+ pos++;
414
+ return token = 6 /* SyntaxKind.ColonToken */;
415
+ case 44 /* CharacterCodes.comma */:
416
+ pos++;
417
+ return token = 5 /* SyntaxKind.CommaToken */;
418
+ // strings
419
+ case 34 /* CharacterCodes.doubleQuote */:
420
+ pos++;
421
+ value = scanString();
422
+ return token = 10 /* SyntaxKind.StringLiteral */;
423
+ // comments
424
+ case 47 /* CharacterCodes.slash */: {
425
+ const start = pos - 1;
426
+ // Single-line comment
427
+ if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {
428
+ pos += 2;
429
+ while (pos < len) {
430
+ if (isLineBreak(text.charCodeAt(pos))) {
431
+ break;
432
+ }
433
+ pos++;
434
+ }
435
+ value = text.substring(start, pos);
436
+ return token = 12 /* SyntaxKind.LineCommentTrivia */;
437
+ }
438
+ // Multi-line comment
439
+ if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {
440
+ pos += 2;
441
+ const safeLength = len - 1; // For lookahead.
442
+ let commentClosed = false;
443
+ while (pos < safeLength) {
444
+ const ch = text.charCodeAt(pos);
445
+ if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {
446
+ pos += 2;
447
+ commentClosed = true;
448
+ break;
449
+ }
450
+ pos++;
451
+ }
452
+ if (!commentClosed) {
453
+ pos++;
454
+ scanError = 1 /* ScanError.UnexpectedEndOfComment */;
455
+ }
456
+ value = text.substring(start, pos);
457
+ return token = 13 /* SyntaxKind.BlockCommentTrivia */;
458
+ }
459
+ // just a single slash
460
+ value += String.fromCharCode(code);
461
+ pos++;
462
+ return token = 16 /* SyntaxKind.Unknown */;
463
+ }
464
+ // numbers
465
+ case 45 /* CharacterCodes.minus */:
466
+ value += String.fromCharCode(code);
467
+ pos++;
468
+ if (pos === len || !isDigit(text.charCodeAt(pos))) {
469
+ return token = 16 /* SyntaxKind.Unknown */;
470
+ }
471
+ // found a minus, followed by a number so
472
+ // we fall through to proceed with scanning
473
+ // numbers
474
+ case 48 /* CharacterCodes._0 */:
475
+ case 49 /* CharacterCodes._1 */:
476
+ case 50 /* CharacterCodes._2 */:
477
+ case 51 /* CharacterCodes._3 */:
478
+ case 52 /* CharacterCodes._4 */:
479
+ case 53 /* CharacterCodes._5 */:
480
+ case 54 /* CharacterCodes._6 */:
481
+ case 55 /* CharacterCodes._7 */:
482
+ case 56 /* CharacterCodes._8 */:
483
+ case 57 /* CharacterCodes._9 */:
484
+ value += scanNumber();
485
+ return token = 11 /* SyntaxKind.NumericLiteral */;
486
+ // literals and unknown symbols
487
+ default:
488
+ // is a literal? Read the full word.
489
+ while (pos < len && isUnknownContentCharacter(code)) {
490
+ pos++;
491
+ code = text.charCodeAt(pos);
492
+ }
493
+ if (tokenOffset !== pos) {
494
+ value = text.substring(tokenOffset, pos);
495
+ // keywords: true, false, null
496
+ switch (value) {
497
+ case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;
498
+ case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;
499
+ case 'null': return token = 7 /* SyntaxKind.NullKeyword */;
500
+ }
501
+ return token = 16 /* SyntaxKind.Unknown */;
502
+ }
503
+ // some
504
+ value += String.fromCharCode(code);
505
+ pos++;
506
+ return token = 16 /* SyntaxKind.Unknown */;
507
+ }
508
+ }
509
+ function isUnknownContentCharacter(code) {
510
+ if (isWhitespace(code) || isLineBreak(code)) {
511
+ return false;
512
+ }
513
+ switch (code) {
514
+ case 125 /* CharacterCodes.closeBrace */:
515
+ case 93 /* CharacterCodes.closeBracket */:
516
+ case 123 /* CharacterCodes.openBrace */:
517
+ case 91 /* CharacterCodes.openBracket */:
518
+ case 34 /* CharacterCodes.doubleQuote */:
519
+ case 58 /* CharacterCodes.colon */:
520
+ case 44 /* CharacterCodes.comma */:
521
+ case 47 /* CharacterCodes.slash */:
522
+ return false;
523
+ }
524
+ return true;
525
+ }
526
+ function scanNextNonTrivia() {
527
+ let result;
528
+ do {
529
+ result = scanNext();
530
+ } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);
531
+ return result;
532
+ }
533
+ return {
534
+ setPosition: setPosition,
535
+ getPosition: () => pos,
536
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
537
+ getToken: () => token,
538
+ getTokenValue: () => value,
539
+ getTokenOffset: () => tokenOffset,
540
+ getTokenLength: () => pos - tokenOffset,
541
+ getTokenError: () => scanError
542
+ };
543
+ }
544
+ function isWhitespace(ch) {
545
+ return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */ || ch === 11 /* CharacterCodes.verticalTab */ || ch === 12 /* CharacterCodes.formFeed */ ||
546
+ ch === 160 /* CharacterCodes.nonBreakingSpace */ || ch === 5760 /* CharacterCodes.ogham */ || ch >= 8192 /* CharacterCodes.enQuad */ && ch <= 8203 /* CharacterCodes.zeroWidthSpace */ ||
547
+ ch === 8239 /* CharacterCodes.narrowNoBreakSpace */ || ch === 8287 /* CharacterCodes.mathematicalSpace */ || ch === 12288 /* CharacterCodes.ideographicSpace */ || ch === 65279 /* CharacterCodes.byteOrderMark */;
548
+ }
549
+ function isLineBreak(ch) {
550
+ return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */ || ch === 8232 /* CharacterCodes.lineSeparator */ || ch === 8233 /* CharacterCodes.paragraphSeparator */;
551
+ }
552
+ function isDigit(ch) {
553
+ return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;
554
+ }
555
+ var CharacterCodes;
556
+ (function (CharacterCodes) {
557
+ CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
558
+ CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
559
+ CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
560
+ CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
561
+ CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
562
+ CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
563
+ // REVIEW: do we need to support this? The scanner doesn't, but our IText does. This seems
564
+ // like an odd disparity? (Or maybe it's completely fine for them to be different).
565
+ CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
566
+ // Unicode 3.0 space characters
567
+ CharacterCodes[CharacterCodes["space"] = 32] = "space";
568
+ CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
569
+ CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
570
+ CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
571
+ CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
572
+ CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
573
+ CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
574
+ CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
575
+ CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
576
+ CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
577
+ CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
578
+ CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
579
+ CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
580
+ CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
581
+ CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
582
+ CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
583
+ CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
584
+ CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
585
+ CharacterCodes[CharacterCodes["_"] = 95] = "_";
586
+ CharacterCodes[CharacterCodes["$"] = 36] = "$";
587
+ CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
588
+ CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
589
+ CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
590
+ CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
591
+ CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
592
+ CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
593
+ CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
594
+ CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
595
+ CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
596
+ CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
597
+ CharacterCodes[CharacterCodes["a"] = 97] = "a";
598
+ CharacterCodes[CharacterCodes["b"] = 98] = "b";
599
+ CharacterCodes[CharacterCodes["c"] = 99] = "c";
600
+ CharacterCodes[CharacterCodes["d"] = 100] = "d";
601
+ CharacterCodes[CharacterCodes["e"] = 101] = "e";
602
+ CharacterCodes[CharacterCodes["f"] = 102] = "f";
603
+ CharacterCodes[CharacterCodes["g"] = 103] = "g";
604
+ CharacterCodes[CharacterCodes["h"] = 104] = "h";
605
+ CharacterCodes[CharacterCodes["i"] = 105] = "i";
606
+ CharacterCodes[CharacterCodes["j"] = 106] = "j";
607
+ CharacterCodes[CharacterCodes["k"] = 107] = "k";
608
+ CharacterCodes[CharacterCodes["l"] = 108] = "l";
609
+ CharacterCodes[CharacterCodes["m"] = 109] = "m";
610
+ CharacterCodes[CharacterCodes["n"] = 110] = "n";
611
+ CharacterCodes[CharacterCodes["o"] = 111] = "o";
612
+ CharacterCodes[CharacterCodes["p"] = 112] = "p";
613
+ CharacterCodes[CharacterCodes["q"] = 113] = "q";
614
+ CharacterCodes[CharacterCodes["r"] = 114] = "r";
615
+ CharacterCodes[CharacterCodes["s"] = 115] = "s";
616
+ CharacterCodes[CharacterCodes["t"] = 116] = "t";
617
+ CharacterCodes[CharacterCodes["u"] = 117] = "u";
618
+ CharacterCodes[CharacterCodes["v"] = 118] = "v";
619
+ CharacterCodes[CharacterCodes["w"] = 119] = "w";
620
+ CharacterCodes[CharacterCodes["x"] = 120] = "x";
621
+ CharacterCodes[CharacterCodes["y"] = 121] = "y";
622
+ CharacterCodes[CharacterCodes["z"] = 122] = "z";
623
+ CharacterCodes[CharacterCodes["A"] = 65] = "A";
624
+ CharacterCodes[CharacterCodes["B"] = 66] = "B";
625
+ CharacterCodes[CharacterCodes["C"] = 67] = "C";
626
+ CharacterCodes[CharacterCodes["D"] = 68] = "D";
627
+ CharacterCodes[CharacterCodes["E"] = 69] = "E";
628
+ CharacterCodes[CharacterCodes["F"] = 70] = "F";
629
+ CharacterCodes[CharacterCodes["G"] = 71] = "G";
630
+ CharacterCodes[CharacterCodes["H"] = 72] = "H";
631
+ CharacterCodes[CharacterCodes["I"] = 73] = "I";
632
+ CharacterCodes[CharacterCodes["J"] = 74] = "J";
633
+ CharacterCodes[CharacterCodes["K"] = 75] = "K";
634
+ CharacterCodes[CharacterCodes["L"] = 76] = "L";
635
+ CharacterCodes[CharacterCodes["M"] = 77] = "M";
636
+ CharacterCodes[CharacterCodes["N"] = 78] = "N";
637
+ CharacterCodes[CharacterCodes["O"] = 79] = "O";
638
+ CharacterCodes[CharacterCodes["P"] = 80] = "P";
639
+ CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
640
+ CharacterCodes[CharacterCodes["R"] = 82] = "R";
641
+ CharacterCodes[CharacterCodes["S"] = 83] = "S";
642
+ CharacterCodes[CharacterCodes["T"] = 84] = "T";
643
+ CharacterCodes[CharacterCodes["U"] = 85] = "U";
644
+ CharacterCodes[CharacterCodes["V"] = 86] = "V";
645
+ CharacterCodes[CharacterCodes["W"] = 87] = "W";
646
+ CharacterCodes[CharacterCodes["X"] = 88] = "X";
647
+ CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
648
+ CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
649
+ CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
650
+ CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
651
+ CharacterCodes[CharacterCodes["at"] = 64] = "at";
652
+ CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
653
+ CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
654
+ CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
655
+ CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
656
+ CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
657
+ CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
658
+ CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
659
+ CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
660
+ CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
661
+ CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
662
+ CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
663
+ CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
664
+ CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
665
+ CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
666
+ CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
667
+ CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
668
+ CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
669
+ CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
670
+ CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
671
+ CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
672
+ CharacterCodes[CharacterCodes["question"] = 63] = "question";
673
+ CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
674
+ CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
675
+ CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
676
+ CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
677
+ CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
678
+ CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
679
+ CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
680
+ CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
681
+ CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
682
+ })(CharacterCodes || (CharacterCodes = {}));
683
+ /**
684
+ * 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.
685
+ * Therefore always check the errors list to find out if the input was valid.
686
+ */
687
+ function parse(text, errors = [], options = ParseOptions.DEFAULT) {
688
+ let currentProperty = null;
689
+ let currentParent = [];
690
+ const previousParents = [];
691
+ function onValue(value) {
692
+ if (Array.isArray(currentParent)) {
693
+ currentParent.push(value);
694
+ }
695
+ else if (currentProperty !== null) {
696
+ currentParent[currentProperty] = value;
697
+ }
698
+ }
699
+ const visitor = {
700
+ onObjectBegin: () => {
701
+ const object = {};
702
+ onValue(object);
703
+ previousParents.push(currentParent);
704
+ currentParent = object;
705
+ currentProperty = null;
706
+ },
707
+ onObjectProperty: (name) => {
708
+ currentProperty = name;
709
+ },
710
+ onObjectEnd: () => {
711
+ currentParent = previousParents.pop();
712
+ },
713
+ onArrayBegin: () => {
714
+ const array = [];
715
+ onValue(array);
716
+ previousParents.push(currentParent);
717
+ currentParent = array;
718
+ currentProperty = null;
719
+ },
720
+ onArrayEnd: () => {
721
+ currentParent = previousParents.pop();
722
+ },
723
+ onLiteralValue: onValue,
724
+ onError: (error, offset, length) => {
725
+ errors.push({ error, offset, length });
726
+ }
727
+ };
728
+ visit(text, visitor, options);
729
+ return currentParent[0];
730
+ }
731
+ /**
732
+ * Parses the given text and invokes the visitor functions for each object, array and literal reached.
733
+ */
734
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
735
+ const _scanner = createScanner(text, false);
736
+ function toNoArgVisit(visitFunction) {
737
+ return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
738
+ }
739
+ function toOneArgVisit(visitFunction) {
740
+ return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
741
+ }
742
+ const 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);
743
+ const disallowComments = options && options.disallowComments;
744
+ const allowTrailingComma = options && options.allowTrailingComma;
745
+ function scanNext() {
746
+ while (true) {
747
+ const token = _scanner.scan();
748
+ switch (_scanner.getTokenError()) {
749
+ case 4 /* ScanError.InvalidUnicode */:
750
+ handleError(14 /* ParseErrorCode.InvalidUnicode */);
751
+ break;
752
+ case 5 /* ScanError.InvalidEscapeCharacter */:
753
+ handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);
754
+ break;
755
+ case 3 /* ScanError.UnexpectedEndOfNumber */:
756
+ handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);
757
+ break;
758
+ case 1 /* ScanError.UnexpectedEndOfComment */:
759
+ if (!disallowComments) {
760
+ handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);
761
+ }
762
+ break;
763
+ case 2 /* ScanError.UnexpectedEndOfString */:
764
+ handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);
765
+ break;
766
+ case 6 /* ScanError.InvalidCharacter */:
767
+ handleError(16 /* ParseErrorCode.InvalidCharacter */);
768
+ break;
769
+ }
770
+ switch (token) {
771
+ case 12 /* SyntaxKind.LineCommentTrivia */:
772
+ case 13 /* SyntaxKind.BlockCommentTrivia */:
773
+ if (disallowComments) {
774
+ handleError(10 /* ParseErrorCode.InvalidCommentToken */);
775
+ }
776
+ else {
777
+ onComment();
778
+ }
779
+ break;
780
+ case 16 /* SyntaxKind.Unknown */:
781
+ handleError(1 /* ParseErrorCode.InvalidSymbol */);
782
+ break;
783
+ case 15 /* SyntaxKind.Trivia */:
784
+ case 14 /* SyntaxKind.LineBreakTrivia */:
785
+ break;
786
+ default:
787
+ return token;
788
+ }
789
+ }
790
+ }
791
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
792
+ onError(error);
793
+ if (skipUntilAfter.length + skipUntil.length > 0) {
794
+ let token = _scanner.getToken();
795
+ while (token !== 17 /* SyntaxKind.EOF */) {
796
+ if (skipUntilAfter.indexOf(token) !== -1) {
797
+ scanNext();
798
+ break;
799
+ }
800
+ else if (skipUntil.indexOf(token) !== -1) {
801
+ break;
802
+ }
803
+ token = scanNext();
804
+ }
805
+ }
806
+ }
807
+ function parseString(isValue) {
808
+ const value = _scanner.getTokenValue();
809
+ if (isValue) {
810
+ onLiteralValue(value);
811
+ }
812
+ else {
813
+ onObjectProperty(value);
814
+ }
815
+ scanNext();
816
+ return true;
817
+ }
818
+ function parseLiteral() {
819
+ switch (_scanner.getToken()) {
820
+ case 11 /* SyntaxKind.NumericLiteral */: {
821
+ let value = 0;
822
+ try {
823
+ value = JSON.parse(_scanner.getTokenValue());
824
+ if (typeof value !== 'number') {
825
+ handleError(2 /* ParseErrorCode.InvalidNumberFormat */);
826
+ value = 0;
827
+ }
828
+ }
829
+ catch (e) {
830
+ handleError(2 /* ParseErrorCode.InvalidNumberFormat */);
831
+ }
832
+ onLiteralValue(value);
833
+ break;
834
+ }
835
+ case 7 /* SyntaxKind.NullKeyword */:
836
+ onLiteralValue(null);
837
+ break;
838
+ case 8 /* SyntaxKind.TrueKeyword */:
839
+ onLiteralValue(true);
840
+ break;
841
+ case 9 /* SyntaxKind.FalseKeyword */:
842
+ onLiteralValue(false);
843
+ break;
844
+ default:
845
+ return false;
846
+ }
847
+ scanNext();
848
+ return true;
849
+ }
850
+ function parseProperty() {
851
+ if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {
852
+ handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);
853
+ return false;
854
+ }
855
+ parseString(false);
856
+ if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {
857
+ onSeparator(':');
858
+ scanNext(); // consume colon
859
+ if (!parseValue()) {
860
+ handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);
861
+ }
862
+ }
863
+ else {
864
+ handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);
865
+ }
866
+ return true;
867
+ }
868
+ function parseObject() {
869
+ onObjectBegin();
870
+ scanNext(); // consume open brace
871
+ let needsComma = false;
872
+ while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {
873
+ if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {
874
+ if (!needsComma) {
875
+ handleError(4 /* ParseErrorCode.ValueExpected */, [], []);
876
+ }
877
+ onSeparator(',');
878
+ scanNext(); // consume comma
879
+ if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {
880
+ break;
881
+ }
882
+ }
883
+ else if (needsComma) {
884
+ handleError(6 /* ParseErrorCode.CommaExpected */, [], []);
885
+ }
886
+ if (!parseProperty()) {
887
+ handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);
888
+ }
889
+ needsComma = true;
890
+ }
891
+ onObjectEnd();
892
+ if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {
893
+ handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);
894
+ }
895
+ else {
896
+ scanNext(); // consume close brace
897
+ }
898
+ return true;
899
+ }
900
+ function parseArray() {
901
+ onArrayBegin();
902
+ scanNext(); // consume open bracket
903
+ let needsComma = false;
904
+ while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {
905
+ if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {
906
+ if (!needsComma) {
907
+ handleError(4 /* ParseErrorCode.ValueExpected */, [], []);
908
+ }
909
+ onSeparator(',');
910
+ scanNext(); // consume comma
911
+ if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {
912
+ break;
913
+ }
914
+ }
915
+ else if (needsComma) {
916
+ handleError(6 /* ParseErrorCode.CommaExpected */, [], []);
917
+ }
918
+ if (!parseValue()) {
919
+ handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);
920
+ }
921
+ needsComma = true;
922
+ }
923
+ onArrayEnd();
924
+ if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {
925
+ handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);
926
+ }
927
+ else {
928
+ scanNext(); // consume close bracket
929
+ }
930
+ return true;
931
+ }
932
+ function parseValue() {
933
+ switch (_scanner.getToken()) {
934
+ case 3 /* SyntaxKind.OpenBracketToken */:
935
+ return parseArray();
936
+ case 1 /* SyntaxKind.OpenBraceToken */:
937
+ return parseObject();
938
+ case 10 /* SyntaxKind.StringLiteral */:
939
+ return parseString(true);
940
+ default:
941
+ return parseLiteral();
942
+ }
943
+ }
944
+ scanNext();
945
+ if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {
946
+ if (options.allowEmptyContent) {
947
+ return true;
948
+ }
949
+ handleError(4 /* ParseErrorCode.ValueExpected */, [], []);
950
+ return false;
951
+ }
952
+ if (!parseValue()) {
953
+ handleError(4 /* ParseErrorCode.ValueExpected */, [], []);
954
+ return false;
955
+ }
956
+ if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {
957
+ handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);
958
+ }
959
+ return true;
960
+ }
961
+
962
+ /*---------------------------------------------------------------------------------------------
963
+ * Copyright (c) Microsoft Corporation. All rights reserved.
964
+ * Licensed under the MIT License. See License.txt in the project root for license information.
965
+ *--------------------------------------------------------------------------------------------*/
966
+ /**
967
+ * Extracted from json.ts to keep json nls free.
968
+ */
969
+ function getParseErrorMessage(errorCode) {
970
+ switch (errorCode) {
971
+ case 1 /* ParseErrorCode.InvalidSymbol */: return localize('error.invalidSymbol', 'Invalid symbol');
972
+ case 2 /* ParseErrorCode.InvalidNumberFormat */: return localize('error.invalidNumberFormat', 'Invalid number format');
973
+ case 3 /* ParseErrorCode.PropertyNameExpected */: return localize('error.propertyNameExpected', 'Property name expected');
974
+ case 4 /* ParseErrorCode.ValueExpected */: return localize('error.valueExpected', 'Value expected');
975
+ case 5 /* ParseErrorCode.ColonExpected */: return localize('error.colonExpected', 'Colon expected');
976
+ case 6 /* ParseErrorCode.CommaExpected */: return localize('error.commaExpected', 'Comma expected');
977
+ case 7 /* ParseErrorCode.CloseBraceExpected */: return localize('error.closeBraceExpected', 'Closing brace expected');
978
+ case 8 /* ParseErrorCode.CloseBracketExpected */: return localize('error.closeBracketExpected', 'Closing bracket expected');
979
+ case 9 /* ParseErrorCode.EndOfFileExpected */: return localize('error.endOfFileExpected', 'End of file expected');
980
+ default:
981
+ return '';
982
+ }
983
+ }
984
+
985
+ function getDefaultExportFromCjs (x) {
986
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
987
+ }
988
+
989
+ var embeddedRegexp = /^data:(.*?),(.*?)/;
990
+ var commentRegexp = /\/\*([\s\S]*?)\*\//g;
991
+ var urlsRegexp = /(?:@import\s+)?url\s*\(\s*(("(.*?)")|('(.*?)')|(.*?))\s*\)|(?:@import\s+)(("(.*?)")|('(.*?)')|(.*?))[\s;]/ig;
992
+
993
+ function isEmbedded (src) {
994
+ return embeddedRegexp.test(src.trim());
995
+ }
996
+
997
+ function getUrls (text) {
998
+ var urls = [];
999
+ var urlMatch, url;
1000
+
1001
+ text = text.replace(commentRegexp, '');
1002
+
1003
+ while ((urlMatch = urlsRegexp.exec(text))) {
1004
+ // Match 3, 5, 6 group if '[@import] url(path)', match 9, 11, 12 group if '@import path'
1005
+ url = urlMatch[3] || urlMatch[5] || urlMatch[6] || urlMatch[9] || urlMatch[11] || urlMatch[12];
1006
+
1007
+ if (url && !isEmbedded(url) && urls.indexOf(url) === -1) {
1008
+ urls.push(url);
1009
+ }
1010
+ }
1011
+
1012
+ return urls;
1013
+ }
1014
+
1015
+ var cssParser = getUrls;
1016
+
1017
+ var parseCssUrls = cssParser;
1018
+ var cssUrlParser = parseCssUrls;
1019
+
1020
+ var parseCssUrl = /*@__PURE__*/getDefaultExportFromCjs(cssUrlParser);
1021
+
1022
+ function extractCommandResources(command) {
1023
+ if (Array.isArray(command)) {
1024
+ return command.flatMap(extractCommandResources);
1025
+ }
1026
+ if (command.icon != null) {
1027
+ if (typeof command.icon === 'object') {
1028
+ return [{ path: command.icon.light }, { path: command.icon.dark }];
1029
+ }
1030
+ else {
1031
+ return [{ path: command.icon }];
1032
+ }
1033
+ }
1034
+ return [];
1035
+ }
1036
+ function extractGrammarResources(grammar) {
1037
+ return [{ path: grammar.path }];
1038
+ }
1039
+ function extractLanguageResources(language) {
1040
+ const resources = [];
1041
+ if (language.icon != null) {
1042
+ resources.push({ path: language.icon.dark }, { path: language.icon.light });
1043
+ }
1044
+ if (language.configuration != null) {
1045
+ resources.push({ path: language.configuration, mimeType: 'application/json' });
1046
+ }
1047
+ return resources;
1048
+ }
1049
+ function extractSnippetsResources(snippet) {
1050
+ return [{ path: snippet.path, mimeType: 'application/json' }];
1051
+ }
1052
+ async function extractThemeResources(theme, getFileContent) {
1053
+ const themeContent = await getFileContent(theme.path);
1054
+ const themeDocument = parseJson(theme.path, themeContent.toString('utf8'));
1055
+ const paths = [{ path: theme.path, mimeType: 'application/json' }];
1056
+ if (themeDocument.fonts != null) {
1057
+ for (const font of themeDocument.fonts) {
1058
+ for (const src of font.src) {
1059
+ paths.push({ path: path.join(path.dirname(theme.path), src.path) });
1060
+ }
1061
+ }
1062
+ }
1063
+ if (themeDocument.iconDefinitions != null) {
1064
+ for (const iconDefinition of Object.values(themeDocument.iconDefinitions)) {
1065
+ if (iconDefinition.iconPath != null) {
1066
+ paths.push({ path: path.join(path.dirname(theme.path), iconDefinition.iconPath) });
1067
+ }
1068
+ }
1069
+ }
1070
+ return paths;
1071
+ }
1072
+ function extractJsonValidationResources(jsonValidation) {
1073
+ if (jsonValidation.url.startsWith('./')) {
1074
+ return [{ path: jsonValidation.url }];
1075
+ }
1076
+ return [];
1077
+ }
1078
+ function extractViewsContainerResources(viewContainers) {
1079
+ return Object.values(viewContainers).flatMap(containers => containers.map(container => ({ path: container.icon })));
1080
+ }
1081
+ async function extractResourcesFromExtensionManifestContribute(contribute, getFileContent) {
1082
+ const resources = [];
1083
+ if (contribute.commands != null)
1084
+ resources.push(...extractCommandResources(contribute.commands));
1085
+ if (contribute.grammars != null)
1086
+ resources.push(...contribute.grammars.flatMap(extractGrammarResources));
1087
+ if (contribute.languages != null)
1088
+ resources.push(...contribute.languages.flatMap(extractLanguageResources));
1089
+ if (contribute.snippets != null)
1090
+ resources.push(...contribute.snippets.flatMap(extractSnippetsResources));
1091
+ if (contribute.themes != null)
1092
+ resources.push(...((await Promise.all(contribute.themes.map(theme => extractThemeResources(theme, getFileContent), getFileContent))).flat()));
1093
+ if (contribute.iconThemes != null)
1094
+ resources.push(...((await Promise.all(contribute.iconThemes.map(theme => extractThemeResources(theme, getFileContent), getFileContent))).flat()));
1095
+ if (contribute.productIconThemes != null)
1096
+ resources.push(...((await Promise.all(contribute.productIconThemes.map(theme => extractThemeResources(theme, getFileContent), getFileContent))).flat()));
1097
+ if (contribute.jsonValidation != null)
1098
+ resources.push(...contribute.jsonValidation.flatMap(extractJsonValidationResources));
1099
+ if (contribute.viewsContainers != null)
1100
+ resources.push(...extractViewsContainerResources(contribute.viewsContainers));
1101
+ if (contribute['markdown.previewStyles'] != null) {
1102
+ resources.push(...(await Promise.all(contribute['markdown.previewStyles'].map(async (path) => [
1103
+ { path, mimeType: 'text/css' },
1104
+ ...(await extractResources(path, getFileContent))
1105
+ ]))).flat());
1106
+ }
1107
+ if (contribute['markdown.previewScripts'] != null) {
1108
+ resources.push(...(await Promise.all(contribute['markdown.previewScripts'].map(async (path) => [
1109
+ { path, mimeType: 'text/javascript' },
1110
+ ...(await extractResources(path, getFileContent))
1111
+ ]))).flat());
1112
+ }
1113
+ return resources.filter((resource, index, list) => !resource.path.startsWith('$(') && !list.slice(0, index).some(o => o === resource));
1114
+ }
1115
+ async function extractResourcesFromExtensionManifest(manifest, getFileContent) {
1116
+ let resources = [];
1117
+ if (manifest.contributes != null) {
1118
+ resources.push(...await extractResourcesFromExtensionManifestContribute(manifest.contributes, getFileContent));
1119
+ }
1120
+ if (manifest.browser != null) {
1121
+ const jsPath = addExtension(manifest.browser, '.js');
1122
+ resources.push({ path: manifest.browser, mimeType: 'text/javascript', realPath: jsPath });
1123
+ resources.push(...(await extractResources(jsPath, getFileContent)));
1124
+ }
1125
+ if (manifest.main != null) {
1126
+ const jsPath = addExtension(manifest.main, '.js');
1127
+ resources.push({ path: manifest.main, mimeType: 'text/javascript', realPath: jsPath });
1128
+ resources.push(...(await extractResources(jsPath, getFileContent)));
1129
+ }
1130
+ resources = resources.map(r => {
1131
+ if (r.mimeType == null) {
1132
+ const detectedType = mime.lookup(r.path);
1133
+ if (detectedType !== false) {
1134
+ return {
1135
+ ...r,
1136
+ mimeType: detectedType
1137
+ };
1138
+ }
1139
+ }
1140
+ return r;
1141
+ });
1142
+ // remove duplicates
1143
+ return Object.values(Object.fromEntries(resources.map(r => [r.path, r])));
1144
+ }
1145
+ async function extractResources(resourcePath, getFileContent) {
1146
+ const resources = [];
1147
+ const content = (await getFileContent(resourcePath)).toString('utf-8');
1148
+ if (resourcePath.endsWith('.js')) {
1149
+ for (const match of content.matchAll(/\/\/# sourceMappingURL=(.*)$/g)) {
1150
+ resources.push({ path: path.join(path.dirname(resourcePath), match[1]) });
1151
+ }
1152
+ for (const match of content.matchAll(/Uri\.joinPath\(context\.extensionUri, '([^']+)'\)/g)) {
1153
+ resources.push({ path: match[1] });
1154
+ resources.push(...(await extractResources(match[1], getFileContent)));
1155
+ }
1156
+ for (const match of content.matchAll(/this.extensionResource\('media', '(.*)'\)/g)) {
1157
+ resources.push({ path: `./media/${match[1]}` });
1158
+ resources.push(...(await extractResources(`./media/${match[1]}`, getFileContent)));
1159
+ }
1160
+ for (const match of content.matchAll(/this\._extensionResourcePath\(resourceProvider, '(.*)'\)/g)) {
1161
+ resources.push({ path: `./media/${match[1]}` });
1162
+ resources.push(...(await extractResources(`./media/${match[1]}`, getFileContent)));
1163
+ }
1164
+ for (const match of content.matchAll(/this\.extensionResourceUrl\('media', '(.*)'\)/g)) {
1165
+ resources.push({ path: `./media/${match[1]}` });
1166
+ resources.push(...(await extractResources(`./media/${match[1]}`, getFileContent)));
1167
+ }
1168
+ }
1169
+ if (resourcePath.endsWith('.css')) {
1170
+ const urls = parseCssUrl(content);
1171
+ for (const url of urls) {
1172
+ const assetPath = './' + path.join(path.dirname(resourcePath), url);
1173
+ try {
1174
+ await getFileContent(assetPath);
1175
+ resources.push({ path: assetPath });
1176
+ }
1177
+ catch (err) {
1178
+ // ignore, the file doesn't exist
1179
+ // It happens for the markdown-math extension without consequences
1180
+ }
1181
+ }
1182
+ }
1183
+ return resources;
1184
+ }
1185
+ function parseJson(path, text) {
1186
+ const errors = [];
1187
+ const result = parse(text, errors);
1188
+ if (errors.length > 0) {
1189
+ throw new Error(`Failed to parse ${path}:\n${errors.map(error => ` ${getParseErrorMessage(error.error)}`).join('\n')}`);
1190
+ }
1191
+ return result;
1192
+ }
1193
+
1194
+ function read(stream) {
1195
+ const bufs = [];
1196
+ return new Promise((resolve) => {
1197
+ stream.on('data', function (d) {
1198
+ bufs.push(d);
1199
+ });
1200
+ stream.on('end', function () {
1201
+ resolve(Buffer.concat(bufs));
1202
+ });
1203
+ });
1204
+ }
1205
+ async function readVsix(file) {
1206
+ return new Promise((resolve) => {
1207
+ const files = {};
1208
+ yauzl.open(file, { lazyEntries: true }, (err, zipfile) => {
1209
+ if (err != null)
1210
+ throw err;
1211
+ zipfile.readEntry();
1212
+ zipfile.on('entry', function (entry) {
1213
+ if (/\/$/.test(entry.fileName) || !entry.fileName.startsWith('extension/')) {
1214
+ zipfile.readEntry();
1215
+ }
1216
+ else {
1217
+ zipfile.openReadStream(entry, async function (err, readStream) {
1218
+ if (err != null)
1219
+ throw err;
1220
+ readStream.on('end', function () {
1221
+ zipfile.readEntry();
1222
+ });
1223
+ files[entry.fileName.slice('extension/'.length)] = await read(readStream);
1224
+ });
1225
+ }
1226
+ });
1227
+ zipfile.on('end', function () {
1228
+ resolve(files);
1229
+ });
1230
+ });
1231
+ });
1232
+ }
1233
+ function getVsixPath(file) {
1234
+ return path.relative('/', path.resolve('/', file));
1235
+ }
1236
+ function plugin({ include = '**/*.vsix', exclude, transformManifest = manifest => manifest, getAdditionalResources = () => Promise.resolve([]) } = {}) {
1237
+ const filter = createFilter(include, exclude);
1238
+ return {
1239
+ name: 'vsix-loader',
1240
+ resolveId(source) {
1241
+ if (filter(source)) {
1242
+ return source;
1243
+ }
1244
+ if (source.startsWith('vsix:')) {
1245
+ return source;
1246
+ }
1247
+ return undefined;
1248
+ },
1249
+ async load(id) {
1250
+ if (!filter(id))
1251
+ return null;
1252
+ const files = await readVsix(id);
1253
+ const manifest = transformManifest(parseJson(id, files['package.json'].toString('utf8')));
1254
+ const extensionResources = (await extractResourcesFromExtensionManifest(manifest, async (path) => {
1255
+ return files[getVsixPath(path)];
1256
+ })).filter(resource => getVsixPath(resource.realPath ?? resource.path) in files);
1257
+ const vsixFile = Object.fromEntries(Object.entries(files).map(([key, value]) => [getVsixPath(key), value]));
1258
+ const resources = [
1259
+ ...extensionResources,
1260
+ ...await getAdditionalResources(manifest)
1261
+ ];
1262
+ const pathMapping = (await Promise.all(resources.map(async (resource) => {
1263
+ const assetPath = getVsixPath(resource.realPath ?? resource.path);
1264
+ let url;
1265
+ if (process.env.NODE_ENV === 'development') {
1266
+ url = `'data:text/javascript;base64,${vsixFile[assetPath].toString('base64')}'`;
1267
+ }
1268
+ else {
1269
+ url = 'import.meta.ROLLUP_FILE_URL_' + this.emitFile({
1270
+ type: 'asset',
1271
+ name: `${path.basename(id)}/${path.basename(assetPath)}`,
1272
+ source: vsixFile[assetPath]
1273
+ });
1274
+ }
1275
+ return [{
1276
+ pathInExtension: getVsixPath(resource.path),
1277
+ url,
1278
+ mimeType: resource.mimeType
1279
+ }, ...(resource.realPath != null
1280
+ ? [{
1281
+ pathInExtension: getVsixPath(resource.realPath),
1282
+ url,
1283
+ mimeType: resource.mimeType
1284
+ }]
1285
+ : [])];
1286
+ }))).flat();
1287
+ let packageJson = parseJson(id, vsixFile['package.json'].toString('utf8'));
1288
+ if ('package.nls.json' in vsixFile) {
1289
+ packageJson = localizeManifest(packageJson, parseJson(id, vsixFile['package.nls.json'].toString()));
1290
+ }
1291
+ return `
1292
+ import { registerExtension } from 'vscode/extensions'
1293
+
1294
+ const manifest = ${JSON.stringify(transformManifest(packageJson))}
1295
+
1296
+ const { registerFileUrl } = registerExtension(manifest)
1297
+
1298
+ ${pathMapping.map(({ pathInExtension, url, mimeType }) => (`
1299
+ registerFileUrl('${pathInExtension}', ${url}${mimeType != null ? `, '${mimeType}'` : ''})`)).join('\n')}
1300
+ `;
1301
+ }
1302
+ };
1303
+ }
1304
+
1305
+ export { plugin as default };