@lvce-editor/extension-host-worker 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,13 +4,13 @@ const Function = 3;
4
4
  const Variable = 4;
5
5
  const Keyword = 5;
6
6
  const Folder = 6;
7
- const File$2 = 7;
7
+ const File$1 = 7;
8
8
  const Field = 8;
9
9
 
10
10
  const EditorCompletionType = {
11
11
  __proto__: null,
12
12
  Field,
13
- File: File$2,
13
+ File: File$1,
14
14
  Folder,
15
15
  Function,
16
16
  Keyword,
@@ -36,9 +36,6 @@ let AssertionError$1 = class AssertionError extends Error {
36
36
  this.name = 'AssertionError';
37
37
  }
38
38
  };
39
-
40
- // TODO consider using an assertion library like https://github.com/alexreardon/tiny-invariant, https://github.com/tj/better-assert
41
-
42
39
  const getType$3 = value => {
43
40
  switch (typeof value) {
44
41
  case 'number':
@@ -67,18 +64,6 @@ const object = value => {
67
64
  throw new AssertionError$1('expected value to be of type object');
68
65
  }
69
66
  };
70
- const number$1 = value => {
71
- const type = getType$3(value);
72
- if (type !== 'number') {
73
- throw new AssertionError$1('expected value to be of type number');
74
- }
75
- };
76
- const array = value => {
77
- const type = getType$3(value);
78
- if (type !== 'array') {
79
- throw new AssertionError$1('expected value to be of type array');
80
- }
81
- };
82
67
  const string = value => {
83
68
  const type = getType$3(value);
84
69
  if (type !== 'string') {
@@ -92,7 +77,7 @@ const fn = value => {
92
77
  }
93
78
  };
94
79
 
95
- const state$b = {
80
+ const state$a = {
96
81
  /** @type{any[]} */
97
82
  onDidOpenEditorListeners: [],
98
83
  /** @type{any[]} */
@@ -103,226 +88,18 @@ const state$b = {
103
88
  onDidSaveTextDocumentListeners: [],
104
89
  textDocuments: Object.create(null)
105
90
  };
106
- const setDocument = (textDocumentId, textDocument) => {
107
- state$b.textDocuments[textDocumentId] = textDocument;
108
- };
109
- const getDidOpenListeners = () => {
110
- return state$b.onDidSaveTextDocumentListeners;
111
- };
112
- const getWillChangeListeners = () => {
113
- return state$b.onWillChangeEditorListeners;
114
- };
115
- const getDidChangeListeners = () => {
116
- return state$b.onDidChangeTextDocumentListeners;
117
- };
118
91
  const getDocument = textDocumentId => {
119
- return state$b.textDocuments[textDocumentId];
120
- };
121
-
122
- const getOffset$1 = (textDocument, position) => {
123
- let offset = 0;
124
- let rowIndex = 0;
125
- while (rowIndex++ < position.rowIndex) {
126
- const newLineIndex = textDocument.text.indexOf('\n', offset);
127
- offset = newLineIndex + 1;
128
- }
129
- offset += position.columnIndex;
130
- return offset;
92
+ return state$a.textDocuments[textDocumentId];
131
93
  };
132
94
 
133
- // const toOffsetBasedEdit = (textDocument, documentEdit) => {
134
- // switch (documentEdit.type) {
135
- // case /* singleLineEdit */ 1: {
136
- // const offset = getOffset(textDocument, documentEdit)
137
- // return {
138
- // offset,
139
- // inserted: documentEdit.inserted,
140
- // deleted: documentEdit.deleted,
141
- // // type: /* singleLineEdit */ 1
142
- // }
143
- // }
144
- // case /* splice */ 2:
145
- // const offset = getOffset(textDocument, {
146
- // rowIndex: documentEdit.rowIndex,
147
- // columnIndex: textDocument.lines[documentEdit.rowIndex - 1].length,
148
- // })
149
- // const inserted = '\n' + documentEdit.newLines.join('\n')
150
- // return {
151
- // offset,
152
- // inserted,
153
- // deleted: 0 /* TODO */,
154
- // }
155
- // }
156
- // }
157
-
158
- // TODO incremental edits, don't send full text
159
- // export const applyEdit = (id, text, edits) => {
160
- // const textDocument = get(id)
161
- // textDocument.lines = text.split('\n')
162
- // const offsetBasedEdits = edits.map((edit) =>
163
- // toOffsetBasedEdit(textDocument, edit)
164
- // )
165
- // for (const listener of state.onDidChangeTextDocumentListeners) {
166
- // // TODO avoid extra object allocation
167
- // listener(textDocument, offsetBasedEdits)
168
- // }
169
- // }
170
-
171
- // TODO data oriented vs object oriented
172
- // data -> simpler, exposes internals, sometimes weird/long (vscode.TextDocument.getText(textDocument))
173
- // object oriented -> hides internals, banana problem (textDocument.getText())
174
-
175
- // TODO send to shared process, which sends it to renderer worker
176
- // renderer worker sends back the edit
177
- // export const applyEdit2 = (textDocument, edit) => {
178
- // if (VALIDATION_ENABLED) {
179
- // assert(typeof textDocument === 'object')
180
- // assert(textDocument !== null)
181
- // assert(typeof textDocument.id === 'number')
182
- // assert(textDocument.id > 0)
183
- // assert(typeof textDocument.getText === 'function')
184
- // assert(typeof edit === 'object')
185
- // assert(typeof edit.offset === 'number')
186
- // assert(typeof edit.inserted === 'string')
187
- // assert(typeof edit.deleted === 'number')
188
- // }
189
-
190
- // let rowIndex = 0
191
- // let offset = 0
192
- // const lines = textDocument.getText().split('\n')
193
- // while (offset < edit.offset) {
194
- // offset += lines[rowIndex++].length + 1
195
- // }
196
- // rowIndex--
197
- // offset -= lines[rowIndex].length + 1
198
- // const edit2 = {
199
- // rowIndex,
200
- // inserted: edit.inserted,
201
- // deleted: edit.deleted,
202
- // columnIndex: edit.offset - offset + edit.deleted,
203
- // type: 1,
204
- // }
205
-
206
- // // // TODO should be invoke and return boolean whether edit was applied or not
207
- // SharedProcess.send({
208
- // event: 'TextDocument.applyEdit',
209
- // args: [/* id */ textDocument.id, /* edits */ edit2],
210
- // })
211
- // }
212
-
213
- // export const create = (textDocumentId, languageId, content) => {
214
- // const textDocument = {
215
- // languageId,
216
- // lines: content.split('\n'),
217
- // }
218
- // state.textDocuments[textDocumentId] = textDocument
219
- // }
220
-
221
- // const createTextDocument = (uri, languageId, text) => {
222
- // if (VALIDATION_ENABLED) {
223
- // assert(typeof uri === 'string')
224
- // assert(typeof languageId === 'string')
225
- // assert(typeof text === 'string')
226
- // }
227
- // const state = {
228
- // /** @internal */
229
- // lines: text.split('\n'),
230
- // uri,
231
- // languageId,
232
- // getText() {
233
- // return state.lines.join('\n')
234
- // },
235
- // }
236
- // return state
237
- // }
238
-
239
- // export const sync = (documentId, languageId, text) => {
240
- // const textDocument = get(documentId)
241
- // if (!textDocument) {
242
- // console.warn(`textDocument is undefined ${languageId}`)
243
- // return
244
- // }
245
- // textDocument.languageId = languageId
246
- // textDocument.lines = text.split('\n')
247
- // // console.log('sync', JSON.stringify(text))
248
- // }
249
-
250
- const runListenerSafe = async (listener, ...args) => {
251
- try {
252
- await listener(...args);
253
- } catch (error) {
254
- // @ts-ignore
255
- if (error && error.message) {
256
- // @ts-ignore
257
- error.message = 'Failed to run open listener: ' + error.message;
258
- }
259
- console.error(error);
260
- }
261
- };
262
- const runListenersSafe = (listeners, ...args) => {
263
- for (const listener of listeners) {
264
- runListenerSafe(listener, ...args);
265
- }
266
- };
267
- const syncFull = (uri, textDocumentId, languageId, text) => {
268
- const textDocument = {
269
- uri,
270
- documentId: textDocumentId,
271
- languageId,
272
- text
273
- };
274
- setDocument(textDocumentId, textDocument);
275
- runListenersSafe(getDidOpenListeners(), textDocument);
276
- };
277
- const getSyntheticChanges = (textDocument, changes) => {
278
- // console.log({ textDocument, changes })
279
- object(textDocument);
280
- array(changes);
281
- const change = changes[0];
282
- const startOffset = getOffset$1(textDocument, change.start);
283
- const endOffset = getOffset$1(textDocument, change.end);
284
- const inserted = change.inserted.join('\n');
285
- const syntheticChanges = [{
286
- startOffset,
287
- endOffset,
288
- inserted
289
- }];
290
- return syntheticChanges;
291
- };
292
- const syncIncremental = (textDocumentId, changes) => {
293
- number$1(textDocumentId);
294
- array(changes);
295
- const textDocument = getDocument(textDocumentId);
296
- if (!textDocument) {
297
- console.warn(`sync not possible, no matching textDocument with id ${textDocumentId}`);
298
- return;
299
- }
300
- const syntheticChanges = getSyntheticChanges(textDocument, changes);
301
- runListenersSafe(getWillChangeListeners(), textDocument, syntheticChanges);
302
- const syntheticChange = syntheticChanges[0];
303
- const oldText = textDocument.text;
304
- const before = oldText.slice(0, syntheticChange.startOffset);
305
- const after = oldText.slice(syntheticChange.endOffset);
306
- textDocument.text = before + syntheticChange.inserted + after;
307
- runListenersSafe(getDidChangeListeners(), textDocument, syntheticChanges);
308
- };
309
95
  const get$3 = textDocumentId => {
310
96
  const textDocument = getDocument(textDocumentId);
311
97
  return textDocument;
312
98
  };
313
- const getText$1 = textDocument => {
99
+ const getText = textDocument => {
314
100
  return textDocument.text;
315
101
  };
316
- const setLanguageId = (textDocumentId, languageId) => {
317
- const newTextDocument = {
318
- ...getDocument(textDocumentId),
319
- languageId
320
- };
321
- setDocument(textDocumentId, newTextDocument);
322
- runListenersSafe(getDidOpenListeners(), newTextDocument);
323
- };
324
102
 
325
- const BABEL_PARSER_SYNTAX_ERROR = 'BABEL_PARSER_SYNTAX_ERROR';
326
103
  const E_COMMAND_NOT_FOUND$1 = 'E_COMMAND_NOT_FOUND';
327
104
  const E_NO_PROVIDER_FOUND = 'E_NO_PROVIDER_FOUND';
328
105
 
@@ -334,32 +111,38 @@ class NoProviderFoundError extends Error {
334
111
  }
335
112
  }
336
113
 
337
- const stringifyError = error => {
338
- const errorPrefixes = ['Error: ', 'VError: '];
339
- const stringifiedError = `${error}`;
340
- for (const errorPrefix of errorPrefixes) {
341
- if (stringifiedError.startsWith(errorPrefix)) {
342
- return stringifiedError.slice(errorPrefix.length);
343
- }
114
+ const normalizeLine$1 = line => {
115
+ if (line.startsWith('Error: ')) {
116
+ return line.slice(`Error: `.length);
344
117
  }
345
- return stringifiedError;
118
+ if (line.startsWith('VError: ')) {
119
+ return line.slice(`VError: `.length);
120
+ }
121
+ return line;
346
122
  };
347
123
  const getCombinedMessage$1 = (error, message) => {
348
- const stringifiedError = stringifyError(error);
124
+ const stringifiedError = normalizeLine$1(`${error}`);
349
125
  if (message) {
350
126
  return `${message}: ${stringifiedError}`;
351
127
  }
352
- return `${stringifiedError}`;
128
+ return stringifiedError;
129
+ };
130
+ const NewLine$3 = '\n';
131
+ const getNewLineIndex$2 = (string, startIndex = undefined) => {
132
+ return string.indexOf(NewLine$3, startIndex);
353
133
  };
354
134
  const mergeStacks$1 = (parent, child) => {
355
135
  if (!child) {
356
136
  return parent;
357
137
  }
358
- const parentNewLineIndex = parent.indexOf('\n');
359
- const childNewLineIndex = child.indexOf('\n');
138
+ const parentNewLineIndex = getNewLineIndex$2(parent);
139
+ const childNewLineIndex = getNewLineIndex$2(child);
140
+ if (childNewLineIndex === -1) {
141
+ return parent;
142
+ }
360
143
  const parentFirstLine = parent.slice(0, parentNewLineIndex);
361
144
  const childRest = child.slice(childNewLineIndex);
362
- const childFirstLine = child.slice(0, childNewLineIndex);
145
+ const childFirstLine = normalizeLine$1(child.slice(0, childNewLineIndex));
363
146
  if (parentFirstLine.includes(childFirstLine)) {
364
147
  return parentFirstLine + childRest;
365
148
  }
@@ -377,6 +160,10 @@ let VError$1 = class VError extends Error {
377
160
  // @ts-ignore
378
161
  this.codeFrame = error.codeFrame;
379
162
  }
163
+ if (error.code) {
164
+ // @ts-ignore
165
+ this.code = error.code;
166
+ }
380
167
  }
381
168
  };
382
169
 
@@ -505,17 +292,17 @@ const improveValidationError = (name, validationError) => {
505
292
  const post = improveValidationErrorPostMessage(validationError, camelCaseName);
506
293
  return pre + ': ' + post;
507
294
  };
508
- let NonError$1 = class NonError extends Error {
295
+ class NonError extends Error {
509
296
  name = 'NonError';
510
297
  constructor(message) {
511
298
  super(message);
512
299
  }
513
- };
300
+ }
514
301
 
515
302
  // ensureError based on https://github.com/sindresorhus/ensure-error/blob/main/index.ts (License MIT)
516
- const ensureError$1 = input => {
303
+ const ensureError = input => {
517
304
  if (!(input instanceof Error)) {
518
- return new NonError$1(input);
305
+ return new NonError(input);
519
306
  }
520
307
  return input;
521
308
  };
@@ -550,7 +337,7 @@ const registerMethod = ({
550
337
  }
551
338
  return result;
552
339
  } catch (error) {
553
- const actualError = ensureError$1(error);
340
+ const actualError = ensureError(error);
554
341
  const spacedOutName = spaceOut(name);
555
342
  if (actualError && actualError.message) {
556
343
  if (actualError.message === 'provider[methodName] is not a function') {
@@ -565,7 +352,7 @@ const registerMethod = ({
565
352
  }
566
353
  };
567
354
  };
568
- const create$a = ({
355
+ const create$8 = ({
569
356
  name,
570
357
  resultShape,
571
358
  executeKey = '',
@@ -609,15 +396,15 @@ const create$a = ({
609
396
 
610
397
  const Array$1 = 'array';
611
398
  const Boolean = 'boolean';
612
- const Number$1 = 'number';
399
+ const Number = 'number';
613
400
  const Object$1 = 'object';
614
- const String$1 = 'string';
401
+ const String = 'string';
615
402
 
616
403
  const {
617
404
  registerBraceCompletionProvider,
618
405
  executeBraceCompletionProvider,
619
406
  reset: reset$9
620
- } = create$a({
407
+ } = create$8({
621
408
  name: 'BraceCompletion',
622
409
  resultShape: {
623
410
  type: Boolean
@@ -627,7 +414,7 @@ const {
627
414
  const {
628
415
  registerClosingTagProvider,
629
416
  executeClosingTagProvider
630
- } = create$a({
417
+ } = create$8({
631
418
  name: 'ClosingTag',
632
419
  returnUndefinedWhenNoProviderFound: true,
633
420
  resultShape: {
@@ -639,7 +426,7 @@ const {
639
426
  const {
640
427
  registerCodeActionProvider,
641
428
  executeCodeActionProvider
642
- } = create$a({
429
+ } = create$8({
643
430
  name: 'CodeAction',
644
431
  resultShape: {
645
432
  type: Array$1,
@@ -648,28 +435,8 @@ const {
648
435
  }
649
436
  }
650
437
  });
651
- const isOrganizeImports = action => {
652
- return action.kind === 'source.organizeImports';
653
- };
654
-
655
- // TODO handle case when multiple organize imports providers are registered
656
- const executeOrganizeImports = async uid => {
657
- const actions = await executeCodeActionProvider(uid);
658
- // @ts-ignore
659
- if (!actions || actions.length === 0) {
660
- return [];
661
- }
662
- // @ts-ignore
663
- const organizeImportsAction = actions.find(isOrganizeImports);
664
- if (!organizeImportsAction) {
665
- return [];
666
- }
667
- const textDocument = get$3(uid);
668
- const edits = await organizeImportsAction.execute(textDocument);
669
- return edits;
670
- };
671
438
 
672
- const state$a = {
439
+ const state$9 = {
673
440
  commands: Object.create(null)
674
441
  };
675
442
  const getCommandDisplay = command => {
@@ -692,10 +459,10 @@ const registerCommand = command => {
692
459
  if (!command.execute) {
693
460
  throw new Error('command is missing execute function');
694
461
  }
695
- if (command.id in state$a.commands) {
462
+ if (command.id in state$9.commands) {
696
463
  throw new Error(`command cannot be registered multiple times`);
697
464
  }
698
- state$a.commands[command.id] = command;
465
+ state$9.commands[command.id] = command;
699
466
  } catch (error) {
700
467
  const commandDisplayId = getCommandDisplay(command);
701
468
  throw new VError$1(error, `Failed to register command${commandDisplayId}`);
@@ -703,7 +470,7 @@ const registerCommand = command => {
703
470
  };
704
471
  const executeCommand = async (id, ...args) => {
705
472
  try {
706
- const command = state$a.commands[id];
473
+ const command = state$9.commands[id];
707
474
  if (!command) {
708
475
  throw new Error(`command ${id} not found`);
709
476
  }
@@ -722,7 +489,7 @@ const {
722
489
  registerCompletionProvider,
723
490
  executeCompletionProvider,
724
491
  executeresolveCompletionItemProvider
725
- } = create$a({
492
+ } = create$8({
726
493
  name: 'Completion',
727
494
  resultShape: {
728
495
  type: Array$1,
@@ -742,24 +509,14 @@ const {
742
509
  }]
743
510
  });
744
511
 
745
- const state$9 = {
512
+ const state$8 = {
746
513
  configuration: Object.create(null)
747
514
  };
748
515
  const getConfiguration = key => {
749
- return state$9.configuration[key] ?? '';
750
- };
751
- const setConfigurations = preferences => {
752
- state$9.configuration = preferences;
516
+ return state$8.configuration[key] ?? '';
753
517
  };
754
518
 
755
- const Two$1 = '2.0';
756
- const create$4$1 = (method, params) => {
757
- return {
758
- jsonrpc: Two$1,
759
- method,
760
- params
761
- };
762
- };
519
+ const Two = '2.0';
763
520
  class AssertionError extends Error {
764
521
  constructor(message) {
765
522
  super(message);
@@ -806,11 +563,11 @@ const get$2 = id => {
806
563
  const remove = id => {
807
564
  delete state$1$1.callbacks[id];
808
565
  };
809
- const state$8 = {
566
+ const state$7 = {
810
567
  id: 0
811
568
  };
812
569
  const create$3$1 = () => {
813
- return ++state$8.id;
570
+ return ++state$7.id;
814
571
  };
815
572
  const warn = (...args) => {
816
573
  console.warn(...args);
@@ -857,7 +614,7 @@ const create$2$1 = (method, params) => {
857
614
  promise
858
615
  } = registerPromise();
859
616
  const message = {
860
- jsonrpc: Two$1,
617
+ jsonrpc: Two,
861
618
  method,
862
619
  params,
863
620
  id
@@ -867,12 +624,12 @@ const create$2$1 = (method, params) => {
867
624
  promise
868
625
  };
869
626
  };
870
- let JsonRpcError$1 = class JsonRpcError extends Error {
627
+ class JsonRpcError extends Error {
871
628
  constructor(message) {
872
629
  super(message);
873
630
  this.name = 'JsonRpcError';
874
631
  }
875
- };
632
+ }
876
633
  const NewLine$2 = '\n';
877
634
  const DomException = 'DOMException';
878
635
  const ReferenceError$1 = 'ReferenceError';
@@ -928,21 +685,21 @@ const getParentStack = error => {
928
685
  }
929
686
  return parentStack;
930
687
  };
931
- const joinLines$2 = lines => {
688
+ const joinLines$1 = lines => {
932
689
  return lines.join(NewLine$2);
933
690
  };
934
- const MethodNotFound$1 = -32601;
691
+ const MethodNotFound = -32601;
935
692
  const Custom = -32001;
936
- const splitLines$2 = lines => {
693
+ const splitLines$1 = lines => {
937
694
  return lines.split(NewLine$2);
938
695
  };
939
696
  const restoreJsonRpcError = error => {
940
697
  if (error && error instanceof Error) {
941
698
  return error;
942
699
  }
943
- const currentStack = joinLines$2(splitLines$2(new Error().stack || '').slice(1));
944
- if (error && error.code && error.code === MethodNotFound$1) {
945
- const restoredError = new JsonRpcError$1(error.message);
700
+ const currentStack = joinLines$1(splitLines$1(new Error().stack || '').slice(1));
701
+ if (error && error.code && error.code === MethodNotFound) {
702
+ const restoredError = new JsonRpcError(error.message);
946
703
  const parentStack = getParentStack(error);
947
704
  restoredError.stack = parentStack + NewLine$2 + currentStack;
948
705
  return restoredError;
@@ -996,7 +753,7 @@ const unwrapJsonRpcResult = responseMessage => {
996
753
  if ('result' in responseMessage) {
997
754
  return responseMessage.result;
998
755
  }
999
- throw new JsonRpcError$1('unexpected response message');
756
+ throw new JsonRpcError('unexpected response message');
1000
757
  };
1001
758
  const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
1002
759
  const getType = prettyError => {
@@ -1011,7 +768,7 @@ const getType = prettyError => {
1011
768
  const getErrorProperty = (error, prettyError) => {
1012
769
  if (error && error.code === E_COMMAND_NOT_FOUND) {
1013
770
  return {
1014
- code: MethodNotFound$1,
771
+ code: MethodNotFound,
1015
772
  message: error.message,
1016
773
  data: error.stack
1017
774
  };
@@ -1030,34 +787,34 @@ const getErrorProperty = (error, prettyError) => {
1030
787
  };
1031
788
  const create$1$1 = (message, error) => {
1032
789
  return {
1033
- jsonrpc: Two$1,
790
+ jsonrpc: Two,
1034
791
  id: message.id,
1035
792
  error
1036
793
  };
1037
794
  };
1038
- const getErrorResponse$1 = (message, error, preparePrettyError, logError) => {
795
+ const getErrorResponse = (message, error, preparePrettyError, logError) => {
1039
796
  const prettyError = preparePrettyError(error);
1040
797
  logError(error, prettyError);
1041
798
  const errorProperty = getErrorProperty(error, prettyError);
1042
799
  return create$1$1(message, errorProperty);
1043
800
  };
1044
- const create$9 = (message, result) => {
801
+ const create$7 = (message, result) => {
1045
802
  return {
1046
- jsonrpc: Two$1,
803
+ jsonrpc: Two,
1047
804
  id: message.id,
1048
805
  result: result ?? null
1049
806
  };
1050
807
  };
1051
- const getSuccessResponse$1 = (message, result) => {
808
+ const getSuccessResponse = (message, result) => {
1052
809
  const resultProperty = result ?? null;
1053
- return create$9(message, resultProperty);
810
+ return create$7(message, resultProperty);
1054
811
  };
1055
- const getResponse$1 = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
812
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
1056
813
  try {
1057
814
  const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
1058
- return getSuccessResponse$1(message, result);
815
+ return getSuccessResponse(message, result);
1059
816
  } catch (error) {
1060
- return getErrorResponse$1(message, error, preparePrettyError, logError);
817
+ return getErrorResponse(message, error, preparePrettyError, logError);
1061
818
  }
1062
819
  };
1063
820
  const defaultPreparePrettyError = error => {
@@ -1070,7 +827,7 @@ const defaultRequiresSocket = () => {
1070
827
  return false;
1071
828
  };
1072
829
  const defaultResolve = resolve;
1073
- const handleJsonRpcMessage$1 = async (...args) => {
830
+ const handleJsonRpcMessage = async (...args) => {
1074
831
  let message;
1075
832
  let ipc;
1076
833
  let execute;
@@ -1098,11 +855,11 @@ const handleJsonRpcMessage$1 = async (...args) => {
1098
855
  }
1099
856
  if ('id' in message) {
1100
857
  if ('method' in message) {
1101
- const response = await getResponse$1(message, ipc, execute, preparePrettyError, logError, requiresSocket);
858
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1102
859
  try {
1103
860
  ipc.send(response);
1104
861
  } catch (error) {
1105
- const errorResponse = getErrorResponse$1(message, error, preparePrettyError, logError);
862
+ const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
1106
863
  ipc.send(errorResponse);
1107
864
  }
1108
865
  return;
@@ -1111,14 +868,10 @@ const handleJsonRpcMessage$1 = async (...args) => {
1111
868
  return;
1112
869
  }
1113
870
  if ('method' in message) {
1114
- await getResponse$1(message, ipc, execute, preparePrettyError, logError, requiresSocket);
871
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1115
872
  return;
1116
873
  }
1117
- throw new JsonRpcError$1('unexpected message');
1118
- };
1119
- const send$1 = (transport, method, ...params) => {
1120
- const message = create$4$1(method, params);
1121
- transport.send(message);
874
+ throw new JsonRpcError('unexpected message');
1122
875
  };
1123
876
  const invoke$1 = async (ipc, method, ...params) => {
1124
877
  const {
@@ -1141,54 +894,59 @@ const invokeAndTransfer$1 = async (ipc, method, ...params) => {
1141
894
  return result;
1142
895
  };
1143
896
 
1144
- const state$7 = {
1145
- getFn() {}
1146
- };
897
+ const processName = `extension host worker`;
898
+
899
+ class CommandNotFoundError extends Error {
900
+ constructor(id) {
901
+ super(`Command "${id}" not found (${processName})`);
902
+ this.name = 'CommandNotFoundError';
903
+ // @ts-ignore
904
+ this.code = E_COMMAND_NOT_FOUND$1;
905
+ }
906
+ }
907
+
908
+ const state$6 = {};
1147
909
  const execute = (method, ...params) => {
1148
910
  // @ts-ignore
1149
- const fn = state$7.getFn(method);
911
+ const fn = state$6[method];
1150
912
  // @ts-ignore
1151
913
  if (!fn) {
1152
- throw new Error(`command not found ${method}`);
914
+ throw new CommandNotFoundError(method);
1153
915
  }
1154
916
  // @ts-ignore
1155
917
  return fn(...params);
1156
918
  };
1157
919
 
1158
- const requiresSocket = () => {
920
+ const requiresSocket$1 = () => {
1159
921
  return false;
1160
922
  };
1161
- const preparePrettyError = error => {
923
+ const preparePrettyError$1 = error => {
1162
924
  return error;
1163
925
  };
1164
926
  const logError$1 = error => {
1165
927
  // handled by renderer worker
1166
928
  };
1167
929
  const handleMessage = event => {
1168
- return handleJsonRpcMessage$1(event.target, event.data, execute, resolve, preparePrettyError, logError$1, requiresSocket);
930
+ return handleJsonRpcMessage(event.target, event.data, execute, resolve, preparePrettyError$1, logError$1, requiresSocket$1);
1169
931
  };
1170
932
 
1171
933
  const handleIpc = ipc => {
1172
934
  ipc.addEventListener('message', handleMessage);
1173
935
  };
1174
936
 
1175
- const state$6 = {
937
+ const state$5 = {
1176
938
  /**
1177
939
  * @type {any}
1178
940
  */
1179
941
  ipc: undefined
1180
942
  };
1181
943
  const get$1 = () => {
1182
- return state$6.ipc;
944
+ return state$5.ipc;
1183
945
  };
1184
946
  const set$1 = ipc => {
1185
- state$6.ipc = ipc;
947
+ state$5.ipc = ipc;
1186
948
  };
1187
949
 
1188
- const send = (method, ...params) => {
1189
- const ipc = get$1();
1190
- send$1(ipc, method, ...params);
1191
- };
1192
950
  const invoke = (method, ...params) => {
1193
951
  const ipc = get$1();
1194
952
  return invoke$1(ipc, method, ...params);
@@ -1202,146 +960,34 @@ const listen$2 = ipc => {
1202
960
  set$1(ipc);
1203
961
  };
1204
962
 
1205
- const state$5 = {
963
+ const state$4 = {
1206
964
  debugProviderMap: Object.create(null)
1207
965
  };
1208
- const getDebugProvider = id => {
1209
- const provider = state$5.debugProviderMap[id];
1210
- if (!provider) {
1211
- // @ts-ignore
1212
- throw new VError$1(`no debug provider "${id}" found`);
1213
- }
1214
- return provider;
1215
- };
1216
966
  const registerDebugProvider = debugProvider => {
1217
967
  if (!debugProvider.id) {
1218
968
  throw new Error('Failed to register debug system provider: missing id');
1219
969
  }
1220
- state$5.debugProviderMap[debugProvider.id] = debugProvider;
1221
- };
1222
- const start = async (protocol, path) => {
1223
- try {
1224
- const handlePaused = params => {
1225
- console.log('send paused', params);
1226
- send('Debug.paused', params);
1227
- };
1228
- const handleResumed = () => {
1229
- send('Debug.resumed');
1230
- };
1231
- const handleScriptParsed = parsedScript => {
1232
- send('Debug.scriptParsed', parsedScript);
1233
- };
1234
- const provider = getDebugProvider(protocol);
1235
- await provider.start({
1236
- handlePaused,
1237
- handleResumed,
1238
- handleScriptParsed
1239
- }, path);
1240
- } catch (error) {
1241
- throw new VError$1(error, 'Failed to execute debug provider');
1242
- }
1243
- };
1244
- const listProcesses = async (protocol, path) => {
1245
- try {
1246
- const provider = getDebugProvider(protocol);
1247
- const processes = await provider.listProcesses(path);
1248
- array(processes);
1249
- return processes;
1250
- } catch (error) {
1251
- throw new VError$1(error, 'Failed to execute debug provider');
1252
- }
1253
- };
1254
- const resume = async protocol => {
1255
- try {
1256
- const provider = getDebugProvider(protocol);
1257
- return await provider.resume();
1258
- } catch (error) {
1259
- throw new VError$1(error, 'Failed to execute debug provider');
1260
- }
1261
- };
1262
- const pause = async protocol => {
1263
- try {
1264
- const provider = getDebugProvider(protocol);
1265
- return await provider.pause();
1266
- } catch (error) {
1267
- throw new VError$1(error, 'Failed to execute debug provider');
1268
- }
1269
- };
1270
- const stepInto = async protocol => {
1271
- try {
1272
- const provider = getDebugProvider(protocol);
1273
- return await provider.stepInto();
1274
- } catch (error) {
1275
- throw new VError$1(error, 'Failed to execute debug provider');
1276
- }
1277
- };
1278
- const stepOut = async protocol => {
1279
- try {
1280
- const provider = getDebugProvider(protocol);
1281
- return await provider.stepOut();
1282
- } catch (error) {
1283
- throw new VError$1(error, 'Failed to execute debug provider');
1284
- }
1285
- };
1286
- const stepOver = async protocol => {
1287
- try {
1288
- const provider = getDebugProvider(protocol);
1289
- return await provider.stepOver();
1290
- } catch (error) {
1291
- throw new VError$1(error, 'Failed to execute debug provider');
1292
- }
1293
- };
1294
- const setPauseOnException = async (protocol, value) => {
1295
- try {
1296
- const provider = getDebugProvider(protocol);
1297
- return await provider.setPauseOnExceptions(value);
1298
- } catch (error) {
1299
- throw new VError$1(error, 'Failed to execute debug provider');
1300
- }
1301
- };
1302
- const getProperties = async (protocol, objectId) => {
1303
- try {
1304
- const provider = getDebugProvider(protocol);
1305
- return await provider.getProperties(objectId);
1306
- } catch (error) {
1307
- throw new VError$1(error, 'Failed to execute debug provider');
1308
- }
1309
- };
1310
- const evaluate = async (protocol, expression, callFrameId) => {
1311
- try {
1312
- const provider = getDebugProvider(protocol);
1313
- return await provider.evaluate(expression, callFrameId);
1314
- } catch (error) {
1315
- throw new VError$1(error, 'Failed to execute debug provider');
1316
- }
1317
- };
1318
- const setPauseOnExceptions = async (protocol, value) => {
1319
- try {
1320
- const provider = getDebugProvider(protocol);
1321
- return await provider.setPauseOnExceptions(value);
1322
- } catch (error) {
1323
- throw new VError$1(error, 'Failed to execute setPauseOnExceptions');
1324
- }
970
+ state$4.debugProviderMap[debugProvider.id] = debugProvider;
1325
971
  };
1326
972
 
1327
973
  const {
1328
974
  registerDefinitionProvider,
1329
975
  executeDefinitionProvider,
1330
976
  reset: reset$8
1331
- } = create$a({
977
+ } = create$8({
1332
978
  name: 'Definition',
1333
979
  resultShape: {
1334
980
  allowUndefined: true,
1335
981
  type: Object$1,
1336
982
  properties: {
1337
983
  uri: {
1338
- type: String$1
984
+ type: String
1339
985
  },
1340
986
  startOffset: {
1341
- type: Number$1
987
+ type: Number
1342
988
  },
1343
989
  endOffset: {
1344
- type: Number$1
990
+ type: Number
1345
991
  }
1346
992
  }
1347
993
  }
@@ -1350,7 +996,7 @@ const {
1350
996
  const {
1351
997
  registerDiagnosticProvider,
1352
998
  executeDiagnosticProvider
1353
- } = create$a({
999
+ } = create$8({
1354
1000
  name: 'Diagnostic',
1355
1001
  resultShape: {
1356
1002
  type: Array$1,
@@ -1372,38 +1018,14 @@ const exec = async (command, args, options) => {
1372
1018
  throw new DepecratedError(`vscode.exec is deprecated, use createNodeRpc instead`);
1373
1019
  };
1374
1020
 
1375
- const state$4 = {
1021
+ const state$3 = {
1376
1022
  fileSystemProviderMap: Object.create(null)
1377
1023
  };
1378
- const getFileSystemProvider = protocol => {
1379
- const provider = state$4.fileSystemProviderMap[protocol];
1380
- if (!provider) {
1381
- // @ts-ignore
1382
- throw new VError$1(`no file system provider for protocol "${protocol}" found`);
1383
- }
1384
- return provider;
1385
- };
1386
1024
  const registerFileSystemProvider = fileSystemProvider => {
1387
1025
  if (!fileSystemProvider.id) {
1388
1026
  throw new Error('Failed to register file system provider: missing id');
1389
1027
  }
1390
- state$4.fileSystemProviderMap[fileSystemProvider.id] = fileSystemProvider;
1391
- };
1392
- const readDirWithFileTypes = async (protocol, path) => {
1393
- try {
1394
- const provider = getFileSystemProvider(protocol);
1395
- return await provider.readDirWithFileTypes(path);
1396
- } catch (error) {
1397
- throw new VError$1(error, 'Failed to execute file system provider');
1398
- }
1399
- };
1400
- const readFile = async (protocol, path) => {
1401
- try {
1402
- const provider = getFileSystemProvider(protocol);
1403
- return await provider.readFile(path);
1404
- } catch (error) {
1405
- throw new VError$1(error, 'Failed to execute file system provider');
1406
- }
1028
+ state$3.fileSystemProviderMap[fileSystemProvider.id] = fileSystemProvider;
1407
1029
  };
1408
1030
  const readFileExternal = async path => {
1409
1031
  // TODO when file is local,
@@ -1415,101 +1037,16 @@ const readFileExternal = async path => {
1415
1037
  const content = await invoke('FileSystem.readFile', path);
1416
1038
  return content;
1417
1039
  };
1418
- const writeFile = async (protocol, uri, content) => {
1419
- try {
1420
- const provider = getFileSystemProvider(protocol);
1421
- return await provider.writeFile(uri, content);
1422
- } catch (error) {
1423
- throw new VError$1(error, 'Failed to execute file system provider');
1424
- }
1425
- };
1426
- const getPathSeparator = protocol => {
1427
- try {
1428
- const provider = getFileSystemProvider(protocol);
1429
- return provider.pathSeparator;
1430
- } catch (error) {
1431
- throw new VError$1(error, 'Failed to execute file system provider');
1432
- }
1433
- };
1434
1040
 
1435
1041
  const webViews = Object.create(null);
1436
1042
  const webViewProviders = Object.create(null);
1437
- const getProvider = providerId => {
1438
- return webViewProviders[providerId];
1439
- };
1440
1043
  const setProvider = (providerId, provider) => {
1441
1044
  webViewProviders[providerId] = provider;
1442
1045
  };
1443
1046
  const getWebView = id => {
1444
1047
  return webViews[id];
1445
1048
  };
1446
- const setWebView = (id, webView) => {
1447
- webViews[id] = webView;
1448
- };
1449
-
1450
- // TODO pass uuid to allow having multiple webviews open at the same time
1451
- const createWebView = async (providerId, port, uri, uid, origin) => {
1452
- const provider = getProvider(providerId);
1453
- if (!provider) {
1454
- throw new Error(`webview provider ${providerId} not found`);
1455
- }
1456
-
1457
- // TODO cancel promise when webview is disposed before sending message
1458
- // TODO handle case when webview doesn't send ready message
1459
- // TODO handle error
1460
- await new Promise(resolve => {
1461
- port.onmessage = resolve;
1462
- });
1463
1049
 
1464
- // TODO use ipc module
1465
- const handlePortMessage = async event => {
1466
- const {
1467
- data,
1468
- target
1469
- } = event;
1470
- const {
1471
- method,
1472
- params,
1473
- id
1474
- } = data;
1475
- if (provider && provider.commands && provider.commands[method]) {
1476
- const fn = provider.commands[method];
1477
- const result = await fn(...params);
1478
- if (id) {
1479
- target.postMessage({
1480
- jsonrpc: '2.0',
1481
- id,
1482
- result
1483
- });
1484
- }
1485
- }
1486
- };
1487
- port.onmessage = handlePortMessage;
1488
- const rpc = {
1489
- uri,
1490
- provider,
1491
- uid,
1492
- origin,
1493
- invoke(method, ...params) {
1494
- // TODO return promise with result
1495
- port.postMessage({
1496
- jsonrpc: '2.0',
1497
- method,
1498
- params
1499
- });
1500
- }
1501
- };
1502
- // TODO allow creating multiple webviews per provider
1503
- setWebView(providerId, rpc);
1504
- };
1505
- const load = async providerId => {
1506
- const rpc = getWebView(providerId);
1507
- await rpc.provider.create(rpc, rpc.uri);
1508
- };
1509
- const disposeWebView = id => {
1510
- // TODO race condition
1511
- // const webView=webViews[id]
1512
- };
1513
1050
  const registerWebViewProvider = provider => {
1514
1051
  setProvider(provider.id, provider);
1515
1052
  };
@@ -1518,7 +1055,7 @@ const {
1518
1055
  registerFormattingProvider,
1519
1056
  executeFormattingProvider,
1520
1057
  reset: reset$7
1521
- } = create$a({
1058
+ } = create$8({
1522
1059
  name: 'Formatting',
1523
1060
  executeKey: 'format',
1524
1061
  resultShape: {
@@ -1528,13 +1065,13 @@ const {
1528
1065
  type: Object$1,
1529
1066
  properties: {
1530
1067
  startOffset: {
1531
- type: Number$1
1068
+ type: Number
1532
1069
  },
1533
1070
  endOffset: {
1534
- type: Number$1
1071
+ type: Number
1535
1072
  },
1536
1073
  inserted: {
1537
- type: String$1
1074
+ type: String
1538
1075
  }
1539
1076
  }
1540
1077
  }
@@ -1580,7 +1117,7 @@ const {
1580
1117
  registerHoverProvider,
1581
1118
  executeHoverProvider,
1582
1119
  reset: reset$6
1583
- } = create$a({
1120
+ } = create$8({
1584
1121
  name: 'Hover',
1585
1122
  resultShape: {
1586
1123
  allowUndefined: true,
@@ -1593,7 +1130,7 @@ const {
1593
1130
  registerImplementationProvider,
1594
1131
  executeImplementationProvider,
1595
1132
  reset: reset$5
1596
- } = create$a({
1133
+ } = create$8({
1597
1134
  name: 'Implementation',
1598
1135
  resultShape: {
1599
1136
  type: Array$1,
@@ -1620,7 +1157,7 @@ const getModule$3 = method => {
1620
1157
  }
1621
1158
  };
1622
1159
 
1623
- const create$8 = async ({
1160
+ const create$6 = async ({
1624
1161
  method,
1625
1162
  ...options
1626
1163
  }) => {
@@ -1647,7 +1184,7 @@ const getModule$2 = method => {
1647
1184
  }
1648
1185
  };
1649
1186
 
1650
- const create$7 = async ({
1187
+ const create$5 = async ({
1651
1188
  method,
1652
1189
  ...options
1653
1190
  }) => {
@@ -1668,12 +1205,12 @@ const createNodeRpc = async ({
1668
1205
  try {
1669
1206
  string(path);
1670
1207
  fn(execute);
1671
- const ipc = await create$8({
1208
+ const ipc = await create$6({
1672
1209
  method: ElectronMessagePort,
1673
1210
  type: 'extension-host-helper-process',
1674
1211
  name
1675
1212
  });
1676
- const rpc = await create$7({
1213
+ const rpc = await create$5({
1677
1214
  ipc,
1678
1215
  method: JsonRpc,
1679
1216
  execute
@@ -1707,7 +1244,7 @@ const {
1707
1244
  executeReferenceProvider,
1708
1245
  executefileReferenceProvider,
1709
1246
  reset: reset$4
1710
- } = create$a({
1247
+ } = create$8({
1711
1248
  name: 'Reference',
1712
1249
  resultShape: {
1713
1250
  type: Array$1,
@@ -1734,7 +1271,7 @@ const {
1734
1271
  executeRenameProvider,
1735
1272
  executeprepareRenameProvider,
1736
1273
  reset: reset$3
1737
- } = create$a({
1274
+ } = create$8({
1738
1275
  name: 'Rename',
1739
1276
  resultShape: {
1740
1277
  type: Object$1,
@@ -1753,9 +1290,6 @@ const {
1753
1290
  });
1754
1291
 
1755
1292
  const rpcs = Object.create(null);
1756
- const add$1 = (id, rpc) => {
1757
- rpcs[id] = rpc;
1758
- };
1759
1293
  const get = id => {
1760
1294
  return rpcs[id];
1761
1295
  };
@@ -1774,12 +1308,12 @@ const createRpcWithId = async ({
1774
1308
  if (!info) {
1775
1309
  throw new Error(`rpc with id ${id} not found`);
1776
1310
  }
1777
- const ipc = await create$8({
1311
+ const ipc = await create$6({
1778
1312
  method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
1779
1313
  url: extensionHostSubWorkerUrl,
1780
1314
  name: info.name
1781
1315
  });
1782
- const rpc = await create$7({
1316
+ const rpc = await create$5({
1783
1317
  ipc,
1784
1318
  method: JsonRpc,
1785
1319
  execute
@@ -1820,12 +1354,12 @@ const createRpc = async ({
1820
1354
  if (contentSecurityPolicy) {
1821
1355
  await set(url, contentSecurityPolicy);
1822
1356
  }
1823
- const ipc = await create$8({
1357
+ const ipc = await create$6({
1824
1358
  method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
1825
1359
  url: extensionHostSubWorkerUrl,
1826
1360
  name
1827
1361
  });
1828
- const rpc = await create$7({
1362
+ const rpc = await create$5({
1829
1363
  ipc,
1830
1364
  method: JsonRpc,
1831
1365
  execute
@@ -1841,7 +1375,7 @@ const {
1841
1375
  registerSelectionProvider,
1842
1376
  executeSelectionProvider,
1843
1377
  reset: reset$2
1844
- } = create$a({
1378
+ } = create$8({
1845
1379
  name: 'Selection',
1846
1380
  resultShape: {
1847
1381
  allowUndefined: true,
@@ -1852,104 +1386,18 @@ const {
1852
1386
  }
1853
1387
  });
1854
1388
 
1855
- const state$3 = {
1389
+ const state$2 = {
1856
1390
  providers: Object.create(null)
1857
1391
  };
1858
1392
  const registerSourceControlProvider = provider => {
1859
- state$3.providers[provider.id] = provider;
1860
- };
1861
- const getFilesFromProvider = provider => {
1862
- return provider.getChangedFiles();
1863
- };
1864
- const getChangedFiles = async providerId => {
1865
- const provider = state$3.providers[providerId];
1866
- if (!provider) {
1867
- throw new Error('no source control provider found');
1868
- }
1869
- const changedFiles = await getFilesFromProvider(provider);
1870
- const flattenedChangedFiles = changedFiles;
1871
- return flattenedChangedFiles;
1872
- };
1873
- const getFileBefore = async (providerId, uri) => {
1874
- string(providerId);
1875
- string(uri);
1876
- const provider = state$3.providers[providerId];
1877
- if (!provider) {
1878
- throw new Error('no source control provider found');
1879
- }
1880
- return provider.getFileBefore(uri);
1881
- };
1882
- const getGroupsFromProvider = async (provider, cwd) => {
1883
- if (provider.getGroups) {
1884
- return provider.getGroups(cwd);
1885
- }
1886
- if (provider.getChangedFiles) {
1887
- const files = await provider.getChangedFiles();
1888
- const groups = [{
1889
- id: 'changes',
1890
- label: 'Changes',
1891
- items: files
1892
- }];
1893
- return groups;
1894
- }
1895
- throw new Error('source control provider is missing required function getGroups');
1896
- };
1897
- const getGroups = async (providerId, cwd) => {
1898
- const provider = state$3.providers[providerId];
1899
- if (!provider) {
1900
- throw new Error('no source control provider found');
1901
- }
1902
- const groups = await getGroupsFromProvider(provider, cwd);
1903
- return groups;
1904
- };
1905
- const acceptInput = async (providerId, value) => {
1906
- const provider = state$3.providers[providerId];
1907
- if (!provider) {
1908
- throw new Error('no source control provider found');
1909
- }
1910
- await provider.acceptInput(value);
1911
- };
1912
- const add = async path => {
1913
- const provider = Object.values(state$3.providers)[0];
1914
- if (!provider) {
1915
- return;
1916
- }
1917
- // @ts-ignore
1918
- await provider.add(path);
1919
- };
1920
- const discard = async path => {
1921
- const provider = Object.values(state$3.providers)[0];
1922
- if (!provider) {
1923
- return;
1924
- }
1925
- // @ts-ignore
1926
- await provider.discard(path);
1927
- };
1928
- const getEnabledProviderIds = async (scheme, root) => {
1929
- string(scheme);
1930
- string(root);
1931
- const providers = Object.values(state$3.providers);
1932
- const enabledIds = [];
1933
- for (const provider of providers) {
1934
- // @ts-ignore
1935
- if (typeof provider.isActive !== 'function') {
1936
- continue;
1937
- }
1938
- // @ts-ignore
1939
- const isActive = await provider.isActive(scheme, root);
1940
- if (isActive) {
1941
- // @ts-ignore
1942
- enabledIds.push(provider.id);
1943
- }
1944
- }
1945
- return enabledIds;
1393
+ state$2.providers[provider.id] = provider;
1946
1394
  };
1947
1395
 
1948
1396
  const {
1949
1397
  registerTabCompletionProvider,
1950
1398
  executeTabCompletionProvider,
1951
1399
  reset: reset$1
1952
- } = create$a({
1400
+ } = create$8({
1953
1401
  name: 'TabCompletion',
1954
1402
  resultShape: {
1955
1403
  type: Object$1,
@@ -1957,7 +1405,7 @@ const {
1957
1405
  }
1958
1406
  });
1959
1407
 
1960
- const state$2 = {
1408
+ const state$1 = {
1961
1409
  textSearchProviders: Object.create(null)
1962
1410
  };
1963
1411
  const registerTextSearchProvider = textSearchProvider => {
@@ -1968,14 +1416,14 @@ const registerTextSearchProvider = textSearchProvider => {
1968
1416
  if (!textSearchProvider.scheme) {
1969
1417
  throw new Error('textSearchProvider is missing scheme');
1970
1418
  }
1971
- state$2.textSearchProviders[textSearchProvider.scheme] = textSearchProvider;
1419
+ state$1.textSearchProviders[textSearchProvider.scheme] = textSearchProvider;
1972
1420
  } catch (error) {
1973
1421
  throw new VError$1(error, 'Failed to register text search provider');
1974
1422
  }
1975
1423
  };
1976
1424
  const executeTextSearchProvider = async (scheme, query) => {
1977
1425
  try {
1978
- const textSearchProvider = state$2.textSearchProviders[scheme];
1426
+ const textSearchProvider = state$1.textSearchProviders[scheme];
1979
1427
  if (!textSearchProvider) {
1980
1428
  throw new Error(`no text search provider for ${scheme} found`);
1981
1429
  }
@@ -1990,20 +1438,20 @@ const {
1990
1438
  registerTypeDefinitionProvider,
1991
1439
  executeTypeDefinitionProvider,
1992
1440
  reset
1993
- } = create$a({
1441
+ } = create$8({
1994
1442
  name: 'TypeDefinition',
1995
1443
  resultShape: {
1996
1444
  allowUndefined: true,
1997
1445
  type: Object$1,
1998
1446
  properties: {
1999
1447
  uri: {
2000
- type: String$1
1448
+ type: String
2001
1449
  },
2002
1450
  startOffset: {
2003
- type: Number$1
1451
+ type: Number
2004
1452
  },
2005
1453
  endOffset: {
2006
- type: Number$1
1454
+ type: Number
2007
1455
  }
2008
1456
  }
2009
1457
  }
@@ -2017,7 +1465,7 @@ const createWorker = async ({
2017
1465
  string(method);
2018
1466
  string(url);
2019
1467
  string(name);
2020
- const ipc = create$8({
1468
+ const ipc = create$6({
2021
1469
  method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
2022
1470
  url,
2023
1471
  name
@@ -2025,14 +1473,11 @@ const createWorker = async ({
2025
1473
  return ipc;
2026
1474
  };
2027
1475
 
2028
- const state$1 = {
1476
+ const state = {
2029
1477
  workspacePath: ''
2030
1478
  };
2031
- const setWorkspacePath = path => {
2032
- state$1.workspacePath = path;
2033
- };
2034
1479
  const getWorkspaceFolder = path => {
2035
- return state$1.workspacePath;
1480
+ return state.workspacePath;
2036
1481
  };
2037
1482
 
2038
1483
  const RE_PROTOCOL = /^([a-z\-]+):\/\//;
@@ -2162,12 +1607,12 @@ class FormattingError extends Error {
2162
1607
  }
2163
1608
  }
2164
1609
 
2165
- const File$1 = 1;
1610
+ const File = 1;
2166
1611
  const Match = 2;
2167
1612
 
2168
1613
  const TextSearchResultType = {
2169
1614
  __proto__: null,
2170
- File: File$1,
1615
+ File,
2171
1616
  Match
2172
1617
  };
2173
1618
 
@@ -2247,7 +1692,7 @@ const api = {
2247
1692
  registerTabCompletionProvider: registerTabCompletionProvider,
2248
1693
  executeTabCompletionProvider: executeTabCompletionProvider,
2249
1694
  // Text Document
2250
- getTextFromTextDocument: getText$1,
1695
+ getTextFromTextDocument: getText,
2251
1696
  // Text Search
2252
1697
  registerTextSearchProvider: registerTextSearchProvider,
2253
1698
  executeTextSearchProvider: executeTextSearchProvider,
@@ -2265,578 +1710,18 @@ const api = {
2265
1710
  getWorkspaceFolder: getWorkspaceFolder
2266
1711
  };
2267
1712
 
2268
- const processName = `extension host worker`;
2269
-
2270
- class CommandNotFoundError extends Error {
2271
- constructor(id) {
2272
- super(`Command "${id}" not found (${processName})`);
2273
- this.name = 'CommandNotFoundError';
1713
+ const getAssetDir = () => {
1714
+ // @ts-ignore
1715
+ if (typeof ASSET_DIR !== 'undefined') {
2274
1716
  // @ts-ignore
2275
- this.code = E_COMMAND_NOT_FOUND$1;
1717
+ return ASSET_DIR;
2276
1718
  }
2277
- }
2278
-
2279
- const BraceCompletionExecuteBraceCompletionProvider = 'ExtensionHostBraceCompletion.executeBraceCompletionProvider';
2280
- const ClosingTagExecuteClosingTagProvider = 'ExtensionHostClosingTag.executeClosingTagProvider';
2281
- const CommandExecute = 'ExtensionHostCommand.executeCommand';
2282
- const CompletionExecute = 'ExtensionHostCompletion.execute';
2283
- const CompletionResolveExecute = 'ExtensionHostCompletion.executeResolve';
2284
- const DefinitionExecuteDefinitionProvider = 'ExtensionHostDefinition.executeDefinitionProvider';
2285
- const DiagnosticExecuteDiagnosticProvider = 'ExtensionHost.executeDiagnosticProvider';
2286
- const ExtensionActivate = 'ExtensionHostExtension.activate';
2287
- const FileSystemGetPathSeparator = 'ExtensionHostFileSystem.getPathSeparator';
2288
- const FileSystemReadDirWithFileTypes = 'ExtensionHostFileSystem.readDirWithFileTypes';
2289
- const FileSystemReadFile = 'ExtensionHostFileSystem.readFile';
2290
- const FileSystemWriteFile = 'ExtensionHostFileSystem.writeFile';
2291
- const FormattingExecuteFormmattingProvider = 'ExtensionHostFormatting.executeFormattingProvider';
2292
- const HoverExecute = 'ExtensionHostHover.execute';
2293
- const ImplementationExecuteImplementationProvider = 'ExtensionHostImplementation.executeImplementationProvider';
2294
- const MockExec = 'ExtensionHostMockExec.mockExec';
2295
- const MockRpc = 'ExtensionHostMockRpc.mockRpc';
2296
- const OrganizeImportsExecute = 'ExtensionHostOrganizeImports.execute';
2297
- const ReferenceExecuteFileReferenceProvider = 'ExtensionHostReference.executeFileReferenceProvider';
2298
- const ReferenceExecuteReferenceProvider = 'ExtensionHostReference.executeReferenceProvider';
2299
- const SourceControlAcceptInput = 'ExtensionHostSourceControl.acceptInput';
2300
- const SourceControlAdd = 'ExtensionHostSourceControl.add';
2301
- const SourceControlDiscard = 'ExtensionHostSourceControl.discard';
2302
- const SourceControlGetChangedFiles = 'ExtensionHost.sourceControlGetChangedFiles';
2303
- const SourceControlGetEnabledProviderIds = 'ExtensionHostSourceControl.getEnabledProviderIds';
2304
- const SourceControlGetFileBefore = 'ExtensionHostSourceControl.GetFileBefore';
2305
- const SourceControlGetGroups = 'ExtensionHostSourceControl.getGroups';
2306
- const StatusBarGetStatusBarItems = 'ExtensionHost.getStatusBarItems';
2307
- const StatusBarRegisterChangeListener = 'ExtensionHostStatusBar.registerChangeListener';
2308
- const TabCompletionExecuteTabCompletionProvider = 'ExtensionHost.executeTabCompletionProvider';
2309
- const TextDocumentSetLanguageId = 'ExtensionHostTextDocument.setLanguageId';
2310
- const TextDocumentSyncFull = 'ExtensionHostTextDocument.syncFull';
2311
- const TextDocumentSyncIncremental = 'ExtensionHostTextDocument.syncIncremental';
2312
- const TextSearchExecuteTextSearchProvider = 'ExtensionHostTextSearch.executeTextSearchProvider';
2313
- const TypeDefinitionExecuteTypeDefinitionProvider = 'ExtensionHostTypeDefinition.executeTypeDefinitionProvider';
2314
- const WorkspaceSetPath = 'Workspace.setWorkspacePath';
2315
- const SelectionExecuteSelectionProvider = 'ExtensionHostSelection.executeSelectionProvider';
2316
- const ConfigurationSetConfiguration = 'ExtensionHostConfiguration.setConfiguration';
2317
-
2318
- const create$6 = () => {
2319
- return {
2320
- finished: false
2321
- };
2322
- };
2323
- const cancel = token => {
2324
- token.finished = true;
2325
- };
2326
- const isCanceled = token => {
2327
- return token.finished;
2328
- };
2329
-
2330
- const baseName = path => {
2331
- const slashIndex = path.lastIndexOf('/');
2332
- return path.slice(slashIndex + 1);
2333
- };
2334
- const getExtensionId = extension => {
2335
- if (extension && extension.id) {
2336
- return extension.id;
2337
- }
2338
- if (extension && extension.path) {
2339
- return baseName(extension.path);
2340
- }
2341
- return '<unknown>';
2342
- };
2343
-
2344
- const getUrlPrefix = extensionPath => {
2345
- if (extensionPath.startsWith('http://') || extensionPath.startsWith('https://')) {
2346
- return extensionPath;
2347
- }
2348
- return `/remote/${extensionPath}`;
2349
- };
2350
- const handleRpcInfos = extension => {
2351
- try {
2352
- if (!extension) {
2353
- return;
2354
- }
2355
- const rpcs = extension.rpc;
2356
- const urlPrefix = getUrlPrefix(extension.path);
2357
- if (!rpcs) {
2358
- return;
2359
- }
2360
- if (!Array.isArray(rpcs)) {
2361
- return;
2362
- }
2363
- for (const rpc of rpcs) {
2364
- rpc.url = `${urlPrefix}/${rpc.url}`;
2365
- add$1(rpc.id, rpc);
2366
- }
2367
- } catch (error) {
2368
- console.warn(`Failed to handle extension rpcs: ${error}`);
2369
- }
2370
- };
2371
-
2372
- class ContentSecurityPolicyError extends Error {
2373
- constructor(violatedDirective, sourceFile, lineNumber, columnNumber) {
2374
- super(`Content Security Policy Violation: ${violatedDirective}`);
2375
- this.name = 'ContentSecurityPolicyError';
2376
- if (sourceFile) {
2377
- this.stack = `Content Security Policy Violation
2378
- at ${sourceFile}:${lineNumber}:${columnNumber}`;
2379
- } else {
2380
- this.stack = `Content Security Policy Violation
2381
- at <unknown>`;
2382
- }
2383
- }
2384
- }
2385
-
2386
- const state = {
2387
- /**
2388
- * @type {any[]}
2389
- */
2390
- errors: []
2391
- };
2392
- const addError = error => {
2393
- // @ts-ignore
2394
- state.errors.push(error);
2395
- };
2396
- const hasRecentErrors = () => {
2397
- return state.errors.length > 0;
2398
- };
2399
- const getRecentError = () => {
2400
- return state.errors.at(-1);
2401
- };
2402
-
2403
- const isImportErrorChrome = error => {
2404
- return error && error instanceof Error && error.message.startsWith('Failed to fetch dynamically imported module');
2405
- };
2406
-
2407
- const isImportErrorFirefox = error => {
2408
- return error && error instanceof TypeError && error.message === 'error loading dynamically imported module';
2409
- };
2410
-
2411
- const isSyntaxError = error => {
2412
- return error instanceof SyntaxError;
2413
- };
2414
-
2415
- const isImportError = error => {
2416
- return isImportErrorChrome(error) || isImportErrorFirefox(error) || isSyntaxError(error);
2417
- };
2418
-
2419
- const sleep = duration => {
2420
- const promiseCallback = (resolve, reject) => {
2421
- setTimeout(resolve, duration);
2422
- };
2423
- return new Promise(promiseCallback);
2424
- };
2425
-
2426
- const NotFound = 404;
2427
-
2428
- const RE_LINE_COLUMN = /(.*)(?:\(\d+\:\d+\))/;
2429
- const getBabelErrorMessage = message => {
2430
- const match = message.match(RE_LINE_COLUMN);
2431
- if (match) {
2432
- return match[1].trim();
2433
- }
2434
- return message;
2435
- };
2436
- class BabelParseError extends SyntaxError {
2437
- constructor(url, error) {
2438
- const message = getBabelErrorMessage(error.message);
2439
- super(message);
2440
- this.name = 'BabelParseError';
2441
- // @ts-ignore
2442
- const line = error.loc.line;
2443
- // @ts-ignore
2444
- const column = error.loc.column + 1;
2445
- this.stack = `${message}
2446
- at ${url}:${line}:${column}`;
2447
- }
2448
- }
2449
-
2450
- const getAssetDir = () => {
2451
- // @ts-ignore
2452
- if (typeof ASSET_DIR !== 'undefined') {
2453
- // @ts-ignore
2454
- return ASSET_DIR;
2455
- }
2456
- if (platform === Electron) {
2457
- return '../../../../..';
2458
- }
2459
- return '';
2460
- };
2461
- const assetDir = getAssetDir();
2462
-
2463
- const loadBabelParser = () => {
2464
- const url = `${assetDir}/js/babel-parser.js`;
2465
- return import(url);
2466
- };
2467
-
2468
- const parse = async (code, options) => {
2469
- const BabelParse = await loadBabelParser();
2470
- return BabelParse.parse(code, options);
2471
- };
2472
-
2473
- const Module = 'module';
2474
-
2475
- const getLineAndColumn = (text, start, end) => {
2476
- let index = -1;
2477
- let line = 0;
2478
- const column = 0;
2479
- while ((index = text.indexOf('\n', index + 1)) !== -1) {
2480
- line++;
2481
- if (index >= start) {
2482
- break;
2483
- }
2484
- }
2485
- return {
2486
- line,
2487
- column
2488
- };
2489
- };
2490
-
2491
- class DependencyNotFoundError extends Error {
2492
- constructor(code, start, end, dependencyRelativePath, dependencyUrl, sourceUrl) {
2493
- super(`Module not found "${dependencyRelativePath}"`);
2494
- const {
2495
- line,
2496
- column
2497
- } = getLineAndColumn(code, start);
2498
- this.stack = `${this.message}
2499
- at Module (${sourceUrl}:${line}:${column})`;
2500
- }
2501
- }
2502
-
2503
- const ArrowFunctionExpression = 'ArrowFunctionExpression';
2504
- const AwaitExpression = 'AwaitExpression';
2505
- const BlockStatement = 'BlockStatement';
2506
- const CallExpression = 'CallExpression';
2507
- const ExportAllDeclaration = 'ExportAllDeclaration';
2508
- const ExportNamedDeclaration = 'ExportNamedDeclaration';
2509
- const ExpressionStatement = 'ExpressionStatement';
2510
- const File = 'File';
2511
- const Import = 'Import';
2512
- const ImportDeclaration = 'ImportDeclaration';
2513
- const Program = 'Program';
2514
- const StringLiteral = 'StringLiteral';
2515
- const VariableDeclaration = 'VariableDeclaration';
2516
- const VariableDeclarator = 'VariableDeclarator';
2517
-
2518
- const walk = (node, visitor) => {
2519
- if (!node) {
2520
- return;
2521
- }
2522
- if (Array.isArray(node)) {
2523
- for (const item of node) {
2524
- walk(item, visitor);
2525
- }
2526
- return;
2527
- }
2528
- visitor(node);
2529
- switch (node.type) {
2530
- case File:
2531
- walk(node.program, visitor);
2532
- break;
2533
- case Program:
2534
- walk(node.body, visitor);
2535
- break;
2536
- case ExportNamedDeclaration:
2537
- walk(node.declaration, visitor);
2538
- break;
2539
- case VariableDeclaration:
2540
- walk(node.declarations, visitor);
2541
- break;
2542
- case VariableDeclarator:
2543
- walk(node.init, visitor);
2544
- break;
2545
- case ArrowFunctionExpression:
2546
- walk(node.body, visitor);
2547
- break;
2548
- case BlockStatement:
2549
- walk(node.body, visitor);
2550
- break;
2551
- case ExpressionStatement:
2552
- walk(node.expression, visitor);
2553
- break;
2554
- case AwaitExpression:
2555
- walk(node.argument, visitor);
2556
- break;
2557
- case CallExpression:
2558
- walk(node.callee, visitor);
2559
- break;
2560
- }
2561
- };
2562
- const getBabelAstDependencies = (code, ast) => {
2563
- const {
2564
- program
2565
- } = ast;
2566
- const {
2567
- body
2568
- } = program;
2569
- const dependencies = [];
2570
- for (const node of body) {
2571
- if (node.type === ImportDeclaration || node.type === ExportAllDeclaration) {
2572
- const relativePath = node.source.extra.rawValue;
2573
- const start = node.source.start;
2574
- const end = node.source.end;
2575
- // @ts-ignore
2576
- dependencies.push({
2577
- relativePath,
2578
- code,
2579
- start,
2580
- end
2581
- });
2582
- } else if (node.type === VariableDeclaration && node.declarations && node.declarations[0] && node.declarations[0].type === VariableDeclarator && node.declarations[0].init && node.declarations[0].init.type === AwaitExpression && node.declarations[0].init.argument && node.declarations[0].init.argument.type === CallExpression && node.declarations[0].init.argument.callee && node.declarations[0].init.argument.callee.type === Import && node.declarations[0].init.argument.arguments && node.declarations[0].init.argument.arguments[0] && node.declarations[0].init.argument.arguments[0].type === StringLiteral) {
2583
- const relativePath = node.declarations[0].init.argument.arguments[0].extra.rawValue;
2584
- const start = node.declarations[0].init.argument.arguments[0].start;
2585
- const end = node.declarations[0].init.argument.arguments[0].end;
2586
- // @ts-ignore
2587
- dependencies.push({
2588
- relativePath,
2589
- code,
2590
- start,
2591
- end
2592
- });
2593
- }
2594
- }
2595
- const visitor = node => {
2596
- if (node && node.type === CallExpression && node.callee && node.callee.type === Import && node.arguments && node.arguments[0] && node.arguments[0].type === StringLiteral) {
2597
- const relativePath = node.arguments[0].extra.rawValue;
2598
- const start = node.arguments[0].start;
2599
- const end = node.arguments[0].end;
2600
- // @ts-ignore
2601
- dependencies.push({
2602
- relativePath,
2603
- code,
2604
- start,
2605
- end
2606
- });
2607
- }
2608
- };
2609
- walk(ast, visitor);
2610
- return dependencies;
2611
- };
2612
-
2613
- const isBabelError = error => {
2614
- // @ts-ignore
2615
- return isSyntaxError(error) && error.code === BABEL_PARSER_SYNTAX_ERROR;
2616
- };
2617
-
2618
- const getOrigin = () => {
2619
- return location.origin;
2620
- };
2621
-
2622
- const getAbsoluteUrl = (relativePath, sourceUrl) => {
2623
- if (sourceUrl.startsWith('/')) {
2624
- const origin = getOrigin();
2625
- const absoluteSourceUrl = new URL(sourceUrl, origin).toString();
2626
- return new URL(relativePath, absoluteSourceUrl).toString();
2627
- }
2628
- return new URL(relativePath, sourceUrl).toString();
2629
- };
2630
-
2631
- const isExternal = url => {
2632
- if (url.startsWith('/')) {
2633
- return false;
2634
- }
2635
- if (url.startsWith(location.protocol)) {
2636
- return false;
2637
- }
2638
- return true;
2639
- };
2640
- const getErrorInDependencies = async (url, dependencies, seenUrls) => {
2641
- for (const dependency of dependencies) {
2642
- const dependencyUrl = getAbsoluteUrl(dependency.relativePath, url);
2643
- if (isExternal(dependencyUrl) || seenUrls.includes(dependencyUrl)) {
2644
- continue;
2645
- }
2646
- seenUrls.push(dependencyUrl);
2647
- // let dependencyResponse
2648
- // try {
2649
- const dependencyResponse = await fetch(dependencyUrl);
2650
- // } catch (error) {}
2651
- if (dependencyResponse.ok) {
2652
- await tryToGetActualErrorMessage(null, dependencyUrl, dependencyResponse, seenUrls);
2653
- } else {
2654
- switch (dependencyResponse.status) {
2655
- case NotFound:
2656
- throw new DependencyNotFoundError(dependency.code, dependency.start, dependency.end, dependency.relativePath, dependencyUrl, url);
2657
- // return `Failed to import ${url}: ${error}`
2658
- }
2659
- }
2660
- }
2661
- };
2662
-
2663
- /**
2664
- *
2665
- * @param {string} url
2666
- * @param {Response} response
2667
- * @returns
2668
- */
2669
- const tryToGetActualErrorMessage = async (error, url, response, seenUrls = []) => {
2670
- let text;
2671
- try {
2672
- text = await response.text();
2673
- } catch (error) {
2674
- return `Failed to import ${url}: Unknown Network Error`;
2675
- }
2676
- let ast;
2677
- try {
2678
- ast = await parse(text, {
2679
- sourceType: Module
2680
- });
2681
- } catch (error) {
2682
- if (isBabelError(error)) {
2683
- throw new BabelParseError(url, error);
2684
- }
2685
- throw error;
2686
- }
2687
- const dependencies = getBabelAstDependencies(text, ast);
2688
- await getErrorInDependencies(url, dependencies, seenUrls);
2689
- if (hasRecentErrors()) {
2690
- const recentError = getRecentError();
2691
- // @ts-ignore
2692
- throw new ContentSecurityPolicyError(recentError.violatedDirective, recentError.sourceFile, recentError.lineNumber, recentError.columnNumber);
2693
- }
2694
- const contentType = response.headers.get('Content-Type');
2695
- if (url.endsWith('.ts') && contentType === null) {
2696
- return `Failed to import ${url}: Missing Content-Type header for javascript`;
2697
- }
2698
- return `Failed to import ${url}: Unknown Network Error`;
2699
- };
2700
-
2701
- const tryToGetActualImportErrorMessage = async (url, error) => {
2702
- let response;
2703
- try {
2704
- response = await fetch(url);
2705
- } catch (error) {
2706
- return `Failed to import ${url}: ${error}`;
2707
- }
2708
- if (response.ok) {
2709
- return await tryToGetActualErrorMessage(error, url, response);
2710
- }
2711
- switch (response.status) {
2712
- case NotFound:
2713
- throw new Error(`Failed to import ${url}: Not found (404)`);
2714
- default:
2715
- return `Failed to import ${url}: ${error}`;
2716
- }
2717
- };
2718
-
2719
- const importScript = async url => {
2720
- try {
2721
- return await import(url);
2722
- } catch (error) {
2723
- if (isImportError(error)) {
2724
- const actualErrorMessage = await tryToGetActualImportErrorMessage(url, error);
2725
- throw new Error(actualErrorMessage);
2726
- }
2727
- // content security policy errors arrive a little bit later
2728
- await sleep(0);
2729
- if (hasRecentErrors()) {
2730
- const recentError = getRecentError();
2731
- // @ts-ignore
2732
- throw new ContentSecurityPolicyError(recentError.violatedDirective, recentError.sourceFile, recentError.lineNumber, recentError.columnNumber);
2733
- }
2734
- throw error;
2735
- }
2736
- };
2737
-
2738
- const activationTimeout = 10_000;
2739
- const rejectAfterTimeout = async (timeout, token) => {
2740
- await sleep(timeout);
2741
- if (isCanceled(token)) {
2742
- return;
2743
- }
2744
- throw new Error(`Activation timeout of ${timeout}ms exceeded`);
2745
- };
2746
- const activate = async (extension, absolutePath) => {
2747
- try {
2748
- string(extension.path);
2749
- string(extension.browser);
2750
- string(absolutePath);
2751
- const module = await importScript(absolutePath);
2752
- handleRpcInfos(extension);
2753
- const token = create$6();
2754
- try {
2755
- await Promise.race([module.activate(extension), rejectAfterTimeout(activationTimeout, token)]);
2756
- } catch (error) {
2757
- if (isImportError(error)) {
2758
- const actualErrorMessage = await tryToGetActualImportErrorMessage(absolutePath, error);
2759
- throw new Error(actualErrorMessage);
2760
- }
2761
- throw error;
2762
- } finally {
2763
- cancel(token);
2764
- }
2765
- } catch (error) {
2766
- const id = getExtensionId(extension);
2767
- throw new VError$1(error, `Failed to activate extension ${id}`);
2768
- }
2769
- // console.info('activated', path)
2770
- };
2771
-
2772
- class ExecError extends Error {
2773
- constructor(command, args, stdout, stderr, exitCode) {
2774
- super(`Failed to execute ${command}: process exited with code ${exitCode}`);
2775
- this.name = 'ExecError';
2776
- // @ts-ignore
2777
- this.stdout = stdout;
2778
- // @ts-ignore
2779
- this.stderr = stderr;
2780
- // @ts-ignore
2781
- this.exitCode = exitCode;
2782
- }
2783
- }
2784
-
2785
- const mockExec = () => {
2786
- try {
2787
- // @ts-ignore
2788
- api.exec = async (command, args, options) => {
2789
- const result = await invoke('Test.executeMockExecFunction', command, args, options);
2790
- const {
2791
- stdout,
2792
- stderr,
2793
- exitCode
2794
- } = result;
2795
- if (exitCode !== 0) {
2796
- throw new ExecError(command, args, stdout, stderr, exitCode);
2797
- }
2798
- return {
2799
- stdout,
2800
- stderr,
2801
- exitCode
2802
- };
2803
- };
2804
- } catch (error) {
2805
- throw new VError$1(error, 'Failed to mock exec function');
2806
- }
2807
- };
2808
-
2809
- const mockRpc = () => {
2810
- // @ts-ignore
2811
- api.createNodeRpc = async options => {
2812
- try {
2813
- return {
2814
- async invoke(method, ...params) {
2815
- const result = await invoke('Test.executeMockRpcFunction', options.name, method, ...params);
2816
- return result;
2817
- }
2818
- };
2819
- } catch (error) {
2820
- throw new VError$1(error, 'Failed to mock exec function');
2821
- }
2822
- };
2823
- };
2824
-
2825
- const getStatusBarItems = async () => {
2826
- const providers = Object.values(state$3.providers);
2827
- const statusBarItems = [];
2828
- for (const provider of providers) {
2829
- // @ts-ignore
2830
- if (provider && provider.statusBarCommands) {
2831
- // @ts-ignore
2832
- statusBarItems.push(...provider.statusBarCommands);
2833
- }
2834
- }
2835
- return statusBarItems;
2836
- };
2837
- const registerChangeListener = () => {
2838
- // TODO
1719
+ if (platform === Electron) {
1720
+ return '../../../../..';
1721
+ }
1722
+ return '';
2839
1723
  };
1724
+ getAssetDir();
2840
1725
 
2841
1726
  const MessagePort$1 = 1;
2842
1727
  const ModuleWorker = 2;
@@ -2968,17 +1853,17 @@ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
2968
1853
  const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
2969
1854
  const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
2970
1855
  const NewLine$1 = '\n';
2971
- const joinLines$1 = lines => {
1856
+ const joinLines = lines => {
2972
1857
  return lines.join(NewLine$1);
2973
1858
  };
2974
- const splitLines$1 = lines => {
1859
+ const splitLines = lines => {
2975
1860
  return lines.split(NewLine$1);
2976
1861
  };
2977
1862
  const isModuleNotFoundMessage = line => {
2978
1863
  return line.includes('[ERR_MODULE_NOT_FOUND]');
2979
1864
  };
2980
1865
  const getModuleNotFoundError = stderr => {
2981
- const lines = splitLines$1(stderr);
1866
+ const lines = splitLines(stderr);
2982
1867
  const messageIndex = lines.findIndex(isModuleNotFoundMessage);
2983
1868
  const message = lines[messageIndex];
2984
1869
  return {
@@ -3002,7 +1887,7 @@ const isMessageCodeBlockEndIndex = line => {
3002
1887
  return RE_MESSAGE_CODE_BLOCK_END.test(line);
3003
1888
  };
3004
1889
  const getMessageCodeBlock = stderr => {
3005
- const lines = splitLines$1(stderr);
1890
+ const lines = splitLines(stderr);
3006
1891
  const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
3007
1892
  const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
3008
1893
  const relevantLines = lines.slice(startIndex, endIndex);
@@ -3041,7 +1926,7 @@ const getDetails = lines => {
3041
1926
  const index = lines.findIndex(isNormalStackLine);
3042
1927
  if (index === -1) {
3043
1928
  return {
3044
- actualMessage: joinLines$1(lines),
1929
+ actualMessage: joinLines(lines),
3045
1930
  rest: []
3046
1931
  };
3047
1932
  }
@@ -3066,7 +1951,7 @@ const getHelpfulChildProcessError = (stdout, stderr) => {
3066
1951
  if (isModuleNotFoundError(stderr)) {
3067
1952
  return getModuleNotFoundError(stderr);
3068
1953
  }
3069
- const lines = splitLines$1(stderr);
1954
+ const lines = splitLines(stderr);
3070
1955
  const {
3071
1956
  actualMessage,
3072
1957
  rest
@@ -3292,971 +2177,35 @@ const getModule$1 = method => {
3292
2177
  }
3293
2178
  };
3294
2179
 
3295
- const handleMessagePort = port => {
3296
- const module = getModule$1(MessagePort$1);
3297
- const ipc = module.wrap(port);
3298
- handleIpc(ipc);
3299
- ipc.send('ready');
2180
+ const handleError = async error => {
2181
+ console.error(error);
3300
2182
  };
3301
2183
 
3302
- const getFn = method => {
3303
- switch (method) {
3304
- case ExtensionActivate:
3305
- return activate;
3306
- case ReferenceExecuteReferenceProvider:
3307
- return executeReferenceProvider;
3308
- case ReferenceExecuteFileReferenceProvider:
3309
- return executefileReferenceProvider;
3310
- case CompletionExecute:
3311
- return executeCompletionProvider;
3312
- case CompletionResolveExecute:
3313
- return executeresolveCompletionItemProvider;
3314
- case TextDocumentSyncFull:
3315
- return syncFull;
3316
- case TextDocumentSetLanguageId:
3317
- return setLanguageId;
3318
- case TypeDefinitionExecuteTypeDefinitionProvider:
3319
- return executeTypeDefinitionProvider;
3320
- case TabCompletionExecuteTabCompletionProvider:
3321
- return executeTabCompletionProvider;
3322
- case BraceCompletionExecuteBraceCompletionProvider:
3323
- return executeBraceCompletionProvider;
3324
- case TextDocumentSyncIncremental:
3325
- return syncIncremental;
3326
- case TextSearchExecuteTextSearchProvider:
3327
- return executeTextSearchProvider;
3328
- case CommandExecute:
3329
- return executeCommand;
3330
- case DiagnosticExecuteDiagnosticProvider:
3331
- return executeDiagnosticProvider;
3332
- case WorkspaceSetPath:
3333
- return setWorkspacePath;
3334
- case DefinitionExecuteDefinitionProvider:
3335
- return executeDefinitionProvider;
3336
- case SourceControlGetChangedFiles:
3337
- return getChangedFiles;
3338
- case SourceControlAcceptInput:
3339
- return acceptInput;
3340
- case FormattingExecuteFormmattingProvider:
3341
- return executeFormattingProvider;
3342
- case SourceControlGetFileBefore:
3343
- return getFileBefore;
3344
- case MockExec:
3345
- return mockExec;
3346
- case MockRpc:
3347
- return mockRpc;
3348
- case FileSystemReadFile:
3349
- return readFile;
3350
- case FileSystemReadDirWithFileTypes:
3351
- return readDirWithFileTypes;
3352
- case FileSystemWriteFile:
3353
- return writeFile;
3354
- case FileSystemGetPathSeparator:
3355
- return getPathSeparator;
3356
- case SourceControlAdd:
3357
- return add;
3358
- case SourceControlDiscard:
3359
- return discard;
3360
- case SourceControlGetEnabledProviderIds:
3361
- return getEnabledProviderIds;
3362
- case SourceControlGetGroups:
3363
- return getGroups;
3364
- case 'ExtensionHostDebug.listProcesses':
3365
- return listProcesses;
3366
- case 'ExtensionHostDebug.pause':
3367
- return pause;
3368
- case 'ExtensionHostDebug.resume':
3369
- return resume;
3370
- case 'ExtensionHostDebug.setPauseOnException':
3371
- return setPauseOnException;
3372
- case 'ExtensionHostDebug.start':
3373
- return start;
3374
- case 'ExtensionHostDebug.stepOver':
3375
- return stepOver;
3376
- case 'ExtensionHostDebug.stepOut':
3377
- return stepOut;
3378
- case 'ExtensionHostDebug.stepInto':
3379
- return stepInto;
3380
- case 'ExtensionHostDebug.getProperties':
3381
- return getProperties;
3382
- case 'ExtensionHostDebug.evaluate':
3383
- return evaluate;
3384
- case 'ExtensionHostDebug.setPauseOnExceptions':
3385
- return setPauseOnExceptions;
3386
- case ClosingTagExecuteClosingTagProvider:
3387
- return executeClosingTagProvider;
3388
- case ImplementationExecuteImplementationProvider:
3389
- return executeImplementationProvider;
3390
- case HoverExecute:
3391
- return executeHoverProvider;
3392
- case StatusBarGetStatusBarItems:
3393
- return getStatusBarItems;
3394
- case StatusBarRegisterChangeListener:
3395
- return registerChangeListener;
3396
- case OrganizeImportsExecute:
3397
- return executeOrganizeImports;
3398
- case SelectionExecuteSelectionProvider:
3399
- return executeSelectionProvider;
3400
- case ConfigurationSetConfiguration:
3401
- return setConfigurations;
3402
- case 'HandleMessagePort.handleMessagePort':
3403
- return handleMessagePort;
3404
- case 'ExtensionHostWebView.create':
3405
- return createWebView;
3406
- case 'ExtensionHostWebView.dispose':
3407
- return disposeWebView;
3408
- case 'ExtensionHostWebView.load':
3409
- return load;
3410
- default:
3411
- throw new CommandNotFoundError(method);
2184
+ /**
2185
+ * @param {PromiseRejectionEvent} event
2186
+ */
2187
+ const handleUnhandledRejection = async event => {
2188
+ try {
2189
+ event.preventDefault();
2190
+ await handleError(event.reason);
2191
+ } catch {
2192
+ console.error(event.reason);
3412
2193
  }
3413
2194
  };
3414
2195
 
3415
- class HTTPError extends Error {
3416
- response;
3417
- request;
3418
- options;
3419
- constructor(response, request, options) {
3420
- const code = response.status || response.status === 0 ? response.status : '';
3421
- const title = response.statusText || '';
3422
- const status = `${code} ${title}`.trim();
3423
- const reason = status ? `status code ${status}` : 'an unknown error';
3424
- super(`Request failed with ${reason}: ${request.method} ${request.url}`);
3425
- this.name = 'HTTPError';
3426
- this.response = response;
3427
- this.request = request;
3428
- this.options = options;
3429
- }
3430
- }
3431
-
3432
- class TimeoutError extends Error {
3433
- request;
3434
- constructor(request) {
3435
- super(`Request timed out: ${request.method} ${request.url}`);
3436
- this.name = 'TimeoutError';
3437
- this.request = request;
3438
- }
3439
- }
3440
-
3441
- // eslint-disable-next-line @typescript-eslint/ban-types
3442
- const isObject = value => value !== null && typeof value === 'object';
3443
-
3444
- const validateAndMerge = (...sources) => {
3445
- for (const source of sources) {
3446
- if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {
3447
- throw new TypeError('The `options` argument must be an object');
3448
- }
2196
+ /**
2197
+ * @param {ErrorEvent} event
2198
+ */
2199
+ const handleUnhandledError = async event => {
2200
+ try {
2201
+ event.preventDefault();
2202
+ await handleError(event.error);
2203
+ } catch {
2204
+ console.error(event.error);
3449
2205
  }
3450
- return deepMerge({}, ...sources);
3451
2206
  };
3452
- const mergeHeaders = (source1 = {}, source2 = {}) => {
3453
- const result = new globalThis.Headers(source1);
3454
- const isHeadersInstance = source2 instanceof globalThis.Headers;
3455
- const source = new globalThis.Headers(source2);
3456
- for (const [key, value] of source.entries()) {
3457
- if (isHeadersInstance && value === 'undefined' || value === undefined) {
3458
- result.delete(key);
3459
- } else {
3460
- result.set(key, value);
3461
- }
3462
- }
3463
- return result;
3464
- };
3465
- function newHookValue(original, incoming, property) {
3466
- return Object.hasOwn(incoming, property) && incoming[property] === undefined ? [] : deepMerge(original[property] ?? [], incoming[property] ?? []);
3467
- }
3468
- const mergeHooks = (original = {}, incoming = {}) => ({
3469
- beforeRequest: newHookValue(original, incoming, 'beforeRequest'),
3470
- beforeRetry: newHookValue(original, incoming, 'beforeRetry'),
3471
- afterResponse: newHookValue(original, incoming, 'afterResponse'),
3472
- beforeError: newHookValue(original, incoming, 'beforeError')
3473
- });
3474
- // TODO: Make this strongly-typed (no `any`).
3475
- const deepMerge = (...sources) => {
3476
- let returnValue = {};
3477
- let headers = {};
3478
- let hooks = {};
3479
- for (const source of sources) {
3480
- if (Array.isArray(source)) {
3481
- if (!Array.isArray(returnValue)) {
3482
- returnValue = [];
3483
- }
3484
- returnValue = [...returnValue, ...source];
3485
- } else if (isObject(source)) {
3486
- for (let [key, value] of Object.entries(source)) {
3487
- if (isObject(value) && key in returnValue) {
3488
- value = deepMerge(returnValue[key], value);
3489
- }
3490
- returnValue = {
3491
- ...returnValue,
3492
- [key]: value
3493
- };
3494
- }
3495
- if (isObject(source.hooks)) {
3496
- hooks = mergeHooks(hooks, source.hooks);
3497
- returnValue.hooks = hooks;
3498
- }
3499
- if (isObject(source.headers)) {
3500
- headers = mergeHeaders(headers, source.headers);
3501
- returnValue.headers = headers;
3502
- }
3503
- }
3504
- }
3505
- return returnValue;
3506
- };
3507
-
3508
- const supportsRequestStreams = (() => {
3509
- let duplexAccessed = false;
3510
- let hasContentType = false;
3511
- const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
3512
- const supportsRequest = typeof globalThis.Request === 'function';
3513
- if (supportsReadableStream && supportsRequest) {
3514
- try {
3515
- hasContentType = new globalThis.Request('https://empty.invalid', {
3516
- body: new globalThis.ReadableStream(),
3517
- method: 'POST',
3518
- // @ts-expect-error - Types are outdated.
3519
- get duplex() {
3520
- duplexAccessed = true;
3521
- return 'half';
3522
- }
3523
- }).headers.has('Content-Type');
3524
- } catch (error) {
3525
- // QQBrowser on iOS throws "unsupported BodyInit type" error (see issue #581)
3526
- if (error instanceof Error && error.message === 'unsupported BodyInit type') {
3527
- return false;
3528
- }
3529
- throw error;
3530
- }
3531
- }
3532
- return duplexAccessed && !hasContentType;
3533
- })();
3534
- const supportsAbortController = typeof globalThis.AbortController === 'function';
3535
- const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';
3536
- const supportsFormData = typeof globalThis.FormData === 'function';
3537
- const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
3538
- const responseTypes = {
3539
- json: 'application/json',
3540
- text: 'text/*',
3541
- formData: 'multipart/form-data',
3542
- arrayBuffer: '*/*',
3543
- blob: '*/*'
3544
- };
3545
- // The maximum value of a 32bit int (see issue #117)
3546
- const maxSafeTimeout = 2_147_483_647;
3547
- const stop = Symbol('stop');
3548
- const kyOptionKeys = {
3549
- json: true,
3550
- parseJson: true,
3551
- stringifyJson: true,
3552
- searchParams: true,
3553
- prefixUrl: true,
3554
- retry: true,
3555
- timeout: true,
3556
- hooks: true,
3557
- throwHttpErrors: true,
3558
- onDownloadProgress: true,
3559
- fetch: true
3560
- };
3561
- const requestOptionsRegistry = {
3562
- method: true,
3563
- headers: true,
3564
- body: true,
3565
- mode: true,
3566
- credentials: true,
3567
- cache: true,
3568
- redirect: true,
3569
- referrer: true,
3570
- referrerPolicy: true,
3571
- integrity: true,
3572
- keepalive: true,
3573
- signal: true,
3574
- window: true,
3575
- dispatcher: true,
3576
- duplex: true,
3577
- priority: true
3578
- };
3579
-
3580
- const normalizeRequestMethod = input => requestMethods.includes(input) ? input.toUpperCase() : input;
3581
- const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
3582
- const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
3583
- const retryAfterStatusCodes = [413, 429, 503];
3584
- const defaultRetryOptions = {
3585
- limit: 2,
3586
- methods: retryMethods,
3587
- statusCodes: retryStatusCodes,
3588
- afterStatusCodes: retryAfterStatusCodes,
3589
- maxRetryAfter: Number.POSITIVE_INFINITY,
3590
- backoffLimit: Number.POSITIVE_INFINITY,
3591
- delay: attemptCount => 0.3 * 2 ** (attemptCount - 1) * 1000
3592
- };
3593
- const normalizeRetryOptions = (retry = {}) => {
3594
- if (typeof retry === 'number') {
3595
- return {
3596
- ...defaultRetryOptions,
3597
- limit: retry
3598
- };
3599
- }
3600
- if (retry.methods && !Array.isArray(retry.methods)) {
3601
- throw new Error('retry.methods must be an array');
3602
- }
3603
- if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
3604
- throw new Error('retry.statusCodes must be an array');
3605
- }
3606
- return {
3607
- ...defaultRetryOptions,
3608
- ...retry
3609
- };
3610
- };
3611
-
3612
- // `Promise.race()` workaround (#91)
3613
- async function timeout(request, init, abortController, options) {
3614
- return new Promise((resolve, reject) => {
3615
- const timeoutId = setTimeout(() => {
3616
- if (abortController) {
3617
- abortController.abort();
3618
- }
3619
- reject(new TimeoutError(request));
3620
- }, options.timeout);
3621
- void options.fetch(request, init).then(resolve).catch(reject).then(() => {
3622
- clearTimeout(timeoutId);
3623
- });
3624
- });
3625
- }
3626
-
3627
- // https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
3628
- async function delay(ms, {
3629
- signal
3630
- }) {
3631
- return new Promise((resolve, reject) => {
3632
- if (signal) {
3633
- signal.throwIfAborted();
3634
- signal.addEventListener('abort', abortHandler, {
3635
- once: true
3636
- });
3637
- }
3638
- function abortHandler() {
3639
- clearTimeout(timeoutId);
3640
- reject(signal.reason);
3641
- }
3642
- const timeoutId = setTimeout(() => {
3643
- signal?.removeEventListener('abort', abortHandler);
3644
- resolve();
3645
- }, ms);
3646
- });
3647
- }
3648
-
3649
- const findUnknownOptions = (request, options) => {
3650
- const unknownOptions = {};
3651
- for (const key in options) {
3652
- if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request)) {
3653
- unknownOptions[key] = options[key];
3654
- }
3655
- }
3656
- return unknownOptions;
3657
- };
3658
-
3659
- class Ky {
3660
- static create(input, options) {
3661
- const ky = new Ky(input, options);
3662
- const function_ = async () => {
3663
- if (typeof ky._options.timeout === 'number' && ky._options.timeout > maxSafeTimeout) {
3664
- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
3665
- }
3666
- // Delay the fetch so that body method shortcuts can set the Accept header
3667
- await Promise.resolve();
3668
- let response = await ky._fetch();
3669
- for (const hook of ky._options.hooks.afterResponse) {
3670
- // eslint-disable-next-line no-await-in-loop
3671
- const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
3672
- if (modifiedResponse instanceof globalThis.Response) {
3673
- response = modifiedResponse;
3674
- }
3675
- }
3676
- ky._decorateResponse(response);
3677
- if (!response.ok && ky._options.throwHttpErrors) {
3678
- let error = new HTTPError(response, ky.request, ky._options);
3679
- for (const hook of ky._options.hooks.beforeError) {
3680
- // eslint-disable-next-line no-await-in-loop
3681
- error = await hook(error);
3682
- }
3683
- throw error;
3684
- }
3685
- // If `onDownloadProgress` is passed, it uses the stream API internally
3686
- /* istanbul ignore next */
3687
- if (ky._options.onDownloadProgress) {
3688
- if (typeof ky._options.onDownloadProgress !== 'function') {
3689
- throw new TypeError('The `onDownloadProgress` option must be a function');
3690
- }
3691
- if (!supportsResponseStreams) {
3692
- throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
3693
- }
3694
- return ky._stream(response.clone(), ky._options.onDownloadProgress);
3695
- }
3696
- return response;
3697
- };
3698
- const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
3699
- const result = isRetriableMethod ? ky._retry(function_) : function_();
3700
- for (const [type, mimeType] of Object.entries(responseTypes)) {
3701
- result[type] = async () => {
3702
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
3703
- ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
3704
- const awaitedResult = await result;
3705
- const response = awaitedResult.clone();
3706
- if (type === 'json') {
3707
- if (response.status === 204) {
3708
- return '';
3709
- }
3710
- const arrayBuffer = await response.clone().arrayBuffer();
3711
- const responseSize = arrayBuffer.byteLength;
3712
- if (responseSize === 0) {
3713
- return '';
3714
- }
3715
- if (options.parseJson) {
3716
- return options.parseJson(await response.text());
3717
- }
3718
- }
3719
- return response[type]();
3720
- };
3721
- }
3722
- return result;
3723
- }
3724
- request;
3725
- abortController;
3726
- _retryCount = 0;
3727
- _input;
3728
- _options;
3729
- // eslint-disable-next-line complexity
3730
- constructor(input, options = {}) {
3731
- this._input = input;
3732
- this._options = {
3733
- ...options,
3734
- headers: mergeHeaders(this._input.headers, options.headers),
3735
- hooks: mergeHooks({
3736
- beforeRequest: [],
3737
- beforeRetry: [],
3738
- beforeError: [],
3739
- afterResponse: []
3740
- }, options.hooks),
3741
- method: normalizeRequestMethod(options.method ?? this._input.method),
3742
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
3743
- prefixUrl: String(options.prefixUrl || ''),
3744
- retry: normalizeRetryOptions(options.retry),
3745
- throwHttpErrors: options.throwHttpErrors !== false,
3746
- timeout: options.timeout ?? 10_000,
3747
- fetch: options.fetch ?? globalThis.fetch.bind(globalThis)
3748
- };
3749
- if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
3750
- throw new TypeError('`input` must be a string, URL, or Request');
3751
- }
3752
- if (this._options.prefixUrl && typeof this._input === 'string') {
3753
- if (this._input.startsWith('/')) {
3754
- throw new Error('`input` must not begin with a slash when using `prefixUrl`');
3755
- }
3756
- if (!this._options.prefixUrl.endsWith('/')) {
3757
- this._options.prefixUrl += '/';
3758
- }
3759
- this._input = this._options.prefixUrl + this._input;
3760
- }
3761
- if (supportsAbortController) {
3762
- this.abortController = new globalThis.AbortController();
3763
- const originalSignal = this._options.signal ?? this._input.signal;
3764
- originalSignal?.addEventListener('abort', () => {
3765
- this.abortController.abort(originalSignal.reason);
3766
- });
3767
- this._options.signal = this.abortController.signal;
3768
- }
3769
- if (supportsRequestStreams) {
3770
- // @ts-expect-error - Types are outdated.
3771
- this._options.duplex = 'half';
3772
- }
3773
- if (this._options.json !== undefined) {
3774
- this._options.body = this._options.stringifyJson?.(this._options.json) ?? JSON.stringify(this._options.json);
3775
- this._options.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
3776
- }
3777
- this.request = new globalThis.Request(this._input, this._options);
3778
- if (this._options.searchParams) {
3779
- // eslint-disable-next-line unicorn/prevent-abbreviations
3780
- const textSearchParams = typeof this._options.searchParams === 'string' ? this._options.searchParams.replace(/^\?/, '') : new URLSearchParams(this._options.searchParams).toString();
3781
- // eslint-disable-next-line unicorn/prevent-abbreviations
3782
- const searchParams = '?' + textSearchParams;
3783
- const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
3784
- // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
3785
- if ((supportsFormData && this._options.body instanceof globalThis.FormData || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
3786
- this.request.headers.delete('content-type');
3787
- }
3788
- // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.
3789
- this.request = new globalThis.Request(new globalThis.Request(url, {
3790
- ...this.request
3791
- }), this._options);
3792
- }
3793
- }
3794
- _calculateRetryDelay(error) {
3795
- this._retryCount++;
3796
- if (this._retryCount > this._options.retry.limit || error instanceof TimeoutError) {
3797
- throw error;
3798
- }
3799
- if (error instanceof HTTPError) {
3800
- if (!this._options.retry.statusCodes.includes(error.response.status)) {
3801
- throw error;
3802
- }
3803
- const retryAfter = error.response.headers.get('Retry-After') ?? error.response.headers.get('RateLimit-Reset') ?? error.response.headers.get('X-RateLimit-Reset') // GitHub
3804
- ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter
3805
- if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
3806
- let after = Number(retryAfter) * 1000;
3807
- if (Number.isNaN(after)) {
3808
- after = Date.parse(retryAfter) - Date.now();
3809
- } else if (after >= Date.parse('2024-01-01')) {
3810
- // A large number is treated as a timestamp (fixed threshold protects against clock skew)
3811
- after -= Date.now();
3812
- }
3813
- const max = this._options.retry.maxRetryAfter ?? after;
3814
- return after < max ? after : max;
3815
- }
3816
- if (error.response.status === 413) {
3817
- throw error;
3818
- }
3819
- }
3820
- const retryDelay = this._options.retry.delay(this._retryCount);
3821
- return Math.min(this._options.retry.backoffLimit, retryDelay);
3822
- }
3823
- _decorateResponse(response) {
3824
- if (this._options.parseJson) {
3825
- response.json = async () => this._options.parseJson(await response.text());
3826
- }
3827
- return response;
3828
- }
3829
- async _retry(function_) {
3830
- try {
3831
- return await function_();
3832
- } catch (error) {
3833
- const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
3834
- if (this._retryCount < 1) {
3835
- throw error;
3836
- }
3837
- await delay(ms, {
3838
- signal: this._options.signal
3839
- });
3840
- for (const hook of this._options.hooks.beforeRetry) {
3841
- // eslint-disable-next-line no-await-in-loop
3842
- const hookResult = await hook({
3843
- request: this.request,
3844
- options: this._options,
3845
- error: error,
3846
- retryCount: this._retryCount
3847
- });
3848
- // If `stop` is returned from the hook, the retry process is stopped
3849
- if (hookResult === stop) {
3850
- return;
3851
- }
3852
- }
3853
- return this._retry(function_);
3854
- }
3855
- }
3856
- async _fetch() {
3857
- for (const hook of this._options.hooks.beforeRequest) {
3858
- // eslint-disable-next-line no-await-in-loop
3859
- const result = await hook(this.request, this._options);
3860
- if (result instanceof Request) {
3861
- this.request = result;
3862
- break;
3863
- }
3864
- if (result instanceof Response) {
3865
- return result;
3866
- }
3867
- }
3868
- const nonRequestOptions = findUnknownOptions(this.request, this._options);
3869
- // Cloning is done here to prepare in advance for retries
3870
- const mainRequest = this.request;
3871
- this.request = mainRequest.clone();
3872
- if (this._options.timeout === false) {
3873
- return this._options.fetch(mainRequest, nonRequestOptions);
3874
- }
3875
- return timeout(mainRequest, nonRequestOptions, this.abortController, this._options);
3876
- }
3877
- /* istanbul ignore next */
3878
- _stream(response, onDownloadProgress) {
3879
- const totalBytes = Number(response.headers.get('content-length')) || 0;
3880
- let transferredBytes = 0;
3881
- if (response.status === 204) {
3882
- if (onDownloadProgress) {
3883
- onDownloadProgress({
3884
- percent: 1,
3885
- totalBytes,
3886
- transferredBytes
3887
- }, new Uint8Array());
3888
- }
3889
- return new globalThis.Response(null, {
3890
- status: response.status,
3891
- statusText: response.statusText,
3892
- headers: response.headers
3893
- });
3894
- }
3895
- return new globalThis.Response(new globalThis.ReadableStream({
3896
- async start(controller) {
3897
- const reader = response.body.getReader();
3898
- if (onDownloadProgress) {
3899
- onDownloadProgress({
3900
- percent: 0,
3901
- transferredBytes: 0,
3902
- totalBytes
3903
- }, new Uint8Array());
3904
- }
3905
- async function read() {
3906
- const {
3907
- done,
3908
- value
3909
- } = await reader.read();
3910
- if (done) {
3911
- controller.close();
3912
- return;
3913
- }
3914
- if (onDownloadProgress) {
3915
- transferredBytes += value.byteLength;
3916
- const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
3917
- onDownloadProgress({
3918
- percent,
3919
- transferredBytes,
3920
- totalBytes
3921
- }, value);
3922
- }
3923
- controller.enqueue(value);
3924
- await read();
3925
- }
3926
- await read();
3927
- }
3928
- }), {
3929
- status: response.status,
3930
- statusText: response.statusText,
3931
- headers: response.headers
3932
- });
3933
- }
3934
- }
3935
-
3936
- /*! MIT License © Sindre Sorhus */
3937
- const createInstance = defaults => {
3938
- // eslint-disable-next-line @typescript-eslint/promise-function-async
3939
- const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
3940
- for (const method of requestMethods) {
3941
- // eslint-disable-next-line @typescript-eslint/promise-function-async
3942
- ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, {
3943
- method
3944
- }));
3945
- }
3946
- ky.create = newDefaults => createInstance(validateAndMerge(newDefaults));
3947
- ky.extend = newDefaults => {
3948
- if (typeof newDefaults === 'function') {
3949
- newDefaults = newDefaults(defaults ?? {});
3950
- }
3951
- return createInstance(validateAndMerge(defaults, newDefaults));
3952
- };
3953
- ky.stop = stop;
3954
- return ky;
3955
- };
3956
- const ky = createInstance();
3957
-
3958
- const getText = async (url, options = {}) => {
3959
- try {
3960
- return await ky(url, options).text();
3961
- } catch (error) {
3962
- if (error && error instanceof TypeError && error.message === 'Failed to fetch') {
3963
- throw new VError$1(error, `Failed to request text from "${url}". Make sure that the server is running and has CORS enabled`);
3964
- }
3965
- throw new VError$1(error, `Failed to request text from "${url}"`);
3966
- }
3967
- };
3968
-
3969
- // based on https://github.com/babel/babel/blob/6be6e04f396f03feace4431f709564a8d842163a/packages/babel-code-frame/src/index.ts (License MIT)
3970
-
3971
- /**
3972
- * RegExp to test for newlines in terminal.
3973
- */
3974
-
3975
- const NEWLINE = /\n/;
3976
-
3977
- /**
3978
- * Extract what lines should be marked and highlighted.
3979
- */
3980
- const getMarkerLines = (loc, source, opts) => {
3981
- const startLoc = {
3982
- column: 0,
3983
- line: -1,
3984
- ...loc.start
3985
- };
3986
- const endLoc = {
3987
- ...startLoc,
3988
- ...loc.end
3989
- };
3990
- const {
3991
- linesAbove = 2,
3992
- linesBelow = 3
3993
- } = opts || {};
3994
- const startLine = startLoc.line;
3995
- const startColumn = startLoc.column;
3996
- const endLine = endLoc.line;
3997
- const endColumn = endLoc.column;
3998
- let start = Math.max(startLine - (linesAbove + 1), 0);
3999
- let end = Math.min(source.length, endLine + linesBelow);
4000
- if (startLine === -1) {
4001
- start = 0;
4002
- }
4003
- if (endLine === -1) {
4004
- end = source.length;
4005
- }
4006
- const lineDiff = endLine - startLine;
4007
- const markerLines = {};
4008
- if (lineDiff) {
4009
- for (let i = 0; i <= lineDiff; i++) {
4010
- const lineNumber = i + startLine;
4011
- if (!startColumn) {
4012
- markerLines[lineNumber] = true;
4013
- } else if (i === 0) {
4014
- const sourceLength = source[lineNumber - 1].length;
4015
- markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
4016
- } else if (i === lineDiff) {
4017
- markerLines[lineNumber] = [0, endColumn];
4018
- } else {
4019
- const sourceLength = source[lineNumber - i].length;
4020
- markerLines[lineNumber] = [0, sourceLength];
4021
- }
4022
- }
4023
- } else if (startColumn === endColumn) {
4024
- if (startColumn) {
4025
- markerLines[startLine] = [startColumn, 0];
4026
- } else {
4027
- markerLines[startLine] = true;
4028
- }
4029
- } else {
4030
- markerLines[startLine] = [startColumn, endColumn - startColumn];
4031
- }
4032
- return {
4033
- start,
4034
- end,
4035
- markerLines
4036
- };
4037
- };
4038
- const create$5 = (rawLines, loc, opts = {}) => {
4039
- const lines = rawLines.split(NEWLINE);
4040
- const {
4041
- start,
4042
- end,
4043
- markerLines
4044
- } = getMarkerLines(loc, lines, opts);
4045
- const hasColumns = loc.start && typeof loc.start.column === 'number';
4046
- const numberMaxWidth = String(end).length;
4047
- let frame = rawLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
4048
- const number = start + 1 + index;
4049
- const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
4050
- const gutter = ` ${paddedNumber} |`;
4051
- const hasMarker = markerLines[number];
4052
- const lastMarkerLine = !markerLines[number + 1];
4053
- if (hasMarker) {
4054
- let markerLine = '';
4055
- if (Array.isArray(hasMarker)) {
4056
- const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, ' ');
4057
- const numberOfMarkers = hasMarker[1] || 1;
4058
- markerLine = ['\n ', gutter.replace(/\d/g, ' '), ' ', markerSpacing, '^'.repeat(numberOfMarkers)].join('');
4059
-
4060
- // @ts-ignore
4061
- if (lastMarkerLine && opts.message) {
4062
- // @ts-ignore
4063
- markerLine += ' ' + opts.message;
4064
- }
4065
- }
4066
- return ['>', gutter, line.length > 0 ? ` ${line}` : '', markerLine].join('');
4067
- }
4068
- return ` ${gutter}${line.length > 0 ? ` ${line}` : ''}`;
4069
- }).join('\n');
4070
-
4071
- // @ts-ignore
4072
- if (opts.message && !hasColumns) {
4073
- // @ts-ignore
4074
- frame = `${' '.repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
4075
- }
4076
- return frame;
4077
- };
4078
-
4079
- const joinLines = lines => {
4080
- return lines.join('\n');
4081
- };
4082
-
4083
- const splitLines = lines => {
4084
- return lines.split('\n');
4085
- };
4086
-
4087
- const getErrorMessage = error => {
4088
- if (!error) {
4089
- return `Error: ${error}`;
4090
- }
4091
- let message = error.message;
4092
- while (error.cause) {
4093
- error = error.cause;
4094
- message += `: ${error}`;
4095
- }
4096
- return message;
4097
- };
4098
- const prepareErrorMessageWithCodeFrame = error => {
4099
- if (!error) {
4100
- return {
4101
- message: error,
4102
- stack: undefined,
4103
- codeFrame: undefined,
4104
- type: 'Error'
4105
- };
4106
- }
4107
- const message = getErrorMessage(error);
4108
- if (error.codeFrame) {
4109
- return {
4110
- message,
4111
- stack: error.stack,
4112
- codeFrame: error.codeFrame,
4113
- type: error.constructor.name
4114
- };
4115
- }
4116
- return {
4117
- message,
4118
- stack: error.originalStack,
4119
- codeFrame: error.originalCodeFrame,
4120
- category: error.category,
4121
- stderr: error.stderr
4122
- };
4123
- };
4124
- const RE_PATH_1 = /\((.*):(\d+):(\d+)\)$/;
4125
- const RE_PATH_2 = /at (.*):(\d+):(\d+)$/;
4126
-
4127
- /**
4128
- *
4129
- * @param {readonly string[]} lines
4130
- * @returns
4131
- */
4132
- const getFile = lines => {
4133
- for (const line of lines) {
4134
- if (RE_PATH_1.test(line) || RE_PATH_2.test(line)) {
4135
- return line;
4136
- }
4137
- }
4138
- return '';
4139
- };
4140
- const prepareErrorMessageWithoutCodeFrame = async error => {
4141
- try {
4142
- const lines = splitLines(error.stack);
4143
- const file = getFile(lines);
4144
- let match = file.match(RE_PATH_1);
4145
- if (!match) {
4146
- match = file.match(RE_PATH_2);
4147
- }
4148
- if (!match) {
4149
- return error;
4150
- }
4151
- const [_, path, line, column] = match;
4152
- const text = await getText(path);
4153
- const parsedLine = Number.parseInt(line);
4154
- const parsedColumn = Number.parseInt(column);
4155
- const codeFrame = create$5(text, {
4156
- start: {
4157
- line: parsedLine,
4158
- column: parsedColumn
4159
- },
4160
- end: {
4161
- line: parsedLine,
4162
- column: parsedColumn
4163
- }
4164
- });
4165
- const relevantStack = joinLines(lines.slice(1));
4166
- const message = getErrorMessage(error);
4167
- return {
4168
- message,
4169
- codeFrame,
4170
- stack: relevantStack,
4171
- type: error.constructor.name
4172
- };
4173
- } catch (otherError) {
4174
- console.warn('ErrorHandling Error');
4175
- console.warn(otherError);
4176
- return error;
4177
- }
4178
- };
4179
- const prepare = async error => {
4180
- if (error && error.message && error.codeFrame) {
4181
- return prepareErrorMessageWithCodeFrame(error);
4182
- }
4183
- if (error && error.stack) {
4184
- return prepareErrorMessageWithoutCodeFrame(error);
4185
- }
4186
- return error;
4187
- };
4188
- const print = error => {
4189
- if (error && error.type && error.message && error.codeFrame) {
4190
- return `${error.type}: ${error.message}\n\n${error.codeFrame}\n\n${error.stack}`;
4191
- }
4192
- if (error && error.message && error.codeFrame) {
4193
- return `${error.message}\n\n${error.codeFrame}\n\n${error.stack}`;
4194
- }
4195
- if (error && error.type && error.message) {
4196
- return `${error.type}: ${error.message}\n${error.stack}`;
4197
- }
4198
- if (error && error.stack) {
4199
- return `${error.stack}`;
4200
- }
4201
- if (error === null) {
4202
- return null;
4203
- }
4204
- return `${error}`;
4205
- };
4206
-
4207
- const logError = async error => {
4208
- const prettyError = await prepare(error);
4209
- const prettyErrorString = print(prettyError);
4210
- console.error(prettyErrorString);
4211
- return prettyError;
4212
- };
4213
- const handleError = async error => {
4214
- try {
4215
- await logError(error);
4216
- } catch (otherError) {
4217
- console.warn('ErrorHandling error');
4218
- console.warn(otherError);
4219
- console.error(error);
4220
- }
4221
- };
4222
-
4223
- /**
4224
- * @param {PromiseRejectionEvent} event
4225
- */
4226
- const handleUnhandledRejection = async event => {
4227
- try {
4228
- event.preventDefault();
4229
- await handleError(event.reason);
4230
- } catch {
4231
- console.error(event.reason);
4232
- }
4233
- };
4234
-
4235
- /**
4236
- * @param {ErrorEvent} event
4237
- */
4238
- const handleUnhandledError = async event => {
4239
- try {
4240
- event.preventDefault();
4241
- await handleError(event.error);
4242
- } catch {
4243
- console.error(event.error);
4244
- }
4245
- };
4246
-
4247
- const handleContentSecurityPolicyViolation = event => {
4248
- const {
4249
- violatedDirective,
4250
- sourceFile,
4251
- lineNumber,
4252
- columnNumber
4253
- } = event;
4254
- addError({
4255
- violatedDirective,
4256
- sourceFile,
4257
- lineNumber,
4258
- columnNumber
4259
- });
2207
+
2208
+ const handleContentSecurityPolicyViolation = event => {
4260
2209
  };
4261
2210
 
4262
2211
  const listen = async ({
@@ -4288,7 +2237,7 @@ const main = async () => {
4288
2237
  }
4289
2238
  globalThis.vscode = api;
4290
2239
  // @ts-ignore
4291
- state$7.getFn = getFn;
2240
+ undefined.getFn = undefined;
4292
2241
  const ipc = await listen({
4293
2242
  method: Auto()
4294
2243
  });
@@ -4306,17 +2255,11 @@ const withResolvers = () => {
4306
2255
  * @type {any}
4307
2256
  */
4308
2257
  let _resolve;
4309
- /**
4310
- * @type {any}
4311
- */
4312
- let _reject;
4313
- const promise = new Promise((resolve, reject) => {
2258
+ const promise = new Promise(resolve => {
4314
2259
  _resolve = resolve;
4315
- _reject = reject;
4316
2260
  });
4317
2261
  return {
4318
2262
  resolve: _resolve,
4319
- reject: _reject,
4320
2263
  promise
4321
2264
  };
4322
2265
  };
@@ -4547,105 +2490,15 @@ const IpcParentWithModuleWorkerAndWorkaroundForChromeDevtoolsBug = {
4547
2490
  wrap: wrap$1
4548
2491
  };
4549
2492
 
4550
- const MethodNotFound = -32601;
4551
-
4552
- const Two = '2.0';
4553
-
4554
- class NonError extends Error {
4555
- constructor(message) {
4556
- super(message);
4557
- this.name = 'NonError';
4558
- }
4559
- }
4560
-
4561
- // ensureError based on https://github.com/sindresorhus/ensure-error/blob/main/index.ts (License MIT)
4562
- const ensureError = input => {
4563
- if (!(input instanceof Error)) {
4564
- return new NonError(input);
4565
- }
4566
- return input;
4567
- };
4568
-
4569
- const serializeError = error => {
4570
- error = ensureError(error);
4571
- return {
4572
- stack: error.stack,
4573
- message: error.message,
4574
- name: error.name,
4575
- type: error.constructor.name,
4576
- codeFrame: error.codeFrame || ''
4577
- };
4578
- };
4579
-
4580
- const getErrorResponse = (message, error) => {
4581
- if (error && error instanceof CommandNotFoundError) {
4582
- return {
4583
- jsonrpc: Two,
4584
- id: message.id,
4585
- error: {
4586
- code: MethodNotFound,
4587
- message: error.message,
4588
- data: error.stack
4589
- }
4590
- };
4591
- }
4592
- const serializedError = serializeError(error);
4593
- return {
4594
- jsonrpc: Two,
4595
- id: message.id,
4596
- error: {
4597
- codeFrame: serializedError.codeFrame,
4598
- message: serializedError.message,
4599
- stack: serializedError.stack,
4600
- name: serializedError.name,
4601
- type: serializedError.type
4602
- }
4603
- };
4604
- };
4605
-
4606
- const getSuccessResponse = (message, result) => {
4607
- return {
4608
- jsonrpc: Two,
4609
- id: message.id,
4610
- result
4611
- };
2493
+ const preparePrettyError = error => {
2494
+ return error;
4612
2495
  };
4613
-
4614
- const getResponse = async (message, execute) => {
4615
- try {
4616
- const result = await execute(message.method, ...message.params);
4617
- return getSuccessResponse(message, result);
4618
- } catch (error) {
4619
- return getErrorResponse(message, error);
4620
- }
2496
+ const logError = error => {
2497
+ // handled by renderer worker
4621
2498
  };
4622
-
4623
- class JsonRpcError extends Error {
4624
- constructor(message) {
4625
- super(message);
4626
- this.name = 'JsonRpcError';
4627
- }
4628
- }
4629
-
4630
- const handleJsonRpcMessage = async (ipc, message, execute, resolve) => {
4631
- if ('id' in message) {
4632
- if ('method' in message) {
4633
- const response = await getResponse(message, execute);
4634
- try {
4635
- ipc.send(response);
4636
- } catch (error) {
4637
- await logError(error);
4638
- const errorResponse = getErrorResponse(message, error);
4639
- ipc.send(errorResponse);
4640
- }
4641
- return;
4642
- }
4643
- resolve(message.id, message);
4644
- return;
4645
- }
4646
- throw new JsonRpcError('unexpected message from renderer worker');
2499
+ const requiresSocket = () => {
2500
+ return false;
4647
2501
  };
4648
-
4649
2502
  const create$1 = ({
4650
2503
  ipc,
4651
2504
  execute
@@ -4653,7 +2506,7 @@ const create$1 = ({
4653
2506
  object(ipc);
4654
2507
  fn(execute);
4655
2508
  const handleMessage = async message => {
4656
- return handleJsonRpcMessage(ipc, message, execute, resolve);
2509
+ return handleJsonRpcMessage(ipc, message, execute, resolve, preparePrettyError, logError, requiresSocket);
4657
2510
  };
4658
2511
  ipc.onmessage = handleMessage;
4659
2512
  return {