Atlas › Test

userDataSyncService.test|title=UserDataSyncService test delete and sync|occurrence=1

Exact test identity: mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/userDataSync/test/common/userDataSyncService.test|title=UserDataSyncService test delete and sync|occurrence=1

Package
mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/userDataSync/test/common
Suite / test hierarchy
userDataSyncService.test|title=UserDataSyncService test delete and sync|occurrence=1
Test
userDataSyncService.test|title=UserDataSyncService test delete and sync|occurrence=1
Introduced at
userDataSyncService.test|title=UserDataSyncService test delete and sync|occurrence=1 Frontier kind: Test frontier
Covered ranges
4750
Covered lines
27941
Covered files
133

Covered source

Expand a file to inspect source; the > gutter marks covered lines.

src/vs/base/common/async.ts 1434 covered LOC · 255 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- async.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken, CancellationTokenSource } from './cancellation.js';
7 > import { BugIndicatingError, CancellationError, isCancellationError } from './errors.js';
8 > import { Emitter, Event } from './event.js';
9 > import { Disposable, DisposableMap, DisposableStore, IDisposable, isDisposable, MutableDisposable, toDisposable } from './lifecycle.js';
10 > import { extUri as defaultExtUri, IExtUri } from './resources.js';
11 > import { URI } from './uri.js';
12 > import { setTimeout0 } from './platform.js';
13 > import { MicrotaskDelay } from './symbols.js';
14 > import { Lazy } from './lazy.js';
15 >
16 > export function isThenable<T>(obj: unknown): obj is Promise<T> {
17 return !!obj && typeof (obj as unknown as Promise<T>).then === 'function';
18 }
19 > async.ts
20 > export interface CancelablePromise<T> extends Promise<T> {
21 > cancel(): void;
22 > }
23 >
24 > /**
25 > * Returns a promise that can be cancelled using the provided cancellation token.
26 > *
27 > * @remarks When cancellation is requested, the promise will be rejected with a {@link CancellationError}.
28 > * If the promise resolves to a disposable object, it will be automatically disposed when cancellation
29 > * is requested.
30 > *
31 > * @param callback A function that accepts a cancellation token and returns a promise
32 > * @returns A promise that can be cancelled
33 > */
34 > export function createCancelablePromise<T>(callback: (token: CancellationToken) => Promise<T>): CancelablePromise<T> {
35 > const source = new CancellationTokenSource(); async.ts
36 >
37 > const thenable = callback(source.token);
38 >
39 > let isCancelled = false;
40 >
41 > const promise = new Promise<T>((resolve, reject) => {
42 > const subscription = source.token.onCancellationRequested(() => {
43 isCancelled = true;
44 subscription.dispose();
45 reject(new CancellationError());
46 > }); async.ts
47 > Promise.resolve(thenable).then(value => {
48 > subscription.dispose(); async.ts
49 > source.dispose();
50 >
51 > if (!isCancelled) {
52 > resolve(value); async.ts
53 >
54 > } else if (isDisposable(value)) { async.ts
55 // promise has been cancelled, result is disposable and will
56 // be cleaned up
57 value.dispose();
58 }
59 > }, err => { async.ts
60 subscription.dispose();
61 source.dispose();
62 reject(err);
63 > }); async.ts
64 > });
65 >
66 > return <CancelablePromise<T>>new class {
67 > cancel() {
68 source.cancel();
69 source.dispose();
70 }
71 > then<TResult1 = T, TResult2 = never>(resolve?: ((value: T) => TResult1 | Promise<TResult1>) | undefined | null, reject?: ((reason: unknown) => TResult2 | Promise<TResult2>) | undefined | null): Promise<TResult1 | TResult2> { async.ts
72 > return promise.then(resolve, reject);
73 > }
74 > catch<TResult = never>(reject?: ((reason: unknown) => TResult | Promise<TResult>) | undefined | null): Promise<T | TResult> {
75 return this.then(undefined, reject);
76 }
77 > finally(onfinally?: (() => void) | undefined | null): Promise<T> { async.ts
78 > return promise.finally(onfinally); async.ts
79 > }
80 > }; async.ts
81 > }
82 > async.ts
83 > /**
84 > * Returns a promise that resolves with `undefined` as soon as the passed token is cancelled.
85 > * @see {@link raceCancellationError}
86 > */
87 > export function raceCancellation<T>(promise: Promise<T>, token: CancellationToken): Promise<T | undefined>;
88 >
89 > /**
90 > * Returns a promise that resolves with `defaultValue` as soon as the passed token is cancelled.
91 > * @see {@link raceCancellationError}
92 > */
93 > export function raceCancellation<T>(promise: Promise<T>, token: CancellationToken, defaultValue: T): Promise<T>;
94 >
95 > export function raceCancellation<T>(promise: Promise<T>, token: CancellationToken, defaultValue?: T): Promise<T | undefined> {
96 return new Promise((resolve, reject) => {
97 const ref = token.onCancellationRequested(() => {
102 });
103 }
104 > async.ts
105 > /**
106 > * Returns a promise that rejects with an {@CancellationError} as soon as the passed token is cancelled.
107 > * @see {@link raceCancellation}
108 > */
109 > export function raceCancellationError<T>(promise: Promise<T>, token: CancellationToken): Promise<T> {
110 return new Promise((resolve, reject) => {
111 const ref = token.onCancellationRequested(() => {
116 });
117 }
118 > async.ts
119 > export function rejectIfNotCanceled(err: unknown): undefined {
120 if (isCancellationError(err)) {
121 return undefined;
123 return Promise.reject(err) as never;
124 }
125 > async.ts
126 > /**
127 > * Wraps a cancellable promise such that it is no cancellable. Can be used to
128 > * avoid issues with shared promises that would normally be returned as
129 > * cancellable to consumers.
130 > */
131 > export function notCancellablePromise<T>(promise: CancelablePromise<T>): Promise<T> {
132 return new Promise<T>((resolve, reject) => {
133 promise.then(resolve, reject);
134 });
135 }
136 > async.ts
137 > /**
138 > * Returns as soon as one of the promises resolves or rejects and cancels remaining promises
139 > */
140 > export function raceCancellablePromises<T>(cancellablePromises: (CancelablePromise<T> | Promise<T>)[]): CancelablePromise<T> {
141 let resolvedPromiseIndex = -1;
142 const promises = cancellablePromises.map((promise, index) => promise.then(result => { resolvedPromiseIndex = index; return result; }));
154 return promise;
155 }
156 > async.ts
157 > export function raceTimeout<T>(promise: Promise<T>, timeout: number, onTimeout?: () => void): Promise<T | undefined> {
158 let promiseResolve: ((value: T | undefined) => void) | undefined = undefined;
159
168 ]);
169 }
170 > async.ts
171 > export function asPromise<T>(callback: () => T | Thenable<T>): Promise<T> {
172 return new Promise<T>((resolve, reject) => {
173 const item = callback();
179 });
180 }
181 > async.ts
182 > /**
183 > * Creates and returns a new promise, plus its `resolve` and `reject` callbacks.
184 > *
185 > * Replace with standardized [`Promise.withResolvers`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers) once it is supported
186 > */
187 > export function promiseWithResolvers<T>(): { promise: Promise<T>; resolve: (value: T | PromiseLike<T>) => void; reject: (err?: any) => void } {
188 let resolve: (value: T | PromiseLike<T>) => void;
189 let reject: (reason?: any) => void;
194 return { promise, resolve: resolve!, reject: reject! };
195 }
196 > async.ts
197 > export interface ITask<T> {
198 > (): T;
199 > }
200 >
201 > export interface ICancellableTask<T> {
202 > (token: CancellationToken): T;
203 > }
204 >
205 > /**
206 > * A helper to prevent accumulation of sequential async tasks.
207 > *
208 > * Imagine a mail man with the sole task of delivering letters. As soon as
209 > * a letter submitted for delivery, he drives to the destination, delivers it
210 > * and returns to his base. Imagine that during the trip, N more letters were submitted.
211 > * When the mail man returns, he picks those N letters and delivers them all in a
212 > * single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
213 > *
214 > * The throttler implements this via the queue() method, by providing it a task
215 > * factory. Following the example:
216 > *
217 > * const throttler = new Throttler();
218 > * const letters = [];
219 > *
220 > * function deliver() {
221 > * const lettersToDeliver = letters;
222 > * letters = [];
223 > * return makeTheTrip(lettersToDeliver);
224 > * }
225 > *
226 > * function onLetterReceived(l) {
227 > * letters.push(l);
228 > * throttler.queue(deliver);
229 > * }
230 > */
231 > export class Throttler implements IDisposable {
232 >
233 > private activePromise: Promise<any> | null;
234 > private queuedPromise: Promise<any> | null;
235 > private queuedPromiseFactory: ICancellableTask<Promise<any>> | null;
236 > private cancellationTokenSource: CancellationTokenSource;
237 >
238 > constructor() {
239 > this.activePromise = null; async.ts
240 > this.queuedPromise = null;
241 > this.queuedPromiseFactory = null;
242 >
243 > this.cancellationTokenSource = new CancellationTokenSource();
244 > }
245 > async.ts
246 > queue<T>(promiseFactory: ICancellableTask<Promise<T>>): Promise<T> {
247 if (this.cancellationTokenSource.token.isCancellationRequested) {
248 return Promise.reject(new Error('Throttler is disposed'));
288 });
289 }
290 > async.ts
291 > dispose(): void {
292 > this.cancellationTokenSource.cancel(); async.ts
293 > }
294 > } async.ts
295 >
296 > export class Sequencer {
297
298 private current: Promise<unknown> = Promise.resolve(null);
299 > async.ts
300 > queue<T>(promiseTask: ITask<Promise<T>>): Promise<T> {
301 return this.current = this.current.then(() => promiseTask(), () => promiseTask());
302 }
303 > } async.ts
304 >
305 > /**
306 > * A {@link Throttler} per key. Calls for the same key coalesce (only the most
307 > * recently queued task runs after the active one settles); calls for different
308 > * keys are independent. Idle keys are cleaned up automatically.
309 > */
310 > export class ThrottlerByKey<TKey> implements IDisposable {
311
312 private readonly throttlers = new Map<TKey, { throttler: Throttler; count: number }>();
313 > async.ts
314 > queue<T>(key: TKey, task: ITask<Promise<T>>): Promise<T> {
315 let entry = this.throttlers.get(key);
316 if (!entry) {
327 });
328 }
329 > async.ts
330 > dispose(): void {
331 for (const { throttler } of this.throttlers.values()) {
332 throttler.dispose();
334 this.throttlers.clear();
335 }
336 > } async.ts
337 >
338 > export class SequencerByKey<TKey> {
339
340 private promiseMap = new Map<TKey, Promise<unknown>>();
341 > async.ts
342 > queue<T>(key: TKey, promiseTask: ITask<Promise<T>>): Promise<T> {
343 const runningPromise = this.promiseMap.get(key) ?? Promise.resolve();
344 const newPromise = runningPromise
353 return newPromise;
354 }
355 > async.ts
356 > peek(key: TKey): Promise<unknown> | undefined {
357 return this.promiseMap.get(key) || undefined;
358 }
359 > async.ts
360 > keys(): IterableIterator<TKey> {
361 return this.promiseMap.keys();
362 }
363 > } async.ts
364 >
365 > interface IScheduledLater extends IDisposable {
366 > isTriggered(): boolean;
367 > }
368 >
369 > const timeoutDeferred = (timeout: number, fn: () => void): IScheduledLater => {
370 let scheduled = true;
371 const handle = setTimeout(() => {
381 };
382 };
383 > async.ts
384 > const microtaskDeferred = (fn: () => void): IScheduledLater => {
385 let scheduled = true;
386 queueMicrotask(() => {
396 };
397 };
398 > async.ts
399 > /**
400 > * A helper to delay (debounce) execution of a task that is being requested often.
401 > *
402 > * Following the throttler, now imagine the mail man wants to optimize the number of
403 > * trips proactively. The trip itself can be long, so he decides not to make the trip
404 > * as soon as a letter is submitted. Instead he waits a while, in case more
405 > * letters are submitted. After said waiting period, if no letters were submitted, he
406 > * decides to make the trip. Imagine that N more letters were submitted after the first
407 > * one, all within a short period of time between each other. Even though N+1
408 > * submissions occurred, only 1 delivery was made.
409 > *
410 > * The delayer offers this behavior via the trigger() method, into which both the task
411 > * to be executed and the waiting period (delay) must be passed in as arguments. Following
412 > * the example:
413 > *
414 > * const delayer = new Delayer(WAITING_PERIOD);
415 > * const letters = [];
416 > *
417 > * function letterReceived(l) {
418 > * letters.push(l);
419 > * delayer.trigger(() => { return makeTheTrip(); });
420 > * }
421 > */
422 > export class Delayer<T> implements IDisposable {
423 >
424 > private deferred: IScheduledLater | null;
425 > private completionPromise: Promise<any> | null;
426 > private doResolve: ((value?: any | Promise<any>) => void) | null;
427 > private doReject: ((err: unknown) => void) | null;
428 > private task: ITask<T | Promise<T>> | null;
429 >
430 > constructor(public defaultDelay: number | typeof MicrotaskDelay) {
431 > this.deferred = null; async.ts
432 > this.completionPromise = null;
433 > this.doResolve = null;
434 > this.doReject = null;
435 > this.task = null;
436 > }
437 > async.ts
438 > trigger(task: ITask<T | Promise<T>>, delay = this.defaultDelay): Promise<T> {
439 this.task = task;
440 this.cancelTimeout();
465 return this.completionPromise;
466 }
467 > async.ts
468 > isTriggered(): boolean {
469 return !!this.deferred?.isTriggered();
470 }
471 > async.ts
472 > cancel(): void {
473 > this.cancelTimeout(); async.ts
474 >
475 > if (this.completionPromise) {
476 this.doReject?.(new CancellationError());
477 this.completionPromise = null;
478 }
479 > } async.ts
480 > async.ts
481 > private cancelTimeout(): void {
482 > this.deferred?.dispose(); async.ts
483 > this.deferred = null;
484 > }
485 > async.ts
486 > dispose(): void {
487 > this.cancel(); async.ts
488 > }
489 > } async.ts
490 >
491 > /**
492 > * A helper to delay execution of a task that is being requested often, while
493 > * preventing accumulation of consecutive executions, while the task runs.
494 > *
495 > * The mail man is clever and waits for a certain amount of time, before going
496 > * out to deliver letters. While the mail man is going out, more letters arrive
497 > * and can only be delivered once he is back. Once he is back the mail man will
498 > * do one more trip to deliver the letters that have accumulated while he was out.
499 > */
500 > export class ThrottledDelayer<T> {
501 >
502 > private delayer: Delayer<Promise<T>>;
503 > private throttler: Throttler;
504 >
505 > constructor(defaultDelay: number) {
506 > this.delayer = new Delayer(defaultDelay); async.ts
507 > this.throttler = new Throttler();
508 > }
509 > async.ts
510 > trigger(promiseFactory: ICancellableTask<Promise<T>>, delay?: number): Promise<T> {
511 return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay) as unknown as Promise<T>;
512 }
513 > async.ts
514 > isTriggered(): boolean {
515 return this.delayer.isTriggered();
516 }
517 > async.ts
518 > cancel(): void {
519 this.delayer.cancel();
520 }
521 > async.ts
522 > dispose(): void {
523 > this.delayer.dispose(); async.ts
524 > this.throttler.dispose();
525 > }
526 > } async.ts
527 >
528 > /**
529 > * A barrier that is initially closed and then becomes opened permanently.
530 > */
531 > export class Barrier {
532 > private _isOpen: boolean;
533 > private _promise: Promise<boolean>;
534 > private _completePromise!: (v: boolean) => void;
535 >
536 > constructor() {
537 this._isOpen = false;
538 this._promise = new Promise<boolean>((c, e) => {
540 });
541 }
542 > async.ts
543 > isOpen(): boolean {
544 return this._isOpen;
545 }
546 > async.ts
547 > open(): void {
548 this._isOpen = true;
549 this._completePromise(true);
550 }
551 > async.ts
552 > wait(): Promise<boolean> {
553 return this._promise;
554 }
555 > } async.ts
556 >
557 > /**
558 > * A barrier that is initially closed and then becomes opened permanently after a certain period of
559 > * time or when open is called explicitly
560 > */
561 > export class AutoOpenBarrier extends Barrier {
562 >
563 > private readonly _timeout: Timeout;
564 >
565 > constructor(autoOpenTimeMs: number) {
566 super();
567 this._timeout = setTimeout(() => this.open(), autoOpenTimeMs);
568 }
569 > async.ts
570 > override open(): void {
571 clearTimeout(this._timeout);
572 super.open();
573 }
574 > } async.ts
575 >
576 > export function timeout(millis: number): CancelablePromise<void>;
577 > export function timeout(millis: number, token: CancellationToken): Promise<void>;
578 > export function timeout(millis: number, token?: CancellationToken): CancelablePromise<void> | Promise<void> {
579 if (!token) {
580 return createCancelablePromise(token => timeout(millis, token));
593 });
594 }
595 > async.ts
596 > /**
597 > * Creates a timeout that can be disposed using its returned value.
598 > * @param handler The timeout handler.
599 > * @param timeout An optional timeout in milliseconds.
600 > * @param store An optional {@link DisposableStore} that will have the timeout disposable managed automatically.
601 > *
602 > * @example
603 > * const store = new DisposableStore;
604 > * // Call the timeout after 1000ms at which point it will be automatically
605 > * // evicted from the store.
606 > * const timeoutDisposable = disposableTimeout(() => {}, 1000, store);
607 > *
608 > * if (foo) {
609 > * // Cancel the timeout and evict it from store.
610 > * timeoutDisposable.dispose();
611 > * }
612 > */
613 > export function disposableTimeout(handler: () => void, timeout = 0, store?: DisposableStore): IDisposable {
614 const timer = setTimeout(() => {
615 handler();
625 return disposable;
626 }
627 > async.ts
628 > /**
629 > * The largest delay (in milliseconds) a single `setTimeout` can represent.
630 > * Larger values overflow its internal 32-bit signed integer and fire (almost)
631 > * immediately instead of waiting.
632 > */
633 > export const MAX_TIMEOUT_DELAY = 2 ** 31 - 1; // ~24.8 days
634 >
635 > /**
636 > * Like {@link disposableTimeout}, but supports delays larger than
637 > * {@link MAX_TIMEOUT_DELAY} (~24.8 days), which a single `setTimeout` cannot
638 > * represent. The wait is split into chunks and re-armed until the target time is
639 > * reached, so the handler fires at approximately `Date.now() + timeout`.
640 > *
641 > * Note: like `setTimeout`, firing is best-effort and may drift across system
642 > * sleep or wall-clock changes; do not rely on it for precise scheduling.
643 > *
644 > * @param handler The timeout handler.
645 > * @param timeout The timeout in milliseconds. May exceed {@link MAX_TIMEOUT_DELAY}.
646 > * @param store An optional {@link DisposableStore} that will have the timeout disposable managed automatically.
647 > */
648 > export function disposableLongTimeout(handler: () => void, timeout: number, store?: DisposableStore): IDisposable {
649 const target = Date.now() + timeout;
650 let timer: Timeout;
671 return disposable;
672 }
673 > async.ts
674 > /**
675 > * Runs the provided list of promise factories in sequential order. The returned
676 > * promise will complete to an array of results from each promise.
677 > */
678 >
679 > export function sequence<T>(promiseFactories: ITask<Promise<T>>[]): Promise<T[]> {
680 const results: T[] = [];
681 let index = 0;
701 return Promise.resolve(null).then(thenHandler);
702 }
703 > async.ts
704 > export function first<T>(promiseFactories: ITask<Promise<T>>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T | null = null): Promise<T | null> {
705 let index = 0;
706 const len = promiseFactories.length;
725 return loop();
726 }
727 > async.ts
728 > /**
729 > * Returns the result of the first promise that matches the "shouldStop",
730 > * running all promises in parallel. Supports cancelable promises.
731 > */
732 > export function firstParallel<T>(promiseList: Promise<T>[], shouldStop?: (t: T) => boolean, defaultValue?: T | null): Promise<T | null>;
733 > export function firstParallel<T, R extends T>(promiseList: Promise<T>[], shouldStop: (t: T) => t is R, defaultValue?: R | null): Promise<R | null>;
734 > export function firstParallel<T>(promiseList: Promise<T>[], shouldStop: (t: T) => boolean = t => !!t, defaultValue: T | null = null) {
735 if (promiseList.length === 0) {
736 return Promise.resolve(defaultValue);
764 });
765 }
766 > async.ts
767 > interface ILimitedTaskFactory<T> {
768 > factory: ITask<Promise<T>>;
769 > c: (value: T | Promise<T>) => void;
770 > e: (error?: unknown) => void;
771 > }
772 >
773 > export interface ILimiter<T> {
774 >
775 > readonly size: number;
776 >
777 > queue(factory: ITask<Promise<T>>): Promise<T>;
778 >
779 > clear(): void;
780 > }
781 >
782 > /**
783 > * A helper to queue N promises and run them all with a max degree of parallelism. The helper
784 > * ensures that at any time no more than M promises are running at the same time.
785 > */
786 > export class Limiter<T> implements ILimiter<T> {
787 >
788 > private _size = 0;
789 > private _isDisposed = false;
790 > private runningPromises: number;
791 > private readonly maxDegreeOfParalellism: number;
792 > private readonly outstandingPromises: ILimitedTaskFactory<T>[];
793 > private readonly _onDrained: Emitter<void>;
794 >
795 > constructor(maxDegreeOfParalellism: number) {
796 > this.maxDegreeOfParalellism = maxDegreeOfParalellism; async.ts
797 > this.outstandingPromises = [];
798 > this.runningPromises = 0;
799 > this._onDrained = new Emitter<void>();
800 > }
801 > async.ts
802 > /**
803 > *
804 > * @returns A promise that resolved when all work is done (onDrained) or when
805 > * there is nothing to do
806 > */
807 > whenIdle(): Promise<void> {
808 return this.size > 0
809 ? Event.toPromise(this.onDrained)
810 : Promise.resolve();
811 }
812 > async.ts
813 > get onDrained(): Event<void> {
814 > return this._onDrained.event; async.ts
815 > }
816 > async.ts
817 > get size(): number {
818 return this._size;
819 }
820 > async.ts
821 > queue(factory: ITask<Promise<T>>): Promise<T> {
822 > if (this._isDisposed) { async.ts
823 throw new Error('Object has been disposed');
824 }
825 > this._size++; async.ts
826 >
827 > return new Promise<T>((c, e) => {
828 > this.outstandingPromises.push({ factory, c, e });
829 > this.consume();
830 > });
831 > }
832 > async.ts
833 > private consume(): void {
834 > while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) { async.ts
835 > const iLimitedTask = this.outstandingPromises.shift()!;
836 > this.runningPromises++;
837 >
838 > const promise = iLimitedTask.factory();
839 > promise.then(iLimitedTask.c, iLimitedTask.e);
840 > promise.then(() => this.consumed(), () => this.consumed());
841 > }
842 > }
843 > async.ts
844 > private consumed(): void {
845 > if (this._isDisposed) { async.ts
846 return;
847 }
848 > this.runningPromises--; async.ts
849 > if (--this._size === 0) {
850 > this._onDrained.fire();
851 > }
852 >
853 > if (this.outstandingPromises.length > 0) {
854 this.consume();
855 }
856 > } async.ts
857 > async.ts
858 > clear(): void {
859 if (this._isDisposed) {
860 throw new Error('Object has been disposed');
863 this._size = this.runningPromises;
864 }
865 > async.ts
866 > dispose(): void {
867 > this._isDisposed = true; async.ts
868 > this.outstandingPromises.length = 0; // stop further processing
869 > this._size = 0;
870 > this._onDrained.dispose();
871 > }
872 > } async.ts
873 >
874 > /**
875 > * A queue is handles one promise at a time and guarantees that at any time only one promise is executing.
876 > */
877 > export class Queue<T> extends Limiter<T> {
878 >
879 > constructor() {
880 > super(1); async.ts
881 > }
882 > } async.ts
883 >
884 > /**
885 > * Same as `Queue`, ensures that only 1 task is executed at the same time. The difference to `Queue` is that
886 > * there is only 1 task about to be scheduled next. As such, calling `queue` while a task is executing will
887 > * replace the currently queued task until it executes.
888 > *
889 > * As such, the returned promise may not be from the factory that is passed in but from the next factory that
890 > * is running after having called `queue`.
891 > */
892 > export class LimitedQueue {
893
894 private readonly sequentializer = new TaskSequentializer();
895
896 private tasks = 0;
897 > async.ts
898 > queue(factory: ITask<Promise<void>>): Promise<void> {
899 if (!this.sequentializer.isRunning()) {
900 return this.sequentializer.run(this.tasks++, factory());
905 });
906 }
907 > } async.ts
908 >
909 > /**
910 > * A helper to organize queues per resource. The ResourceQueue makes sure to manage queues per resource
911 > * by disposing them once the queue is empty.
912 > */
913 > export class ResourceQueue implements IDisposable {
914 > async.ts
915 > private readonly queues = new Map<string, Queue<void>>();
916 >
917 > private readonly drainers = new Set<DeferredPromise<void>>();
918 >
919 > private drainListeners: DisposableMap<number> | undefined = undefined;
920 > private drainListenerCount = 0;
921 > async.ts
922 > async whenDrained(): Promise<void> {
923 if (this.isDrained()) {
924 return;
930 return promise.p;
931 }
932 > async.ts
933 > private isDrained(): boolean {
934 > for (const [, queue] of this.queues) { async.ts
935 if (queue.size > 0) {
936 return false;
937 }
938 }
939 > async.ts
940 > return true;
941 > }
942 > async.ts
943 > queueSize(resource: URI, extUri: IExtUri = defaultExtUri): number {
944 const key = extUri.getComparisonKey(resource);
945
946 return this.queues.get(key)?.size ?? 0;
947 }
948 > async.ts
949 > queueFor(resource: URI, factory: ITask<Promise<void>>, extUri: IExtUri = defaultExtUri): Promise<void> {
950 > const key = extUri.getComparisonKey(resource); async.ts
951 >
952 > let queue = this.queues.get(key);
953 > if (!queue) {
954 > queue = new Queue<void>();
955 > const drainListenerId = this.drainListenerCount++;
956 > const drainListener = Event.once(queue.onDrained)(() => {
957 > queue?.dispose();
958 > this.queues.delete(key);
959 > this.onDidQueueDrain();
960 >
961 > this.drainListeners?.deleteAndDispose(drainListenerId);
962 >
963 > if (this.drainListeners?.size === 0) {
964 > this.drainListeners.dispose();
965 > this.drainListeners = undefined;
966 > }
967 > });
968 >
969 > if (!this.drainListeners) {
970 > this.drainListeners = new DisposableMap();
971 > }
972 > this.drainListeners.set(drainListenerId, drainListener);
973 >
974 > this.queues.set(key, queue);
975 > }
976 >
977 > return queue.queue(factory);
978 > }
979 > async.ts
980 > private onDidQueueDrain(): void {
981 > if (!this.isDrained()) { async.ts
982 return; // not done yet
983 }
984 > async.ts
985 > this.releaseDrainers();
986 > }
987 > async.ts
988 > private releaseDrainers(): void {
989 > for (const drainer of this.drainers) { async.ts
990 drainer.complete();
991 }
992 > async.ts
993 > this.drainers.clear();
994 > }
995 > async.ts
996 > dispose(): void {
997 > for (const [, queue] of this.queues) { async.ts
998 queue.dispose();
999 }
1000 > async.ts
1001 > this.queues.clear();
1002 >
1003 > // Even though we might still have pending
1004 > // tasks queued, after the queues have been
1005 > // disposed, we can no longer track them, so
1006 > // we release drainers to prevent hanging
1007 > // promises when the resource queue is being
1008 > // disposed.
1009 > this.releaseDrainers();
1010 >
1011 > this.drainListeners?.dispose();
1012 > }
1013 > } async.ts
1014 >
1015 > export type Task<T = void> = () => (Promise<T> | T);
1016 >
1017 > /**
1018 > * Wrap a type in an optional promise. This can be useful to avoid the runtime
1019 > * overhead of creating a promise.
1020 > */
1021 > export type MaybePromise<T> = Promise<T> | T;
1022 >
1023 > /**
1024 > * Processes tasks in the order they were scheduled.
1025 > */
1026 > export class TaskQueue {
1027 private _runningTask: Task<any> | undefined = undefined;
1028 private _pendingTasks: { task: Task<any>; deferred: DeferredPromise<any>; setUndefinedWhenCleared: boolean }[] = [];
1029 > async.ts
1030 > /**
1031 > * Waits for the current and pending tasks to finish, then runs and awaits the given task.
1032 > * If the task is skipped because of clearPending, the promise is rejected with a CancellationError.
1033 > */
1034 > public schedule<T>(task: Task<T>): Promise<T> {
1035 const deferred = new DeferredPromise<T>();
1036 this._pendingTasks.push({ task, deferred, setUndefinedWhenCleared: false });
1038 return deferred.p;
1039 }
1040 > async.ts
1041 > /**
1042 > * Waits for the current and pending tasks to finish, then runs and awaits the given task.
1043 > * If the task is skipped because of clearPending, the promise is resolved with undefined.
1044 > */
1045 > public scheduleSkipIfCleared<T>(task: Task<T>): Promise<T | undefined> {
1046 const deferred = new DeferredPromise<T>();
1047 this._pendingTasks.push({ task, deferred, setUndefinedWhenCleared: true });
1049 return deferred.p;
1050 }
1051 > async.ts
1052 > private _runIfNotRunning(): void {
1053 if (this._runningTask === undefined) {
1054 this._processQueue();
1055 }
1056 }
1057 > async.ts
1058 > private async _processQueue(): Promise<void> {
1059 if (this._pendingTasks.length === 0) {
1060 return;
1082 }
1083 }
1084 > async.ts
1085 > /**
1086 > * Clears all pending tasks. Does not cancel the currently running task.
1087 > */
1088 > public clearPending(): void {
1089 const tasks = this._pendingTasks;
1090 this._pendingTasks = [];
1097 }
1098 }
1099 > } async.ts
1100 >
1101 > export class TimeoutTimer implements IDisposable {
1102 > private _token: Timeout | undefined;
1103 > private _isDisposed = false;
1104 >
1105 > constructor();
1106 > constructor(runner: () => void, timeout: number);
1107 > constructor(runner?: () => void, timeout?: number) {
1108 this._token = undefined;
1109
1112 }
1113 }
1114 > async.ts
1115 > dispose(): void {
1116 this.cancel();
1117 this._isDisposed = true;
1118 }
1119 > async.ts
1120 > cancel(): void {
1121 if (this._token !== undefined) {
1122 clearTimeout(this._token);
1124 }
1125 }
1126 > async.ts
1127 > cancelAndSet(runner: () => void, timeout: number): void {
1128 if (this._isDisposed) {
1129 throw new BugIndicatingError(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);
1136 }, timeout);
1137 }
1138 > async.ts
1139 > setIfNotSet(runner: () => void, timeout: number): void {
1140 if (this._isDisposed) {
1141 throw new BugIndicatingError(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);
1151 }, timeout);
1152 }
1153 > } async.ts
1154 >
1155 > export class IntervalTimer implements IDisposable {
1156
1157 private disposable: IDisposable | undefined = undefined;
1158 private isDisposed = false;
1159 > async.ts
1160 > cancel(): void {
1161 this.disposable?.dispose();
1162 this.disposable = undefined;
1163 }
1164 > async.ts
1165 > cancelAndSet(runner: () => void, interval: number, context = globalThis): void {
1166 if (this.isDisposed) {
1167 throw new BugIndicatingError(`Calling 'cancelAndSet' on a disposed IntervalTimer`);
1178 });
1179 }
1180 > async.ts
1181 > dispose(): void {
1182 this.cancel();
1183 this.isDisposed = true;
1184 }
1185 > } async.ts
1186 >
1187 > export class RunOnceScheduler<Runner extends (...args: any[]) => any = () => any> implements IDisposable {
1188 >
1189 > protected runner: Runner | null;
1190 >
1191 > private timeoutToken: Timeout | undefined;
1192 > private timeout: number;
1193 > private timeoutHandler: () => void;
1194 >
1195 > constructor(runner: Runner, delay: number) {
1196 > this.timeoutToken = undefined; async.ts
1197 > this.runner = runner;
1198 > this.timeout = delay;
1199 > this.timeoutHandler = this.onTimeout.bind(this);
1200 > }
1201 > async.ts
1202 > /**
1203 > * Dispose RunOnceScheduler
1204 > */
1205 > dispose(): void {
1206 > this.cancel(); async.ts
1207 > this.runner = null;
1208 > }
1209 > async.ts
1210 > /**
1211 > * Cancel current scheduled runner (if any).
1212 > */
1213 > cancel(): void {
1214 > if (this.isScheduled()) { async.ts
1215 > clearTimeout(this.timeoutToken); async.ts
1216 > this.timeoutToken = undefined;
1217 > }
1218 > } async.ts
1219 > async.ts
1220 > /**
1221 > * Cancel previous runner (if any) & schedule a new runner.
1222 > */
1223 > schedule(delay = this.timeout): void {
1224 > this.cancel(); async.ts
1225 > this.timeoutToken = setTimeout(this.timeoutHandler, delay);
1226 > }
1227 > async.ts
1228 > get delay(): number {
1229 return this.timeout;
1230 }
1231 > async.ts
1232 > set delay(value: number) {
1233 this.timeout = value;
1234 }
1235 > async.ts
1236 > /**
1237 > * Returns true if scheduled.
1238 > */
1239 > isScheduled(): boolean {
1240 > return this.timeoutToken !== undefined; async.ts
1241 > }
1242 > async.ts
1243 > flush(): void {
1244 if (this.isScheduled()) {
1245 this.cancel();
1247 }
1248 }
1249 > async.ts
1250 > private onTimeout() {
1251 > this.timeoutToken = undefined; async.ts
1252 > if (this.runner) {
1253 > this.doRun();
1254 > }
1255 > }
1256 > async.ts
1257 > protected doRun(): void {
1258 > this.runner?.(); async.ts
1259 > }
1260 > } async.ts
1261 >
1262 > /**
1263 > * Same as `RunOnceScheduler`, but doesn't count the time spent in sleep mode.
1264 > * > **NOTE**: Only offers 1s resolution.
1265 > *
1266 > * When calling `setTimeout` with 3hrs, and putting the computer immediately to sleep
1267 > * for 8hrs, `setTimeout` will fire **as soon as the computer wakes from sleep**. But
1268 > * this scheduler will execute 3hrs **after waking the computer from sleep**.
1269 > */
1270 > export class ProcessTimeRunOnceScheduler {
1271 >
1272 > private runner: (() => void) | null;
1273 > private timeout: number;
1274 >
1275 > private counter: number;
1276 > private intervalToken: Timeout | undefined;
1277 > private intervalHandler: () => void;
1278 >
1279 > constructor(runner: () => void, delay: number) {
1280 if (delay % 1000 !== 0) {
1281 console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);
1287 this.intervalHandler = this.onInterval.bind(this);
1288 }
1289 > async.ts
1290 > dispose(): void {
1291 this.cancel();
1292 this.runner = null;
1293 }
1294 > async.ts
1295 > cancel(): void {
1296 if (this.isScheduled()) {
1297 clearInterval(this.intervalToken);
1299 }
1300 }
1301 > async.ts
1302 > /**
1303 > * Cancel previous runner (if any) & schedule a new runner.
1304 > */
1305 > schedule(delay = this.timeout): void {
1306 if (delay % 1000 !== 0) {
1307 console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`);
1311 this.intervalToken = setInterval(this.intervalHandler, 1000);
1312 }
1313 > async.ts
1314 > /**
1315 > * Returns true if scheduled.
1316 > */
1317 > isScheduled(): boolean {
1318 return this.intervalToken !== undefined;
1319 }
1320 > async.ts
1321 > private onInterval() {
1322 this.counter--;
1323 if (this.counter > 0) {
1331 this.runner?.();
1332 }
1333 > } async.ts
1334 >
1335 > export class RunOnceWorker<T> extends RunOnceScheduler<(units: T[]) => void> {
1336 >
1337 > private units: T[] = [];
1338 >
1339 > constructor(runner: (units: T[]) => void, timeout: number) {
1340 super(runner, timeout);
1341 }
1342 > async.ts
1343 > work(unit: T): void {
1344 this.units.push(unit);
1345
1348 }
1349 }
1350 > async.ts
1351 > protected override doRun(): void {
1352 const units = this.units;
1353 this.units = [];
1355 this.runner?.(units);
1356 }
1357 > async.ts
1358 > override dispose(): void {
1359 this.units = [];
1360
1361 super.dispose();
1362 }
1363 > } async.ts
1364 >
1365 > export interface IThrottledWorkerOptions {
1366 >
1367 > /**
1368 > * maximum of units the worker will pass onto handler at once
1369 > */
1370 > maxWorkChunkSize: number;
1371 >
1372 > /**
1373 > * maximum of units the worker will keep in memory for processing
1374 > */
1375 > maxBufferedWork: number | undefined;
1376 >
1377 > /**
1378 > * delay before processing the next round of chunks when chunk size exceeds limits
1379 > */
1380 > throttleDelay: number;
1381 >
1382 > /**
1383 > * When enabled will guarantee that two distinct calls to `work()` are not executed
1384 > * without throttle delay between them.
1385 > * Otherwise if the worker isn't currently throttling it will execute work immediately.
1386 > */
1387 > waitThrottleDelayBetweenWorkUnits?: boolean;
1388 > }
1389 >
1390 > /**
1391 > * The `ThrottledWorker` will accept units of work `T`
1392 > * to handle. The contract is:
1393 > * * there is a maximum of units the worker can handle at once (via `maxWorkChunkSize`)
1394 > * * there is a maximum of units the worker will keep in memory for processing (via `maxBufferedWork`)
1395 > * * after having handled `maxWorkChunkSize` units, the worker needs to rest (via `throttleDelay`)
1396 > */
1397 > export class ThrottledWorker<T> extends Disposable {
1398 >
1399 > private readonly pendingWork: T[] = [];
1400 >
1401 > private readonly throttler = this._register(new MutableDisposable<RunOnceScheduler>());
1402 > private disposed = false;
1403 > private lastExecutionTime = 0;
1404 >
1405 > constructor(
1406 private options: IThrottledWorkerOptions,
1407 private readonly handler: (units: T[]) => void
1409 super();
1410 }
1411 > async.ts
1412 > /**
1413 > * The number of work units that are pending to be processed.
1414 > */
1415 > get pending(): number { return this.pendingWork.length; }
1416 >
1417 > /**
1418 > * Add units to be worked on. Use `pending` to figure out
1419 > * how many units are not yet processed after this method
1420 > * was called.
1421 > *
1422 > * @returns whether the work was accepted or not. If the
1423 > * worker is disposed, it will not accept any more work.
1424 > * If the number of pending units would become larger
1425 > * than `maxPendingWork`, more work will also not be accepted.
1426 > */
1427 > work(units: readonly T[]): boolean {
1428 if (this.disposed) {
1429 return false; // work not accepted: disposed
1469 return true; // work accepted
1470 }
1471 > async.ts
1472 > private doWork(): void {
1473 this.lastExecutionTime = Date.now();
1474
1481 }
1482 }
1483 > async.ts
1484 > private scheduleThrottler(delay = this.options.throttleDelay): void {
1485 this.throttler.value = new RunOnceScheduler(() => {
1486 this.throttler.clear();
1490 this.throttler.value.schedule();
1491 }
1492 > async.ts
1493 > override dispose(): void {
1494 super.dispose();
1495
1497 this.disposed = true;
1498 }
1499 > } async.ts
1500 >
1501 > //#region -- run on idle tricks ------------
1502 >
1503 > export interface IdleDeadline {
1504 > readonly didTimeout: boolean;
1505 > timeRemaining(): number;
1506 > }
1507 >
1508 > type IdleApi = Pick<typeof globalThis, 'requestIdleCallback' | 'cancelIdleCallback'>;
1509 >
1510 >
1511 > /**
1512 > * Execute the callback the next time the browser is idle, returning an
1513 > * {@link IDisposable} that will cancel the callback when disposed. This wraps
1514 > * [requestIdleCallback] so it will fallback to [setTimeout] if the environment
1515 > * doesn't support it.
1516 > *
1517 > * @param callback The callback to run when idle, this includes an
1518 > * [IdleDeadline] that provides the time alloted for the idle callback by the
1519 > * browser. Not respecting this deadline will result in a degraded user
1520 > * experience.
1521 > * @param timeout A timeout at which point to queue no longer wait for an idle
1522 > * callback but queue it on the regular event loop (like setTimeout). Typically
1523 > * this should not be used.
1524 > *
1525 > * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline
1526 > * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
1527 > * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
1528 > *
1529 > * **Note** that there is `dom.ts#runWhenWindowIdle` which is better suited when running inside a browser
1530 > * context
1531 > */
1532 > export let runWhenGlobalIdle: (callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable;
1533 >
1534 > export let _runWhenIdle: (targetWindow: IdleApi, callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable;
1535 >
1536 > (function () {
1537 > const safeGlobal: any = globalThis;
1538 > if (typeof safeGlobal.requestIdleCallback !== 'function' || typeof safeGlobal.cancelIdleCallback !== 'function') {
1539 > _runWhenIdle = (_targetWindow, runner, timeout?) => {
1540 setTimeout0(() => {
1541 if (disposed) {
1561 };
1562 };
1563 > } else { async.ts
1564 _runWhenIdle = (targetWindow: typeof safeGlobal, runner, timeout?) => {
1565 const handle: number = targetWindow.requestIdleCallback(runner, typeof timeout === 'number' ? { timeout } : undefined);
1576 };
1577 }
1578 > runWhenGlobalIdle = (runner, timeout) => _runWhenIdle(globalThis, runner, timeout); async.ts
1579 > })();
1580 >
1581 > export function installFakeRunWhenIdle(fakeImpl: typeof _runWhenIdle): IDisposable {
1582 const origRunWhenIdle = _runWhenIdle;
1583 const origRunWhenGlobalIdle = runWhenGlobalIdle;
1589 });
1590 }
1591 > async.ts
1592 > export abstract class AbstractIdleValue<T> {
1593 >
1594 > private readonly _executor: () => void;
1595 > private readonly _handle: IDisposable;
1596 >
1597 > private _didRun: boolean = false;
1598 > private _value?: T;
1599 > private _error: unknown;
1600 >
1601 > constructor(targetWindow: IdleApi, executor: () => T) {
1602 this._executor = () => {
1603 try {
1611 this._handle = _runWhenIdle(targetWindow, () => this._executor());
1612 }
1613 > async.ts
1614 > dispose(): void {
1615 this._handle.dispose();
1616 }
1617 > async.ts
1618 > get value(): T {
1619 if (!this._didRun) {
1620 this._handle.dispose();
1626 return this._value!;
1627 }
1628 > async.ts
1629 > get isInitialized(): boolean {
1630 return this._didRun;
1631 }
1632 > } async.ts
1633 >
1634 > /**
1635 > * An `IdleValue` that always uses the current window (which might be throttled or inactive)
1636 > *
1637 > * **Note** that there is `dom.ts#WindowIdleValue` which is better suited when running inside a browser
1638 > * context
1639 > */
1640 > export class GlobalIdleValue<T> extends AbstractIdleValue<T> {
1641 >
1642 > constructor(executor: () => T) {
1643 super(globalThis, executor);
1644 }
1645 > } async.ts
1646 >
1647 > //#endregion
1648 >
1649 export async function retry<T>(task: ITask<Promise<T>>, delay: number, retries: number): Promise<T> {
1650 let lastError: Error | undefined;
1662 throw lastError;
1663 }
1664 > async.ts
1665 > //#region Task Sequentializer
1666 >
1667 > interface IRunningTask {
1668 > readonly taskId: number;
1669 > readonly cancel: () => void;
1670 > readonly promise: Promise<void>;
1671 > }
1672 >
1673 > interface IQueuedTask {
1674 > readonly promise: Promise<void>;
1675 > readonly promiseResolve: () => void;
1676 > readonly promiseReject: (error: Error) => void;
1677 > run: ITask<Promise<void>>;
1678 > }
1679 >
1680 > export interface ITaskSequentializerWithRunningTask {
1681 > readonly running: Promise<void>;
1682 > }
1683 >
1684 > export interface ITaskSequentializerWithQueuedTask {
1685 > readonly queued: IQueuedTask;
1686 > }
1687 >
1688 > /**
1689 > * @deprecated use `LimitedQueue` instead for an easier to use API
1690 > */
1691 > export class TaskSequentializer {
1692 >
1693 > private _running?: IRunningTask;
1694 > private _queued?: IQueuedTask;
1695 >
1696 > isRunning(taskId?: number): this is ITaskSequentializerWithRunningTask {
1697 if (typeof taskId === 'number') {
1698 return this._running?.taskId === taskId;
1701 return !!this._running;
1702 }
1703 > async.ts
1704 > get running(): Promise<void> | undefined {
1705 return this._running?.promise;
1706 }
1707 > async.ts
1708 > cancelRunning(): void {
1709 this._running?.cancel();
1710 }
1711 > async.ts
1712 > run(taskId: number, promise: Promise<void>, onCancel?: () => void,): Promise<void> {
1713 this._running = { taskId, cancel: () => onCancel?.(), promise };
1714
1717 return promise;
1718 }
1719 > async.ts
1720 > private doneRunning(taskId: number): void {
1721 if (this._running && taskId === this._running.taskId) {
1722
1728 }
1729 }
1730 > async.ts
1731 > private runQueued(): void {
1732 if (this._queued) {
1733 const queued = this._queued;
1738 }
1739 }
1740 > async.ts
1741 > /**
1742 > * Note: the promise to schedule as next run MUST itself call `run`.
1743 > * Otherwise, this sequentializer will report `false` for `isRunning`
1744 > * even when this task is running. Missing this detail means that
1745 > * suddenly multiple tasks will run in parallel.
1746 > */
1747 > queue(run: ITask<Promise<void>>): Promise<void> {
1748
1749 // this is our first queued task, so we create associated promise with it
1767 return this._queued.promise;
1768 }
1769 > async.ts
1770 > hasQueued(): this is ITaskSequentializerWithQueuedTask {
1771 return !!this._queued;
1772 }
1773 > async.ts
1774 > async join(): Promise<void> {
1775 return this._queued?.promise ?? this._running?.promise;
1776 }
1777 > } async.ts
1778 >
1779 > //#endregion
1780 >
1781 > //#region
1782 >
1783 > /**
1784 > * The `IntervalCounter` allows to count the number
1785 > * of calls to `increment()` over a duration of
1786 > * `interval`. This utility can be used to conditionally
1787 > * throttle a frequent task when a certain threshold
1788 > * is reached.
1789 > */
1790 > export class IntervalCounter {
1791 >
1792 > private lastIncrementTime = 0;
1793 >
1794 > private value = 0;
1795 >
1796 > constructor(private readonly interval: number, private readonly nowFn = () => Date.now()) { }
1797 >
1798 > increment(): number {
1799 const now = this.nowFn();
1800
1810 return this.value;
1811 }
1812 > } async.ts
1813 >
1814 > //#endregion
1815 >
1816 > //#region
1817 >
1818 > export type ValueCallback<T = unknown> = (value: T | Promise<T>) => void;
1819 >
1820 > const enum DeferredOutcome {
1821 > Resolved,
1822 > Rejected
1823 > }
1824 >
1825 > /**
1826 > * Creates a promise whose resolution or rejection can be controlled imperatively.
1827 > */
1828 > export class DeferredPromise<T> {
1829 >
1830 > public static fromPromise<T>(promise: Promise<T>): DeferredPromise<T> {
1831 const deferred = new DeferredPromise<T>();
1832 deferred.settleWith(promise);
1833 return deferred;
1834 }
1835 > async.ts
1836 > private completeCallback!: ValueCallback<T>;
1837 > private errorCallback!: (err: unknown) => void;
1838 > private outcome?: { outcome: DeferredOutcome.Rejected; value: unknown } | { outcome: DeferredOutcome.Resolved; value: T };
1839 >
1840 > public get isRejected() {
1841 return this.outcome?.outcome === DeferredOutcome.Rejected;
1842 }
1843 > async.ts
1844 > public get isResolved() {
1845 return this.outcome?.outcome === DeferredOutcome.Resolved;
1846 }
1847 > async.ts
1848 > public get isSettled() {
1849 return !!this.outcome;
1850 }
1851 > async.ts
1852 > public get value() {
1853 return this.outcome?.outcome === DeferredOutcome.Resolved ? this.outcome?.value : undefined;
1854 }
1855 > async.ts
1856 > public readonly p: Promise<T>;
1857 >
1858 > constructor() {
1859 this.p = new Promise<T>((c, e) => {
1860 this.completeCallback = c;
1862 });
1863 }
1864 > async.ts
1865 > public complete(value: T) {
1866 if (this.isSettled) {
1867 return Promise.resolve();
1874 });
1875 }
1876 > async.ts
1877 > public error(err: unknown) {
1878 if (this.isSettled) {
1879 return Promise.resolve();
1886 });
1887 }
1888 > async.ts
1889 > public settleWith(promise: Promise<T>): Promise<void> {
1890 return promise.then(
1891 value => this.complete(value),
1893 );
1894 }
1895 > async.ts
1896 > public cancel() {
1897 return this.error(new CancellationError());
1898 }
1899 > } async.ts
1900 >
1901 > //#endregion
1902 >
1903 > //#region Promises
1904 >
1905 > export namespace Promises {
1906 >
1907 > /**
1908 > * A drop-in replacement for `Promise.all` with the only difference
1909 > * that the method awaits every promise to either fulfill or reject.
1910 > *
1911 > * Similar to `Promise.all`, only the first error will be returned
1912 > * if any.
1913 > */
1914 > export async function settled<T>(promises: Promise<T>[]): Promise<T[]> {
1915 > let firstError: Error | undefined = undefined; async.ts
1916 >
1917 > const result = await Promise.all(promises.map(promise => promise.then(value => value, error => {
1918 if (!firstError) {
1919 firstError = error;
1921
1922 return undefined; // do not rethrow so that other promises can settle
1923 > }))); async.ts
1924 >
1925 > if (typeof firstError !== 'undefined') {
1926 throw firstError;
1927 }
1928 > async.ts
1929 > return result as unknown as T[]; // cast is needed and protected by the `throw` above
1930 > } async.ts
1931 > async.ts
1932 > /**
1933 > * A helper to create a new `Promise<T>` with a body that is a promise
1934 > * itself. By default, an error that raises from the async body will
1935 > * end up as a unhandled rejection, so this utility properly awaits the
1936 > * body and rejects the promise as a normal promise does without async
1937 > * body.
1938 > *
1939 > * This method should only be used in rare cases where otherwise `async`
1940 > * cannot be used (e.g. when callbacks are involved that require this).
1941 > */
1942 > export function withAsyncBody<T, E = Error>(bodyFn: (resolve: (value: T) => unknown, reject: (error: E) => unknown) => Promise<unknown>): Promise<T> {
1943 // eslint-disable-next-line no-async-promise-executor
1944 return new Promise<T>(async (resolve, reject) => {
1950 });
1951 }
1952 > } async.ts
1953 >
1954 > export class StatefulPromise<T> {
1955 > private _value: T | undefined = undefined;
1956 > get value(): T | undefined { return this._value; }
1957 >
1958 > private _error: unknown = undefined;
1959 > get error(): unknown { return this._error; }
1960 >
1961 > private _isResolved = false;
1962 > get isResolved() { return this._isResolved; }
1963 >
1964 > public readonly promise: Promise<T>;
1965 >
1966 > constructor(promise: Promise<T>) {
1967 this.promise = promise.then(
1968 value => {
1978 );
1979 }
1980 > async.ts
1981 > /**
1982 > * Returns the resolved value.
1983 > * Throws if the promise is not resolved yet.
1984 > */
1985 > public requireValue(): T {
1986 if (!this._isResolved) {
1987 throw new BugIndicatingError('Promise is not resolved yet');
1992 return this._value!;
1993 }
1994 > } async.ts
1995 >
1996 > export class LazyStatefulPromise<T> {
1997 > private readonly _promise = new Lazy(() => new StatefulPromise(this._compute()));
1998 >
1999 > constructor(
2000 private readonly _compute: () => Promise<T>,
2001 ) { }
2002 > async.ts
2003 > /**
2004 > * Returns the resolved value.
2005 > * Throws if the promise is not resolved yet.
2006 > */
2007 > public requireValue(): T {
2008 return this._promise.value.requireValue();
2009 }
2010 > async.ts
2011 > /**
2012 > * Returns the promise (and triggers a computation of the promise if not yet done so).
2013 > */
2014 > public getPromise(): Promise<T> {
2015 return this._promise.value.promise;
2016 }
2017 > async.ts
2018 > /**
2019 > * Reads the current value without triggering a computation of the promise.
2020 > */
2021 > public get currentValue(): T | undefined {
2022 return this._promise.rawValue?.value;
2023 }
2024 > } async.ts
2025 >
2026 > //#endregion
2027 >
2028 > //#region
2029 >
2030 > const enum AsyncIterableSourceState {
2031 > Initial,
2032 > DoneOK,
2033 > DoneError,
2034 > }
2035 >
2036 > /**
2037 > * An object that allows to emit async values asynchronously or bring the iterable to an error state using `reject()`.
2038 > * This emitter is valid only for the duration of the executor (until the promise returned by the executor settles).
2039 > */
2040 > export interface AsyncIterableEmitter<T> {
2041 > /**
2042 > * The value will be appended at the end.
2043 > *
2044 > * **NOTE** If `reject()` has already been called, this method has no effect.
2045 > */
2046 > emitOne(value: T): void;
2047 > /**
2048 > * The values will be appended at the end.
2049 > *
2050 > * **NOTE** If `reject()` has already been called, this method has no effect.
2051 > */
2052 > emitMany(values: T[]): void;
2053 > /**
2054 > * Writing an error will permanently invalidate this iterable.
2055 > * The current users will receive an error thrown, as will all future users.
2056 > *
2057 > * **NOTE** If `reject()` have already been called, this method has no effect.
2058 > */
2059 > reject(error: Error): void;
2060 > }
2061 >
2062 > /**
2063 > * An executor for the `AsyncIterableObject` that has access to an emitter.
2064 > */
2065 > export interface AsyncIterableExecutor<T> {
2066 > /**
2067 > * @param emitter An object that allows to emit async values valid only for the duration of the executor.
2068 > */
2069 > (emitter: AsyncIterableEmitter<T>): unknown | Promise<unknown>;
2070 > }
2071 >
2072 > /**
2073 > * A rich implementation for an `AsyncIterable<T>`.
2074 > */
2075 > export class AsyncIterableObject<T> implements AsyncIterable<T> {
2076 >
2077 > public static fromArray<T>(items: T[]): AsyncIterableObject<T> {
2078 > return new AsyncIterableObject<T>((writer) => {
2079 > writer.emitMany(items);
2080 > });
2081 > }
2082 >
2083 > public static fromPromise<T>(promise: Promise<T[]>): AsyncIterableObject<T> {
2084 return new AsyncIterableObject<T>(async (emitter) => {
2085 emitter.emitMany(await promise);
2086 });
2087 }
2088 > async.ts
2089 > public static fromPromisesResolveOrder<T>(promises: Promise<T>[]): AsyncIterableObject<T> {
2090 return new AsyncIterableObject<T>(async (emitter) => {
2091 await Promise.all(promises.map(async (p) => emitter.emitOne(await p)));
2092 });
2093 }
2094 > async.ts
2095 > public static merge<T>(iterables: AsyncIterable<T>[]): AsyncIterableObject<T> {
2096 return new AsyncIterableObject(async (emitter) => {
2097 await Promise.all(iterables.map(async (iterable) => {
2102 });
2103 }
2104 > async.ts
2105 > public static EMPTY = AsyncIterableObject.fromArray<any>([]);
2106 >
2107 > private _state: AsyncIterableSourceState;
2108 > private _results: T[];
2109 > private _error: Error | null;
2110 > private readonly _onReturn?: () => void | Promise<void>;
2111 > private readonly _onStateChanged: Emitter<void>;
2112 >
2113 > constructor(executor: AsyncIterableExecutor<T>, onReturn?: () => void | Promise<void>) {
2114 > this._state = AsyncIterableSourceState.Initial;
2115 > this._results = [];
2116 > this._error = null;
2117 > this._onReturn = onReturn;
2118 > this._onStateChanged = new Emitter<void>();
2119 >
2120 > queueMicrotask(async () => {
2121 > const writer: AsyncIterableEmitter<T> = {
2122 > emitOne: (item) => this.emitOne(item),
2123 > emitMany: (items) => this.emitMany(items),
2124 > reject: (error) => this.reject(error)
2125 > };
2126 > try {
2127 > await Promise.resolve(executor(writer));
2128 > this.resolve();
2129 > } catch (err) {
2130 this.reject(err);
2131 > } finally { async.ts
2132 > // The executor has settled; emitting afterwards must be a no-op per the
2133 > // documented "no effect after resolve()/reject()" contract (see emitOne).
2134 > writer.emitOne = () => { };
2135 > writer.emitMany = () => { };
2136 > writer.reject = () => { };
2137 > }
2138 > });
2139 > }
2140 >
2141 > [Symbol.asyncIterator](): AsyncIterator<T, undefined, undefined> {
2142 let i = 0;
2143 return {
2162 };
2163 }
2164 > async.ts
2165 > public static map<T, R>(iterable: AsyncIterable<T>, mapFn: (item: T) => R): AsyncIterableObject<R> {
2166 return new AsyncIterableObject<R>(async (emitter) => {
2167 for await (const item of iterable) {
2170 });
2171 }
2172 > async.ts
2173 > public map<R>(mapFn: (item: T) => R): AsyncIterableObject<R> {
2174 return AsyncIterableObject.map(this, mapFn);
2175 }
2176 > async.ts
2177 > public static filter<T>(iterable: AsyncIterable<T>, filterFn: (item: T) => boolean): AsyncIterableObject<T> {
2178 return new AsyncIterableObject<T>(async (emitter) => {
2179 for await (const item of iterable) {
2184 });
2185 }
2186 > async.ts
2187 > public filter<T2 extends T>(filterFn: (item: T) => item is T2): AsyncIterableObject<T2>;
2188 > public filter(filterFn: (item: T) => boolean): AsyncIterableObject<T>;
2189 > public filter(filterFn: (item: T) => boolean): AsyncIterableObject<T> {
2190 return AsyncIterableObject.filter(this, filterFn);
2191 }
2192 > async.ts
2193 > public static coalesce<T>(iterable: AsyncIterable<T | undefined | null>): AsyncIterableObject<T> {
2194 return <AsyncIterableObject<T>>AsyncIterableObject.filter(iterable, item => !!item);
2195 }
2196 > async.ts
2197 > public coalesce(): AsyncIterableObject<NonNullable<T>> {
2198 return AsyncIterableObject.coalesce(this) as AsyncIterableObject<NonNullable<T>>;
2199 }
2200 > async.ts
2201 > public static async toPromise<T>(iterable: AsyncIterable<T>): Promise<T[]> {
2202 const result: T[] = [];
2203 for await (const item of iterable) {
2206 return result;
2207 }
2208 > async.ts
2209 > public toPromise(): Promise<T[]> {
2210 return AsyncIterableObject.toPromise(this);
2211 }
2212 > async.ts
2213 > /**
2214 > * The value will be appended at the end.
2215 > *
2216 > * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
2217 > */
2218 > private emitOne(value: T): void {
2219 if (this._state !== AsyncIterableSourceState.Initial) {
2220 return;
2225 this._onStateChanged.fire();
2226 }
2227 > async.ts
2228 > /**
2229 > * The values will be appended at the end.
2230 > *
2231 > * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
2232 > */
2233 > private emitMany(values: T[]): void {
2234 > if (this._state !== AsyncIterableSourceState.Initial) {
2235 return;
2236 }
2237 > // it is important to add new values at the end, async.ts
2238 > // as we may have iterators already running on the array
2239 > this._results = this._results.concat(values);
2240 > this._onStateChanged.fire();
2241 > }
2242 >
2243 > /**
2244 > * Calling `resolve()` will mark the result array as complete.
2245 > *
2246 > * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.
2247 > * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
2248 > */
2249 > private resolve(): void {
2250 > if (this._state !== AsyncIterableSourceState.Initial) {
2251 return;
2252 }
2253 > this._state = AsyncIterableSourceState.DoneOK; async.ts
2254 > this._onStateChanged.fire();
2255 > }
2256 >
2257 > /**
2258 > * Writing an error will permanently invalidate this iterable.
2259 > * The current users will receive an error thrown, as will all future users.
2260 > *
2261 > * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
2262 > */
2263 > private reject(error: Error) {
2264 if (this._state !== AsyncIterableSourceState.Initial) {
2265 return;
2269 this._onStateChanged.fire();
2270 }
2271 > } async.ts
2272 >
2273 >
2274 > export function createCancelableAsyncIterableProducer<T>(callback: (token: CancellationToken) => AsyncIterable<T>): CancelableAsyncIterableProducer<T> {
2275 const source = new CancellationTokenSource();
2276 const innerIterable = callback(source.token);
2299 });
2300 }
2301 > async.ts
2302 > export class AsyncIterableSource<T> {
2303 >
2304 > private readonly _deferred = new DeferredPromise<void>();
2305 > private readonly _asyncIterable: AsyncIterableObject<T>;
2306 >
2307 > private _errorFn: (error: Error) => void;
2308 > private _emitOneFn: (item: T) => void;
2309 > private _emitManyFn: (item: T[]) => void;
2310 >
2311 > /**
2312 > *
2313 > * @param onReturn A function that will be called when consuming the async iterable
2314 > * has finished by the consumer, e.g the for-await-loop has be existed (break, return) early.
2315 > * This is NOT called when resolving this source by its owner.
2316 > */
2317 > constructor(onReturn?: () => Promise<void> | void) {
2318 this._asyncIterable = new AsyncIterableObject(emitter => {
2319
2354 };
2355 }
2356 > async.ts
2357 > get asyncIterable(): AsyncIterableObject<T> {
2358 return this._asyncIterable;
2359 }
2360 > async.ts
2361 > resolve(): void {
2362 this._deferred.complete();
2363 }
2364 > async.ts
2365 > reject(error: Error): void {
2366 this._errorFn(error);
2367 this._deferred.complete();
2368 }
2369 > async.ts
2370 > emitOne(item: T): void {
2371 this._emitOneFn(item);
2372 }
2373 > async.ts
2374 > emitMany(items: T[]) {
2375 this._emitManyFn(items);
2376 }
2377 > } async.ts
2378 >
2379 > export function cancellableIterable<T>(iterableOrIterator: AsyncIterator<T> | AsyncIterable<T>, token: CancellationToken): AsyncIterableIterator<T> {
2380 const iterator = Symbol.asyncIterator in iterableOrIterator ? iterableOrIterator[Symbol.asyncIterator]() : iterableOrIterator;
2381
2395 };
2396 }
2397 > async.ts
2398 > type ProducerConsumerValue<T> = {
2399 > ok: true;
2400 > value: T;
2401 > } | {
2402 > ok: false;
2403 > error: Error;
2404 > };
2405 >
2406 > class ProducerConsumer<T> {
2407 > private readonly _unsatisfiedConsumers: DeferredPromise<T>[] = [];
2408 > private readonly _unconsumedValues: ProducerConsumerValue<T>[] = [];
2409 > private _finalValue: ProducerConsumerValue<T> | undefined;
2410 >
2411 > public get hasFinalValue(): boolean {
2412 > return !!this._finalValue;
2413 > }
2414 >
2415 > produce(value: ProducerConsumerValue<T>): void {
2416 this._ensureNoFinalValue();
2417 if (this._unsatisfiedConsumers.length > 0) {
2422 }
2423 }
2424 > async.ts
2425 > produceFinal(value: ProducerConsumerValue<T>): void {
2426 > this._ensureNoFinalValue();
2427 > this._finalValue = value;
2428 > for (const deferred of this._unsatisfiedConsumers) {
2429 this._resolveOrRejectDeferred(deferred, value);
2430 }
2431 > this._unsatisfiedConsumers.length = 0; async.ts
2432 > }
2433 >
2434 > private _ensureNoFinalValue(): void {
2435 > if (this._finalValue) {
2436 throw new BugIndicatingError('ProducerConsumer: cannot produce after final value has been set');
2437 }
2438 > } async.ts
2439 >
2440 > private _resolveOrRejectDeferred(deferred: DeferredPromise<T>, value: ProducerConsumerValue<T>): void {
2441 if (value.ok) {
2442 deferred.complete(value.value);
2445 }
2446 }
2447 > async.ts
2448 > consume(): Promise<T> {
2449 if (this._unconsumedValues.length > 0 || this._finalValue) {
2450 const value = this._unconsumedValues.length > 0 ? this._unconsumedValues.shift()! : this._finalValue!;
2460 }
2461 }
2462 > } async.ts
2463 >
2464 > /**
2465 > * Important difference to AsyncIterableObject:
2466 > * If it is iterated two times, the second iterator will not see the values emitted by the first iterator.
2467 > */
2468 > export class AsyncIterableProducer<T> implements AsyncIterable<T> {
2469 > private readonly _producerConsumer = new ProducerConsumer<IteratorResult<T>>();
2470 >
2471 > constructor(executor: AsyncIterableExecutor<T>, private readonly _onReturn?: () => void) {
2472 > queueMicrotask(async () => {
2473 > const p = executor({
2474 > emitOne: value => this._producerConsumer.produce({ ok: true, value: { done: false, value: value } }),
2475 > emitMany: values => {
2476 > for (const value of values) {
2477 this._producerConsumer.produce({ ok: true, value: { done: false, value: value } });
2478 }
2479 > }, async.ts
2480 > reject: error => this._finishError(error),
2481 > });
2482 >
2483 > if (!this._producerConsumer.hasFinalValue) {
2484 > try {
2485 > await p;
2486 > this._finishOk();
2487 > } catch (error) {
2488 this._finishError(error);
2489 }
2490 > } async.ts
2491 > });
2492 > }
2493 >
2494 > public static fromArray<T>(items: T[]): AsyncIterableProducer<T> {
2495 > return new AsyncIterableProducer<T>((writer) => {
2496 > writer.emitMany(items);
2497 > });
2498 > }
2499 >
2500 > public static fromPromise<T>(promise: Promise<T[]>): AsyncIterableProducer<T> {
2501 return new AsyncIterableProducer<T>(async (emitter) => {
2502 emitter.emitMany(await promise);
2503 });
2504 }
2505 > async.ts
2506 > public static fromPromisesResolveOrder<T>(promises: Promise<T>[]): AsyncIterableProducer<T> {
2507 return new AsyncIterableProducer<T>(async (emitter) => {
2508 await Promise.all(promises.map(async (p) => emitter.emitOne(await p)));
2509 });
2510 }
2511 > async.ts
2512 > public static merge<T>(iterables: AsyncIterable<T>[]): AsyncIterableProducer<T> {
2513 return new AsyncIterableProducer(async (emitter) => {
2514 await Promise.all(iterables.map(async (iterable) => {
2519 });
2520 }
2521 > async.ts
2522 > public static EMPTY = AsyncIterableProducer.fromArray<any>([]);
2523 >
2524 > public static map<T, R>(iterable: AsyncIterable<T>, mapFn: (item: T) => R): AsyncIterableProducer<R> {
2525 return new AsyncIterableProducer<R>(async (emitter) => {
2526 for await (const item of iterable) {
2529 });
2530 }
2531 > async.ts
2532 > public static tee<T>(iterable: AsyncIterable<T>): [AsyncIterableProducer<T>, AsyncIterableProducer<T>] {
2533 let emitter1: AsyncIterableEmitter<T> | undefined;
2534 let emitter2: AsyncIterableEmitter<T> | undefined;
2565 return [p1, p2];
2566 }
2567 > async.ts
2568 > public map<R>(mapFn: (item: T) => R): AsyncIterableProducer<R> {
2569 return AsyncIterableProducer.map(this, mapFn);
2570 }
2571 > async.ts
2572 > public static coalesce<T>(iterable: AsyncIterable<T | undefined | null>): AsyncIterableProducer<T> {
2573 return <AsyncIterableProducer<T>>AsyncIterableProducer.filter(iterable, item => !!item);
2574 }
2575 > async.ts
2576 > public coalesce(): AsyncIterableProducer<NonNullable<T>> {
2577 return AsyncIterableProducer.coalesce(this) as AsyncIterableProducer<NonNullable<T>>;
2578 }
2579 > async.ts
2580 > public static filter<T>(iterable: AsyncIterable<T>, filterFn: (item: T) => boolean): AsyncIterableProducer<T> {
2581 return new AsyncIterableProducer<T>(async (emitter) => {
2582 for await (const item of iterable) {
2587 });
2588 }
2589 > async.ts
2590 > public filter<T2 extends T>(filterFn: (item: T) => item is T2): AsyncIterableProducer<T2>;
2591 > public filter(filterFn: (item: T) => boolean): AsyncIterableProducer<T>;
2592 > public filter(filterFn: (item: T) => boolean): AsyncIterableProducer<T> {
2593 return AsyncIterableProducer.filter(this, filterFn);
2594 }
2595 > async.ts
2596 > private _finishOk(): void {
2597 > if (!this._producerConsumer.hasFinalValue) {
2598 > this._producerConsumer.produceFinal({ ok: true, value: { done: true, value: undefined } });
2599 > }
2600 > }
2601 >
2602 > private _finishError(error: Error): void {
2603 if (!this._producerConsumer.hasFinalValue) {
2604 this._producerConsumer.produceFinal({ ok: false, error: error });
2606 // Warning: this can cause to dropped errors.
2607 }
2608 > async.ts
2609 > private readonly _iterator: AsyncIterator<T, void, void> = {
2610 > next: () => this._producerConsumer.consume(),
2611 > return: () => {
2612 this._onReturn?.();
2613 return Promise.resolve({ done: true, value: undefined });
2614 },
2615 > throw: async (e) => { async.ts
2616 this._finishError(e);
2617 return { done: true, value: undefined };
2618 },
2619 > }; async.ts
2620 >
2621 > [Symbol.asyncIterator](): AsyncIterator<T, void, void> {
2622 return this._iterator;
2623 }
2624 > } async.ts
2625 >
2626 > export class CancelableAsyncIterableProducer<T> extends AsyncIterableProducer<T> {
2627 > constructor(
2628 private readonly _source: CancellationTokenSource,
2629 executor: AsyncIterableExecutor<T>
2631 super(executor);
2632 }
2633 > async.ts
2634 > cancel(): void {
2635 this._source.cancel();
2636 }
2637 > } async.ts
2638 >
2639 > //#endregion
2640 >
2641 > export const AsyncReaderEndOfStream = Symbol('AsyncReaderEndOfStream');
2642 >
2643 > export class AsyncReader<T> {
2644 > private _buffer: T[] = [];
2645 > private _atEnd = false;
2646 >
2647 > public get endOfStream(): boolean { return this._buffer.length === 0 && this._atEnd; }
2648 > private _extendBufferPromise: Promise<void> | undefined;
2649 >
2650 > constructor(
2651 private readonly _source: AsyncIterator<T>
2652 ) {
2653 }
2654 > async.ts
2655 > public async read(): Promise<T | typeof AsyncReaderEndOfStream> {
2656 if (this._buffer.length === 0 && !this._atEnd) {
2657 await this._extendBuffer();
2662 return this._buffer.shift()!;
2663 }
2664 > async.ts
2665 > public async readWhile(predicate: (value: T) => boolean, callback: (element: T) => unknown): Promise<void> {
2666 do {
2667 const piece = await this.peek();
2676 } while (true);
2677 }
2678 > async.ts
2679 > public readBufferedOrThrow(): T | typeof AsyncReaderEndOfStream {
2680 const value = this.peekBufferedOrThrow();
2681 this._buffer.shift();
2682 return value;
2683 }
2684 > async.ts
2685 > public async consumeToEnd(): Promise<void> {
2686 while (!this.endOfStream) {
2687 await this.read();
2688 }
2689 }
2690 > async.ts
2691 > public async peek(): Promise<T | typeof AsyncReaderEndOfStream> {
2692 if (this._buffer.length === 0 && !this._atEnd) {
2693 await this._extendBuffer();
2698 return this._buffer[0];
2699 }
2700 > async.ts
2701 > public peekBufferedOrThrow(): T | typeof AsyncReaderEndOfStream {
2702 if (this._buffer.length === 0) {
2703 if (this._atEnd) {
2709 return this._buffer[0];
2710 }
2711 > async.ts
2712 > public async peekTimeout(timeoutMs: number): Promise<T | typeof AsyncReaderEndOfStream | undefined> {
2713 if (this._buffer.length === 0 && !this._atEnd) {
2714 await raceTimeout(this._extendBuffer(), timeoutMs);
2722 return this._buffer[0];
2723 }
2724 > async.ts
2725 > private _extendBuffer(): Promise<void> {
2726 if (this._atEnd) {
2727 return Promise.resolve();
2742 return this._extendBufferPromise;
2743 }
2744 > } async.ts
2745 >
2746 > export function createTimeout(ms: number, cb: () => void): IDisposable {
2747 const t = setTimeout(cb, ms);
2748 return toDisposable(() => clearTimeout(t));
src/vs/platform/files/common/files.ts 1430 covered LOC · 75 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- files.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer, VSBufferReadable, VSBufferReadableStream } from '../../../base/common/buffer.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { Event } from '../../../base/common/event.js';
9 > import { IExpression, IRelativePattern } from '../../../base/common/glob.js';
10 > import { IDisposable } from '../../../base/common/lifecycle.js';
11 > import { TernarySearchTree } from '../../../base/common/ternarySearchTree.js';
12 > import { sep } from '../../../base/common/path.js';
13 > import { ReadableStreamEvents } from '../../../base/common/stream.js';
14 > import { startsWithIgnoreCase } from '../../../base/common/strings.js';
15 > import { isNumber } from '../../../base/common/types.js';
16 > import { URI } from '../../../base/common/uri.js';
17 > import { localize } from '../../../nls.js';
18 > import { createDecorator } from '../../instantiation/common/instantiation.js';
19 > import { isWeb } from '../../../base/common/platform.js';
20 > import { Schemas } from '../../../base/common/network.js';
21 > import { IMarkdownString } from '../../../base/common/htmlContent.js';
22 > import { Lazy } from '../../../base/common/lazy.js';
23 >
24 > //#region file service & providers
25 >
26 > export const IFileService = createDecorator<IFileService>('fileService');
27 >
28 > export interface IFileService {
29 >
30 > readonly _serviceBrand: undefined;
31 >
32 > /**
33 > * An event that is fired when a file system provider is added or removed
34 > */
35 > readonly onDidChangeFileSystemProviderRegistrations: Event<IFileSystemProviderRegistrationEvent>;
36 >
37 > /**
38 > * An event that is fired when a registered file system provider changes its capabilities.
39 > */
40 > readonly onDidChangeFileSystemProviderCapabilities: Event<IFileSystemProviderCapabilitiesChangeEvent>;
41 >
42 > /**
43 > * An event that is fired when a file system provider is about to be activated. Listeners
44 > * can join this event with a long running promise to help in the activation process.
45 > */
46 > readonly onWillActivateFileSystemProvider: Event<IFileSystemProviderActivationEvent>;
47 >
48 > /**
49 > * Registers a file system provider for a certain scheme.
50 > */
51 > registerProvider(scheme: string, provider: IFileSystemProvider): IDisposable;
52 >
53 > /**
54 > * Returns a file system provider for a certain scheme.
55 > */
56 > getProvider(scheme: string): IFileSystemProvider | undefined;
57 >
58 > /**
59 > * Tries to activate a provider with the given scheme.
60 > */
61 > activateProvider(scheme: string): Promise<void>;
62 >
63 > /**
64 > * Checks if this file service can handle the given resource by
65 > * first activating any extension that wants to be activated
66 > * on the provided resource scheme to include extensions that
67 > * contribute file system providers for the given resource.
68 > */
69 > canHandleResource(resource: URI): Promise<boolean>;
70 >
71 > /**
72 > * Checks if the file service has a registered provider for the
73 > * provided resource.
74 > *
75 > * Note: this does NOT account for contributed providers from
76 > * extensions that have not been activated yet. To include those,
77 > * consider to call `await fileService.canHandleResource(resource)`.
78 > */
79 > hasProvider(resource: URI): boolean;
80 >
81 > /**
82 > * Checks if the provider for the provided resource has the provided file system capability.
83 > */
84 > hasCapability(resource: URI, capability: FileSystemProviderCapabilities): boolean;
85 >
86 > /**
87 > * List the schemes and capabilities for registered file system providers
88 > */
89 > listCapabilities(): Iterable<{ scheme: string; capabilities: FileSystemProviderCapabilities }>;
90 >
91 > /**
92 > * Allows to listen for file changes. The event will fire for every file within the opened workspace
93 > * (if any) as well as all files that have been watched explicitly using the #watch() API.
94 > */
95 > readonly onDidFilesChange: Event<FileChangesEvent>;
96 >
97 > /**
98 > * An event that is fired upon successful completion of a certain file operation.
99 > */
100 > readonly onDidRunOperation: Event<FileOperationEvent>;
101 >
102 > /**
103 > * Resolve the properties of a file/folder identified by the resource. For a folder, children
104 > * information is resolved as well depending on the provided options. Use `stat()` method if
105 > * you do not need children information.
106 > *
107 > * If the optional parameter "resolveTo" is specified in options, the stat service is asked
108 > * to provide a stat object that should contain the full graph of folders up to all of the
109 > * target resources.
110 > *
111 > * If the optional parameter "resolveSingleChildDescendants" is specified in options,
112 > * the stat service is asked to automatically resolve child folders that only
113 > * contain a single element.
114 > *
115 > * If the optional parameter "resolveMetadata" is specified in options,
116 > * the stat will contain metadata information such as size, mtime and etag.
117 > */
118 > resolve(resource: URI, options: IResolveMetadataFileOptions): Promise<IFileStatWithMetadata>;
119 > resolve(resource: URI, options?: IResolveFileOptions): Promise<IFileStat>;
120 >
121 > /**
122 > * Same as `resolve()` but supports resolving multiple resources in parallel.
123 > *
124 > * If one of the resolve targets fails to resolve returns a fake `IFileStat` instead of
125 > * making the whole call fail.
126 > */
127 > resolveAll(toResolve: { resource: URI; options: IResolveMetadataFileOptions }[]): Promise<IFileStatResult[]>;
128 > resolveAll(toResolve: { resource: URI; options?: IResolveFileOptions }[]): Promise<IFileStatResult[]>;
129 >
130 > /**
131 > * Same as `resolve()` but without resolving the children of a folder if the
132 > * resource is pointing to a folder.
133 > */
134 > stat(resource: URI): Promise<IFileStatWithPartialMetadata>;
135 >
136 > /**
137 > * Attempts to resolve the real path of the provided resource. The real path can be
138 > * different from the resource path for example when it is a symlink.
139 > *
140 > * Will return `undefined` if the real path cannot be resolved.
141 > */
142 > realpath(resource: URI): Promise<URI | undefined>;
143 >
144 > /**
145 > * Finds out if a file/folder identified by the resource exists.
146 > */
147 > exists(resource: URI): Promise<boolean>;
148 >
149 > /**
150 > * Read the contents of the provided resource unbuffered.
151 > */
152 > readFile(resource: URI, options?: IReadFileOptions, token?: CancellationToken): Promise<IFileContent>;
153 >
154 > /**
155 > * Read the contents of the provided resource buffered as stream.
156 > */
157 > readFileStream(resource: URI, options?: IReadFileStreamOptions, token?: CancellationToken): Promise<IFileStreamContent>;
158 >
159 > /**
160 > * Updates the content replacing its previous value.
161 > * If `options.append` is true, appends content to the end of the file instead.
162 > *
163 > * Emits a `FileOperation.WRITE` file operation event when successful.
164 > */
165 > writeFile(resource: URI, bufferOrReadableOrStream: VSBuffer | VSBufferReadable | VSBufferReadableStream, options?: IWriteFileOptions): Promise<IFileStatWithMetadata>;
166 >
167 > /**
168 > * Moves the file/folder to a new path identified by the resource.
169 > *
170 > * The optional parameter overwrite can be set to replace an existing file at the location.
171 > *
172 > * Emits a `FileOperation.MOVE` file operation event when successful.
173 > */
174 > move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>;
175 >
176 > /**
177 > * Find out if a move operation is possible given the arguments. No changes on disk will
178 > * be performed. Returns an Error if the operation cannot be done.
179 > */
180 > canMove(source: URI, target: URI, overwrite?: boolean): Promise<Error | true>;
181 >
182 > /**
183 > * Copies the file/folder to a path identified by the resource. A folder is copied
184 > * recursively.
185 > *
186 > * Emits a `FileOperation.COPY` file operation event when successful.
187 > */
188 > copy(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata>;
189 >
190 > /**
191 > * Find out if a copy operation is possible given the arguments. No changes on disk will
192 > * be performed. Returns an Error if the operation cannot be done.
193 > */
194 > canCopy(source: URI, target: URI, overwrite?: boolean): Promise<Error | true>;
195 >
196 > /**
197 > * Clones a file to a path identified by the resource. Folders are not supported.
198 > *
199 > * If the target path exists, it will be overwritten.
200 > */
201 > cloneFile(source: URI, target: URI): Promise<void>;
202 >
203 > /**
204 > * Creates a new file with the given path and optional contents. The returned promise
205 > * will have the stat model object as a result.
206 > *
207 > * The optional parameter content can be used as value to fill into the new file.
208 > *
209 > * Emits a `FileOperation.CREATE` file operation event when successful.
210 > */
211 > createFile(resource: URI, bufferOrReadableOrStream?: VSBuffer | VSBufferReadable | VSBufferReadableStream, options?: ICreateFileOptions): Promise<IFileStatWithMetadata>;
212 >
213 > /**
214 > * Find out if a file create operation is possible given the arguments. No changes on disk will
215 > * be performed. Returns an Error if the operation cannot be done.
216 > */
217 > canCreateFile(resource: URI, options?: ICreateFileOptions): Promise<Error | true>;
218 >
219 > /**
220 > * Creates a new folder with the given path. The returned promise
221 > * will have the stat model object as a result.
222 > *
223 > * Emits a `FileOperation.CREATE` file operation event when successful.
224 > */
225 > createFolder(resource: URI): Promise<IFileStatWithMetadata>;
226 >
227 > /**
228 > * Deletes the provided file. The optional useTrash parameter allows to
229 > * move the file to trash. The optional recursive parameter allows to delete
230 > * non-empty folders recursively.
231 > *
232 > * Emits a `FileOperation.DELETE` file operation event when successful.
233 > */
234 > del(resource: URI, options?: Partial<IFileDeleteOptions>): Promise<void>;
235 >
236 > /**
237 > * Find out if a delete operation is possible given the arguments. No changes on disk will
238 > * be performed. Returns an Error if the operation cannot be done.
239 > */
240 > canDelete(resource: URI, options?: Partial<IFileDeleteOptions>): Promise<Error | true>;
241 >
242 > /**
243 > * An event that signals an error when watching for file changes.
244 > */
245 > readonly onDidWatchError: Event<Error>;
246 >
247 > /**
248 > * Allows to start a watcher that reports file/folder change events on the provided resource.
249 > *
250 > * The watcher runs correlated and thus, file events will be reported on the returned
251 > * `IFileSystemWatcher` and not on the generic `IFileService.onDidFilesChange` event.
252 > *
253 > * Note: only non-recursive file watching supports event correlation for now.
254 > */
255 > createWatcher(resource: URI, options: IWatchOptionsWithoutCorrelation & { recursive: false }): IFileSystemWatcher;
256 >
257 > /**
258 > * Allows to start a watcher that reports file/folder change events on the provided resource.
259 > *
260 > * The watcher runs uncorrelated and thus will report all events from `IFileService.onDidFilesChange`.
261 > * This means, most listeners in the application will receive your events. It is encouraged to
262 > * use correlated watchers (via `IWatchOptionsWithCorrelation`) to limit events to your listener.
263 > */
264 > watch(resource: URI, options?: IWatchOptionsWithoutCorrelation): IDisposable;
265 >
266 > /**
267 > * Frees up any resources occupied by this service.
268 > */
269 > dispose(): void;
270 > }
271 >
272 > export interface IFileOverwriteOptions {
273 >
274 > /**
275 > * Set to `true` to overwrite a file if it exists. Will
276 > * throw an error otherwise if the file does exist.
277 > */
278 > readonly overwrite: boolean;
279 > }
280 >
281 > export interface IFileUnlockOptions {
282 >
283 > /**
284 > * Set to `true` to try to remove any write locks the file might
285 > * have. A file that is write locked will throw an error for any
286 > * attempt to write to unless `unlock: true` is provided.
287 > */
288 > readonly unlock: boolean;
289 > }
290 >
291 > export interface IFileAtomicReadOptions {
292 >
293 > /**
294 > * The optional `atomic` flag can be used to make sure
295 > * the `readFile` method is not running in parallel with
296 > * any `write` operations in the same process.
297 > *
298 > * Typically you should not need to use this flag but if
299 > * for example you are quickly reading a file right after
300 > * a file event occurred and the file changes a lot, there
301 > * is a chance that a read returns an empty or partial file
302 > * because a pending write has not finished yet.
303 > *
304 > * Note: this does not prevent the file from being written
305 > * to from a different process. If you need such atomic
306 > * operations, you better use a real database as storage.
307 > */
308 > readonly atomic: boolean;
309 > }
310 >
311 > export interface IFileAtomicOptions {
312 >
313 > /**
314 > * The postfix is used to create a temporary file based
315 > * on the original resource. The resulting temporary
316 > * file will be in the same folder as the resource and
317 > * have `postfix` appended to the resource name.
318 > *
319 > * Example: given a file resource `file:///some/path/foo.txt`
320 > * and a postfix `.vsctmp`, the temporary file will be
321 > * created as `file:///some/path/foo.txt.vsctmp`.
322 > */
323 > readonly postfix: string;
324 > }
325 >
326 > export interface IFileAtomicWriteOptions {
327 >
328 > /**
329 > * The optional `atomic` flag can be used to make sure
330 > * the `writeFile` method updates the target file atomically
331 > * by first writing to a temporary file in the same folder
332 > * and then renaming it over the target.
333 > */
334 > readonly atomic: IFileAtomicOptions | false;
335 > }
336 >
337 > export interface IFileAtomicDeleteOptions {
338 >
339 > /**
340 > * The optional `atomic` flag can be used to make sure
341 > * the `delete` method deletes the target atomically by
342 > * first renaming it to a temporary resource in the same
343 > * folder and then deleting it.
344 > */
345 > readonly atomic: IFileAtomicOptions | false;
346 > }
347 >
348 > export interface IFileReadLimits {
349 >
350 > /**
351 > * If the file exceeds the given size, an error of kind
352 > * `FILE_TOO_LARGE` will be thrown.
353 > */
354 > size?: number;
355 > }
356 >
357 > export interface IFileReadStreamOptions {
358 >
359 > /**
360 > * Is an integer specifying where to begin reading from in the file. If position is undefined,
361 > * data will be read from the current file position.
362 > */
363 > readonly position?: number;
364 >
365 > /**
366 > * Is an integer specifying how many bytes to read from the file. By default, all bytes
367 > * will be read.
368 > */
369 > readonly length?: number;
370 >
371 > /**
372 > * If provided, the size of the file will be checked against the limits
373 > * and an error will be thrown if any limit is exceeded.
374 > */
375 > readonly limits?: IFileReadLimits;
376 > }
377 >
378 > export interface IFileWriteOptions extends IFileOverwriteOptions, IFileUnlockOptions, IFileAtomicWriteOptions {
379 >
380 > /**
381 > * Set to `true` to create a file when it does not exist. Will
382 > * throw an error otherwise if the file does not exist.
383 > */
384 > readonly create: boolean;
385 >
386 > /**
387 > * Set to `true` to append content to the end of the file. Implies `create: true`,
388 > * and set only when the corresponding `FileAppend` capability is defined.
389 > */
390 > readonly append?: boolean;
391 > }
392 >
393 > export type IFileOpenOptions = IFileOpenForReadOptions | IFileOpenForWriteOptions;
394 >
395 > export function isFileOpenForWriteOptions(options: IFileOpenOptions): options is IFileOpenForWriteOptions {
396 return options.create === true;
397 }
398 > files.ts
399 > export interface IFileOpenForReadOptions {
400 >
401 > /**
402 > * A hint that the file should be opened for reading only.
403 > */
404 > readonly create: false;
405 > }
406 >
407 > export interface IFileOpenForWriteOptions extends IFileUnlockOptions {
408 >
409 > /**
410 > * A hint that the file should be opened for reading and writing.
411 > */
412 > readonly create: true;
413 >
414 > /**
415 > * Open the file in append mode. This will write data to the
416 > * end of the file.
417 > */
418 > readonly append?: boolean;
419 > }
420 >
421 > export interface IFileDeleteOptions {
422 >
423 > /**
424 > * Set to `true` to recursively delete any children of the file. This
425 > * only applies to folders and can lead to an error unless provided
426 > * if the folder is not empty.
427 > */
428 > readonly recursive: boolean;
429 >
430 > /**
431 > * Set to `true` to attempt to move the file to trash
432 > * instead of deleting it permanently from disk.
433 > *
434 > * This option maybe not be supported on all providers.
435 > */
436 > readonly useTrash: boolean;
437 >
438 > /**
439 > * The optional `atomic` flag can be used to make sure
440 > * the `delete` method deletes the target atomically by
441 > * first renaming it to a temporary resource in the same
442 > * folder and then deleting it.
443 > *
444 > * This option maybe not be supported on all providers.
445 > */
446 > readonly atomic: IFileAtomicOptions | false;
447 > }
448 >
449 > export enum FileType {
450 >
451 > /**
452 > * File is unknown (neither file, directory nor symbolic link).
453 > */
454 > Unknown = 0,
455 >
456 > /**
457 > * File is a normal file.
458 > */
459 > File = 1,
460 >
461 > /**
462 > * File is a directory.
463 > */
464 > Directory = 2,
465 >
466 > /**
467 > * File is a symbolic link.
468 > *
469 > * Note: even when the file is a symbolic link, you can test for
470 > * `FileType.File` and `FileType.Directory` to know the type of
471 > * the target the link points to.
472 > */
473 > SymbolicLink = 64
474 > }
475 >
476 > export enum FilePermission {
477 >
478 > /**
479 > * File is readonly. Components like editors should not
480 > * offer to edit the contents.
481 > */
482 > Readonly = 1,
483 >
484 > /**
485 > * File is locked. Components like editors should offer
486 > * to edit the contents and ask the user upon saving to
487 > * remove the lock.
488 > */
489 > Locked = 2,
490 >
491 > /**
492 > * File is executable. Relevant for Unix-like systems where
493 > * the executable bit determines if a file can be run.
494 > */
495 > Executable = 4
496 > }
497 >
498 > export interface IStat {
499 >
500 > /**
501 > * The file type.
502 > */
503 > readonly type: FileType;
504 >
505 > /**
506 > * The last modification date represented as millis from unix epoch.
507 > */
508 > readonly mtime: number;
509 >
510 > /**
511 > * The creation date represented as millis from unix epoch.
512 > */
513 > readonly ctime: number;
514 >
515 > /**
516 > * The size of the file in bytes.
517 > */
518 > readonly size: number;
519 >
520 > /**
521 > * The file permissions.
522 > */
523 > readonly permissions?: FilePermission;
524 > }
525 >
526 > export interface IWatchOptionsWithoutCorrelation {
527 >
528 > /**
529 > * Set to `true` to watch for changes recursively in a folder
530 > * and all of its children.
531 > */
532 > recursive: boolean;
533 >
534 > /**
535 > * A set of glob patterns or paths to exclude from watching.
536 > * Paths can be relative or absolute and when relative are
537 > * resolved against the watched folder. Glob patterns are
538 > * always matched relative to the watched folder.
539 > */
540 > excludes: string[];
541 >
542 > /**
543 > * An optional set of glob patterns or paths to include for
544 > * watching. If not provided, all paths are considered for
545 > * events.
546 > * Paths can be relative or absolute and when relative are
547 > * resolved against the watched folder. Glob patterns are
548 > * always matched relative to the watched folder.
549 > */
550 > includes?: Array<string | IRelativePattern>;
551 >
552 > /**
553 > * If provided, allows to filter the events that the watcher should consider
554 > * for emitting. If not provided, all events are emitted.
555 > *
556 > * For example, to emit added and updated events, set to:
557 > * `FileChangeFilter.ADDED | FileChangeFilter.UPDATED`.
558 > */
559 > filter?: FileChangeFilter;
560 > }
561 >
562 > export interface IWatchOptions extends IWatchOptionsWithoutCorrelation {
563 >
564 > /**
565 > * If provided, file change events from the watcher that
566 > * are a result of this watch request will carry the same
567 > * id.
568 > */
569 > readonly correlationId?: number;
570 > }
571 >
572 > export const enum FileChangeFilter {
573 > UPDATED = 1 << 1,
574 > ADDED = 1 << 2,
575 > DELETED = 1 << 3
576 > }
577 >
578 > export interface IWatchOptionsWithCorrelation extends IWatchOptions {
579 > readonly correlationId: number;
580 > }
581 >
582 > export interface IFileSystemWatcher extends IDisposable {
583 >
584 > /**
585 > * An event which fires on file/folder change only for changes
586 > * that correlate to the watch request with matching correlation
587 > * identifier.
588 > */
589 > readonly onDidChange: Event<FileChangesEvent>;
590 > }
591 >
592 > export function isFileSystemWatcher(thing: unknown): thing is IFileSystemWatcher {
593 const candidate = thing as IFileSystemWatcher | undefined;
594
595 return !!candidate && typeof candidate.onDidChange === 'function';
596 }
597 > files.ts
598 > export const enum FileSystemProviderCapabilities {
599 >
600 > /**
601 > * No capabilities.
602 > */
603 > None = 0,
604 >
605 > /**
606 > * Provider supports unbuffered read/write.
607 > */
608 > FileReadWrite = 1 << 1,
609 >
610 > /**
611 > * Provider supports open/read/write/close low level file operations.
612 > */
613 > FileOpenReadWriteClose = 1 << 2,
614 >
615 > /**
616 > * Provider supports stream based reading.
617 > */
618 > FileReadStream = 1 << 4,
619 >
620 > /**
621 > * Provider supports copy operation.
622 > */
623 > FileFolderCopy = 1 << 3,
624 >
625 > /**
626 > * Provider is path case sensitive.
627 > */
628 > PathCaseSensitive = 1 << 10,
629 >
630 > /**
631 > * All files of the provider are readonly.
632 > */
633 > Readonly = 1 << 11,
634 >
635 > /**
636 > * Provider supports to delete via trash.
637 > */
638 > Trash = 1 << 12,
639 >
640 > /**
641 > * Provider support to unlock files for writing.
642 > */
643 > FileWriteUnlock = 1 << 13,
644 >
645 > /**
646 > * Provider support to read files atomically. This implies the
647 > * provider provides the `FileReadWrite` capability too.
648 > */
649 > FileAtomicRead = 1 << 14,
650 >
651 > /**
652 > * Provider support to write files atomically. This implies the
653 > * provider provides the `FileReadWrite` capability too.
654 > */
655 > FileAtomicWrite = 1 << 15,
656 >
657 > /**
658 > * Provider support to delete atomically.
659 > */
660 > FileAtomicDelete = 1 << 16,
661 >
662 > /**
663 > * Provider support to clone files atomically.
664 > */
665 > FileClone = 1 << 17,
666 >
667 > /**
668 > * Provider support to resolve real paths.
669 > */
670 > FileRealpath = 1 << 18,
671 >
672 > /**
673 > * Provider support to append to files.
674 > */
675 > FileAppend = 1 << 19
676 > }
677 >
678 > export interface IFileSystemProvider {
679 >
680 > readonly capabilities: FileSystemProviderCapabilities;
681 > readonly onDidChangeCapabilities: Event<void>;
682 >
683 > readonly onDidChangeFile: Event<readonly IFileChange[]>;
684 > readonly onDidWatchError?: Event<string>;
685 > watch(resource: URI, opts: IWatchOptions): IDisposable;
686 >
687 > stat(resource: URI): Promise<IStat>;
688 > mkdir(resource: URI): Promise<void>;
689 > readdir(resource: URI): Promise<[string, FileType][]>;
690 > delete(resource: URI, opts: IFileDeleteOptions): Promise<void>;
691 >
692 > rename(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void>;
693 > copy?(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void>;
694 >
695 > readFile?(resource: URI): Promise<Uint8Array>;
696 > writeFile?(resource: URI, content: Uint8Array, opts: IFileWriteOptions): Promise<void>;
697 >
698 > readFileStream?(resource: URI, opts: IFileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array>;
699 >
700 > open?(resource: URI, opts: IFileOpenOptions): Promise<number>;
701 > close?(fd: number): Promise<void>;
702 > read?(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>;
703 > write?(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>;
704 >
705 > cloneFile?(from: URI, to: URI): Promise<void>;
706 > }
707 >
708 > export interface IFileSystemProviderWithFileReadWriteCapability extends IFileSystemProvider {
709 > readFile(resource: URI): Promise<Uint8Array>;
710 > writeFile(resource: URI, content: Uint8Array, opts: IFileWriteOptions): Promise<void>;
711 > }
712 >
713 > export function hasReadWriteCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileReadWriteCapability {
714 > return !!(provider.capabilities & FileSystemProviderCapabilities.FileReadWrite); files.ts
715 > }
716 > files.ts
717 > export function hasFileAppendCapability(provider: IFileSystemProvider): boolean {
718 return !!(provider.capabilities & FileSystemProviderCapabilities.FileAppend);
719 }
720 > files.ts
721 > export interface IFileSystemProviderWithFileFolderCopyCapability extends IFileSystemProvider {
722 > copy(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void>;
723 > }
724 >
725 > export function hasFileFolderCopyCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileFolderCopyCapability {
726 return !!(provider.capabilities & FileSystemProviderCapabilities.FileFolderCopy);
727 }
728 > files.ts
729 > export interface IFileSystemProviderWithFileCloneCapability extends IFileSystemProvider {
730 > cloneFile(from: URI, to: URI): Promise<void>;
731 > }
732 >
733 > export function hasFileCloneCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileCloneCapability {
734 return !!(provider.capabilities & FileSystemProviderCapabilities.FileClone);
735 }
736 > files.ts
737 > export interface IFileSystemProviderWithFileRealpathCapability extends IFileSystemProvider {
738 > realpath(resource: URI): Promise<string>;
739 > }
740 >
741 > export function hasFileRealpathCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileRealpathCapability {
742 return !!(provider.capabilities & FileSystemProviderCapabilities.FileRealpath);
743 }
744 > files.ts
745 > export interface IFileSystemProviderWithOpenReadWriteCloseCapability extends IFileSystemProvider {
746 > open(resource: URI, opts: IFileOpenOptions): Promise<number>;
747 > close(fd: number): Promise<void>;
748 > read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>;
749 > write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number>;
750 > }
751 >
752 > export function hasOpenReadWriteCloseCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithOpenReadWriteCloseCapability {
753 > return !!(provider.capabilities & FileSystemProviderCapabilities.FileOpenReadWriteClose); files.ts
754 > }
755 > files.ts
756 > export interface IFileSystemProviderWithFileReadStreamCapability extends IFileSystemProvider {
757 > readFileStream(resource: URI, opts: IFileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array>;
758 > }
759 >
760 > export function hasFileReadStreamCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileReadStreamCapability {
761 return !!(provider.capabilities & FileSystemProviderCapabilities.FileReadStream);
762 }
763 > files.ts
764 > export interface IFileSystemProviderWithFileAtomicReadCapability extends IFileSystemProvider {
765 > readFile(resource: URI, opts?: IFileAtomicReadOptions): Promise<Uint8Array>;
766 > enforceAtomicReadFile?(resource: URI): boolean;
767 > }
768 >
769 > export function hasFileAtomicReadCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileAtomicReadCapability {
770 > if (!hasReadWriteCapability(provider)) { files.ts
771 return false; // we require the `FileReadWrite` capability too
772 }
773 > files.ts
774 > return !!(provider.capabilities & FileSystemProviderCapabilities.FileAtomicRead);
775 > }
776 > files.ts
777 > export interface IFileSystemProviderWithFileAtomicWriteCapability extends IFileSystemProvider {
778 > writeFile(resource: URI, contents: Uint8Array, opts?: IFileAtomicWriteOptions): Promise<void>;
779 > enforceAtomicWriteFile?(resource: URI): IFileAtomicOptions | false;
780 > }
781 >
782 > export function hasFileAtomicWriteCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileAtomicWriteCapability {
783 > if (!hasReadWriteCapability(provider)) { files.ts
784 return false; // we require the `FileReadWrite` capability too
785 }
786 > files.ts
787 > return !!(provider.capabilities & FileSystemProviderCapabilities.FileAtomicWrite);
788 > }
789 > files.ts
790 > export interface IFileSystemProviderWithFileAtomicDeleteCapability extends IFileSystemProvider {
791 > delete(resource: URI, opts: IFileAtomicDeleteOptions): Promise<void>;
792 > enforceAtomicDelete?(resource: URI): IFileAtomicOptions | false;
793 > }
794 >
795 > export function hasFileAtomicDeleteCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithFileAtomicDeleteCapability {
796 > return !!(provider.capabilities & FileSystemProviderCapabilities.FileAtomicDelete); files.ts
797 > }
798 > files.ts
799 > export interface IFileSystemProviderWithReadonlyCapability extends IFileSystemProvider {
800 >
801 > readonly capabilities: FileSystemProviderCapabilities.Readonly & FileSystemProviderCapabilities;
802 >
803 > /**
804 > * An optional message to show in the UI to explain why the file system is readonly.
805 > */
806 > readonly readOnlyMessage?: IMarkdownString;
807 > }
808 >
809 > export function hasReadonlyCapability(provider: IFileSystemProvider): provider is IFileSystemProviderWithReadonlyCapability {
810 return !!(provider.capabilities & FileSystemProviderCapabilities.Readonly);
811 }
812 > files.ts
813 > export enum FileSystemProviderErrorCode {
814 > FileExists = 'EntryExists',
815 > FileNotFound = 'EntryNotFound',
816 > FileNotADirectory = 'EntryNotADirectory',
817 > FileIsADirectory = 'EntryIsADirectory',
818 > FileExceedsStorageQuota = 'EntryExceedsStorageQuota',
819 > FileTooLarge = 'EntryTooLarge',
820 > FileWriteLocked = 'EntryWriteLocked',
821 > NoPermissions = 'NoPermissions',
822 > Unavailable = 'Unavailable',
823 > Unknown = 'Unknown'
824 > }
825 >
826 > export interface IFileSystemProviderError extends Error {
827 > readonly name: string;
828 > readonly code: FileSystemProviderErrorCode;
829 > }
830 >
831 > export class FileSystemProviderError extends Error implements IFileSystemProviderError {
832 >
833 > static create(error: Error | string, code: FileSystemProviderErrorCode): FileSystemProviderError {
834 > const providerError = new FileSystemProviderError(error.toString(), code);
835 > markAsFileSystemProviderError(providerError, code);
836 >
837 > return providerError;
838 > }
839 >
840 > private constructor(message: string, readonly code: FileSystemProviderErrorCode) {
841 > super(message); files.ts
842 > }
843 > } files.ts
844 >
845 > export function createFileSystemProviderError(error: Error | string, code: FileSystemProviderErrorCode): FileSystemProviderError {
846 > return FileSystemProviderError.create(error, code); files.ts
847 > }
848 > files.ts
849 > export function ensureFileSystemProviderError(error?: Error): Error {
850 > if (!error) { files.ts
851 return createFileSystemProviderError(localize('unknownError', "Unknown Error"), FileSystemProviderErrorCode.Unknown); // https://github.com/microsoft/vscode/issues/72798
852 }
853 > files.ts
854 > return error;
855 > }
856 > files.ts
857 > export function markAsFileSystemProviderError(error: Error, code: FileSystemProviderErrorCode): Error {
858 > error.name = code ? `${code} (FileSystemError)` : `FileSystemError`; files.ts
859 >
860 > return error;
861 > }
862 > files.ts
863 > export function toFileSystemProviderErrorCode(error: Error | undefined | null): FileSystemProviderErrorCode {
864 > files.ts
865 > // Guard against abuse
866 > if (!error) {
867 return FileSystemProviderErrorCode.Unknown;
868 }
869 > files.ts
870 > // FileSystemProviderError comes with the code
871 > if (error instanceof FileSystemProviderError) {
872 > return error.code; files.ts
873 > }
874
875 // Any other error, check for name match by assuming that the error
882 switch (match[1]) {
883 case FileSystemProviderErrorCode.FileExists: return FileSystemProviderErrorCode.FileExists;
884 > case FileSystemProviderErrorCode.FileIsADirectory: return FileSystemProviderErrorCode.FileIsADirectory; files.ts
885 > case FileSystemProviderErrorCode.FileNotADirectory: return FileSystemProviderErrorCode.FileNotADirectory;
886 > case FileSystemProviderErrorCode.FileNotFound: return FileSystemProviderErrorCode.FileNotFound;
887 > case FileSystemProviderErrorCode.FileTooLarge: return FileSystemProviderErrorCode.FileTooLarge;
888 > case FileSystemProviderErrorCode.FileWriteLocked: return FileSystemProviderErrorCode.FileWriteLocked;
889 > case FileSystemProviderErrorCode.NoPermissions: return FileSystemProviderErrorCode.NoPermissions;
890 > case FileSystemProviderErrorCode.Unavailable: return FileSystemProviderErrorCode.Unavailable;
891 > }
892
893 return FileSystemProviderErrorCode.Unknown;
894 }
895 > files.ts
896 > export function toFileOperationResult(error: Error): FileOperationResult {
897 > files.ts
898 > // FileSystemProviderError comes with the result already
899 > if (error instanceof FileOperationError) {
900 > return error.fileOperationResult; files.ts
901 > }
902
903 // Otherwise try to find from code
905 case FileSystemProviderErrorCode.FileNotFound:
906 return FileOperationResult.FILE_NOT_FOUND;
907 > case FileSystemProviderErrorCode.FileIsADirectory: files.ts
908 return FileOperationResult.FILE_IS_DIRECTORY;
909 > case FileSystemProviderErrorCode.FileNotADirectory: files.ts
910 return FileOperationResult.FILE_NOT_DIRECTORY;
911 > case FileSystemProviderErrorCode.FileWriteLocked: files.ts
912 return FileOperationResult.FILE_WRITE_LOCKED;
913 > case FileSystemProviderErrorCode.NoPermissions: files.ts
914 return FileOperationResult.FILE_PERMISSION_DENIED;
915 > case FileSystemProviderErrorCode.FileExists: files.ts
916 return FileOperationResult.FILE_MOVE_CONFLICT;
917 > case FileSystemProviderErrorCode.FileTooLarge: files.ts
918 return FileOperationResult.FILE_TOO_LARGE;
919 > default: files.ts
920 return FileOperationResult.FILE_OTHER_ERROR;
921 > } files.ts
922 > }
923 > files.ts
924 > export interface IFileSystemProviderRegistrationEvent {
925 > readonly added: boolean;
926 > readonly scheme: string;
927 > readonly provider?: IFileSystemProvider;
928 > }
929 >
930 > export interface IFileSystemProviderCapabilitiesChangeEvent {
931 > readonly provider: IFileSystemProvider;
932 > readonly scheme: string;
933 > }
934 >
935 > export interface IFileSystemProviderActivationEvent {
936 > readonly scheme: string;
937 > join(promise: Promise<void>): void;
938 > }
939 >
940 > export const enum FileOperation {
941 > CREATE,
942 > DELETE,
943 > MOVE,
944 > COPY,
945 > WRITE
946 > }
947 >
948 > export interface IFileOperationEvent {
949 >
950 > readonly resource: URI;
951 > readonly operation: FileOperation;
952 >
953 > isOperation(operation: FileOperation.DELETE | FileOperation.WRITE): boolean;
954 > isOperation(operation: FileOperation.CREATE | FileOperation.MOVE | FileOperation.COPY): this is IFileOperationEventWithMetadata;
955 > }
956 >
957 > export interface IFileOperationEventWithMetadata extends IFileOperationEvent {
958 > readonly target: IFileStatWithMetadata;
959 > }
960 >
961 > export class FileOperationEvent implements IFileOperationEvent {
962 >
963 > constructor(resource: URI, operation: FileOperation.DELETE | FileOperation.WRITE);
964 > constructor(resource: URI, operation: FileOperation.CREATE | FileOperation.MOVE | FileOperation.COPY, target: IFileStatWithMetadata);
965 > constructor(readonly resource: URI, readonly operation: FileOperation, readonly target?: IFileStatWithMetadata) { }
966 >
967 > isOperation(operation: FileOperation.DELETE | FileOperation.WRITE): boolean;
968 > isOperation(operation: FileOperation.CREATE | FileOperation.MOVE | FileOperation.COPY): this is IFileOperationEventWithMetadata;
969 > isOperation(operation: FileOperation): boolean {
970 > return this.operation === operation; files.ts
971 > }
972 > } files.ts
973 >
974 > /**
975 > * Possible changes that can occur to a file.
976 > */
977 > export const enum FileChangeType {
978 > UPDATED,
979 > ADDED,
980 > DELETED
981 > }
982 >
983 > /**
984 > * Identifies a single change in a file.
985 > */
986 > export interface IFileChange {
987 >
988 > /**
989 > * The type of change that occurred to the file.
990 > */
991 > type: FileChangeType;
992 >
993 > /**
994 > * The unified resource identifier of the file that changed.
995 > */
996 > readonly resource: URI;
997 >
998 > /**
999 > * If provided when starting the file watcher, the correlation
1000 > * identifier will match the original file watching request as
1001 > * a way to identify the original component that is interested
1002 > * in the change.
1003 > */
1004 > readonly cId?: number;
1005 > }
1006 >
1007 > export class FileChangesEvent {
1008 >
1009 > private static readonly MIXED_CORRELATION = null;
1010 >
1011 > private readonly correlationId: number | undefined | typeof FileChangesEvent.MIXED_CORRELATION = undefined;
1012 >
1013 > constructor(changes: readonly IFileChange[], private readonly ignorePathCasing: boolean) {
1014 for (const change of changes) {
1015
1043 }
1044 }
1045 > files.ts
1046 > private readonly added = new Lazy(() => {
1047 > const added = TernarySearchTree.forUris<boolean>(() => this.ignorePathCasing); files.ts
1048 > added.fill(this.rawAdded.map(resource => [resource, true]));
1049 >
1050 > return added;
1051 > }); files.ts
1052 >
1053 > private readonly updated = new Lazy(() => {
1054 > const updated = TernarySearchTree.forUris<boolean>(() => this.ignorePathCasing); files.ts
1055 > updated.fill(this.rawUpdated.map(resource => [resource, true]));
1056 >
1057 > return updated;
1058 > }); files.ts
1059 >
1060 > private readonly deleted = new Lazy(() => {
1061 > const deleted = TernarySearchTree.forUris<boolean>(() => this.ignorePathCasing); files.ts
1062 > deleted.fill(this.rawDeleted.map(resource => [resource, true]));
1063 >
1064 > return deleted;
1065 > }); files.ts
1066 >
1067 > /**
1068 > * Find out if the file change events match the provided resource.
1069 > *
1070 > * Note: when passing `FileChangeType.DELETED`, we consider a match
1071 > * also when the parent of the resource got deleted.
1072 > */
1073 > contains(resource: URI, ...types: FileChangeType[]): boolean {
1074 return this.doContains(resource, { includeChildren: false }, ...types);
1075 }
1076 > files.ts
1077 > /**
1078 > * Find out if the file change events either match the provided
1079 > * resource, or contain a child of this resource.
1080 > */
1081 > affects(resource: URI, ...types: FileChangeType[]): boolean {
1082 return this.doContains(resource, { includeChildren: true }, ...types);
1083 }
1084 > files.ts
1085 > private doContains(resource: URI, options: { includeChildren: boolean }, ...types: FileChangeType[]): boolean {
1086 if (!resource) {
1087 return false;
1125 return false;
1126 }
1127 > files.ts
1128 > /**
1129 > * Returns if this event contains added files.
1130 > */
1131 > gotAdded(): boolean {
1132 return this.rawAdded.length > 0;
1133 }
1134 > files.ts
1135 > /**
1136 > * Returns if this event contains deleted files.
1137 > */
1138 > gotDeleted(): boolean {
1139 return this.rawDeleted.length > 0;
1140 }
1141 > files.ts
1142 > /**
1143 > * Returns if this event contains updated files.
1144 > */
1145 > gotUpdated(): boolean {
1146 return this.rawUpdated.length > 0;
1147 }
1148 > files.ts
1149 > /**
1150 > * Returns if this event contains changes that correlate to the
1151 > * provided `correlationId`.
1152 > *
1153 > * File change event correlation is an advanced watch feature that
1154 > * allows to identify from which watch request the events originate
1155 > * from. This correlation allows to route events specifically
1156 > * only to the requestor and not emit them to all listeners.
1157 > */
1158 > correlates(correlationId: number): boolean {
1159 return this.correlationId === correlationId;
1160 }
1161 > files.ts
1162 > /**
1163 > * Figure out if the event contains changes that correlate to one
1164 > * correlation identifier.
1165 > *
1166 > * File change event correlation is an advanced watch feature that
1167 > * allows to identify from which watch request the events originate
1168 > * from. This correlation allows to route events specifically
1169 > * only to the requestor and not emit them to all listeners.
1170 > */
1171 > hasCorrelation(): boolean {
1172 return typeof this.correlationId === 'number';
1173 }
1174 > files.ts
1175 > /**
1176 > * @deprecated use the `contains` or `affects` method to efficiently find
1177 > * out if the event relates to a given resource. these methods ensure:
1178 > * - that there is no expensive lookup needed (by using a `TernarySearchTree`)
1179 > * - correctly handles `FileChangeType.DELETED` events
1180 > */
1181 > readonly rawAdded: URI[] = [];
1182 >
1183 > /**
1184 > * @deprecated use the `contains` or `affects` method to efficiently find
1185 > * out if the event relates to a given resource. these methods ensure:
1186 > * - that there is no expensive lookup needed (by using a `TernarySearchTree`)
1187 > * - correctly handles `FileChangeType.DELETED` events
1188 > */
1189 > readonly rawUpdated: URI[] = [];
1190 >
1191 > /**
1192 > * @deprecated use the `contains` or `affects` method to efficiently find
1193 > * out if the event relates to a given resource. these methods ensure:
1194 > * - that there is no expensive lookup needed (by using a `TernarySearchTree`)
1195 > * - correctly handles `FileChangeType.DELETED` events
1196 > */
1197 > readonly rawDeleted: URI[] = [];
1198 > }
1199 >
1200 > export function isParent(path: string, candidate: string, ignoreCase?: boolean): boolean {
1201 if (!path || !candidate || path === candidate) {
1202 return false;
1217 return path.indexOf(candidate) === 0;
1218 }
1219 > files.ts
1220 > export interface IBaseFileStat {
1221 >
1222 > /**
1223 > * The unified resource identifier of this file or folder.
1224 > */
1225 > readonly resource: URI;
1226 >
1227 > /**
1228 > * The name which is the last segment
1229 > * of the {{path}}.
1230 > */
1231 > readonly name: string;
1232 >
1233 > /**
1234 > * The size of the file.
1235 > *
1236 > * The value may or may not be resolved as
1237 > * it is optional.
1238 > */
1239 > readonly size?: number;
1240 >
1241 > /**
1242 > * The last modification date represented as millis from unix epoch.
1243 > *
1244 > * The value may or may not be resolved as
1245 > * it is optional.
1246 > */
1247 > readonly mtime?: number;
1248 >
1249 > /**
1250 > * The creation date represented as millis from unix epoch.
1251 > *
1252 > * The value may or may not be resolved as
1253 > * it is optional.
1254 > */
1255 > readonly ctime?: number;
1256 >
1257 > /**
1258 > * A unique identifier that represents the
1259 > * current state of the file or directory.
1260 > *
1261 > * The value may or may not be resolved as
1262 > * it is optional.
1263 > */
1264 > readonly etag?: string;
1265 >
1266 > /**
1267 > * File is readonly. Components like editors should not
1268 > * offer to edit the contents.
1269 > */
1270 > readonly readonly?: boolean;
1271 >
1272 > /**
1273 > * File is locked. Components like editors should offer
1274 > * to edit the contents and ask the user upon saving to
1275 > * remove the lock.
1276 > */
1277 > readonly locked?: boolean;
1278 >
1279 > /**
1280 > * File is executable. Relevant for Unix-like systems where
1281 > * the executable bit determines if a file can be run.
1282 > */
1283 > readonly executable?: boolean;
1284 > }
1285 >
1286 > export interface IBaseFileStatWithMetadata extends Required<IBaseFileStat> { }
1287 >
1288 > /**
1289 > * A file resource with meta information and resolved children if any.
1290 > */
1291 > export interface IFileStat extends IBaseFileStat {
1292 >
1293 > /**
1294 > * The resource is a file.
1295 > */
1296 > readonly isFile: boolean;
1297 >
1298 > /**
1299 > * The resource is a directory.
1300 > */
1301 > readonly isDirectory: boolean;
1302 >
1303 > /**
1304 > * The resource is a symbolic link. Note: even when the
1305 > * file is a symbolic link, you can test for `FileType.File`
1306 > * and `FileType.Directory` to know the type of the target
1307 > * the link points to.
1308 > */
1309 > readonly isSymbolicLink: boolean;
1310 >
1311 > /**
1312 > * The children of the file stat or undefined if none.
1313 > */
1314 > children: IFileStat[] | undefined;
1315 > }
1316 >
1317 > export interface IFileStatWithMetadata extends IFileStat, IBaseFileStatWithMetadata {
1318 > readonly mtime: number;
1319 > readonly ctime: number;
1320 > readonly etag: string;
1321 > readonly size: number;
1322 > readonly readonly: boolean;
1323 > readonly locked: boolean;
1324 > readonly executable: boolean;
1325 > readonly children: IFileStatWithMetadata[] | undefined;
1326 > }
1327 >
1328 > export interface IFileStatResult {
1329 > readonly stat?: IFileStat;
1330 > readonly success: boolean;
1331 > }
1332 >
1333 > export interface IFileStatResultWithMetadata extends IFileStatResult {
1334 > readonly stat?: IFileStatWithMetadata;
1335 > }
1336 >
1337 > export interface IFileStatWithPartialMetadata extends Omit<IFileStatWithMetadata, 'children'> { }
1338 >
1339 > export interface IFileContent extends IBaseFileStatWithMetadata {
1340 >
1341 > /**
1342 > * The content of a file as buffer.
1343 > */
1344 > readonly value: VSBuffer;
1345 > }
1346 >
1347 > export interface IFileStreamContent extends IBaseFileStatWithMetadata {
1348 >
1349 > /**
1350 > * The content of a file as stream.
1351 > */
1352 > readonly value: VSBufferReadableStream;
1353 > }
1354 >
1355 > export interface IBaseReadFileOptions extends IFileReadStreamOptions {
1356 >
1357 > /**
1358 > * The optional etag parameter allows to return early from resolving the resource if
1359 > * the contents on disk match the etag. This prevents accumulated reading of resources
1360 > * that have been read already with the same etag.
1361 > * It is the task of the caller to makes sure to handle this error case from the promise.
1362 > */
1363 > readonly etag?: string;
1364 > }
1365 >
1366 > export interface IReadFileStreamOptions extends IBaseReadFileOptions { }
1367 >
1368 > export interface IReadFileOptions extends IBaseReadFileOptions {
1369 >
1370 > /**
1371 > * The optional `atomic` flag can be used to make sure
1372 > * the `readFile` method is not running in parallel with
1373 > * any `write` operations in the same process.
1374 > *
1375 > * Typically you should not need to use this flag but if
1376 > * for example you are quickly reading a file right after
1377 > * a file event occurred and the file changes a lot, there
1378 > * is a chance that a read returns an empty or partial file
1379 > * because a pending write has not finished yet.
1380 > *
1381 > * Note: this does not prevent the file from being written
1382 > * to from a different process. If you need such atomic
1383 > * operations, you better use a real database as storage.
1384 > */
1385 > readonly atomic?: boolean;
1386 > }
1387 >
1388 > export interface IWriteFileOptions {
1389 >
1390 > /**
1391 > * The last known modification time of the file. This can be used to prevent dirty writes.
1392 > */
1393 > readonly mtime?: number;
1394 >
1395 > /**
1396 > * The etag of the file. This can be used to prevent dirty writes.
1397 > */
1398 > readonly etag?: string;
1399 >
1400 > /**
1401 > * Whether to attempt to unlock a file before writing.
1402 > */
1403 > readonly unlock?: boolean;
1404 >
1405 > /**
1406 > * The optional `atomic` flag can be used to make sure
1407 > * the `writeFile` method updates the target file atomically
1408 > * by first writing to a temporary file in the same folder
1409 > * and then renaming it over the target.
1410 > */
1411 > readonly atomic?: IFileAtomicOptions | false;
1412 >
1413 > /**
1414 > * If set to true, will append to the end of the file instead of
1415 > * replacing its contents. Will create the file if it doesn't exist.
1416 > */
1417 > readonly append?: boolean;
1418 > }
1419 >
1420 > export interface IResolveFileOptions {
1421 >
1422 > /**
1423 > * Automatically continue resolving children of a directory until the provided resources
1424 > * are found.
1425 > */
1426 > readonly resolveTo?: readonly URI[];
1427 >
1428 > /**
1429 > * Automatically continue resolving children of a directory if the number of children is 1.
1430 > */
1431 > readonly resolveSingleChildDescendants?: boolean;
1432 >
1433 > /**
1434 > * Will resolve mtime, ctime, size and etag of files if enabled. This can have a negative impact
1435 > * on performance and thus should only be used when these values are required.
1436 > */
1437 > readonly resolveMetadata?: boolean;
1438 > }
1439 >
1440 > export interface IResolveMetadataFileOptions extends IResolveFileOptions {
1441 > readonly resolveMetadata: true;
1442 > }
1443 >
1444 > export interface ICreateFileOptions {
1445 >
1446 > /**
1447 > * Overwrite the file to create if it already exists on disk. Otherwise
1448 > * an error will be thrown (FILE_MODIFIED_SINCE).
1449 > */
1450 > readonly overwrite?: boolean;
1451 > }
1452 >
1453 > export class FileOperationError extends Error {
1454 > constructor(
1455 > message: string, files.ts
1456 > readonly fileOperationResult: FileOperationResult,
1457 > readonly options?: IReadFileOptions | IWriteFileOptions | ICreateFileOptions
1458 > ) {
1459 > super(message);
1460 > }
1461 > } files.ts
1462 >
1463 > export class TooLargeFileOperationError extends FileOperationError {
1464 > constructor(
1465 message: string,
1466 override readonly fileOperationResult: FileOperationResult.FILE_TOO_LARGE,
1470 super(message, fileOperationResult, options);
1471 }
1472 > } files.ts
1473 >
1474 > export class NotModifiedSinceFileOperationError extends FileOperationError {
1475 >
1476 > constructor(
1477 message: string,
1478 readonly stat: IFileStatWithMetadata,
1481 super(message, FileOperationResult.FILE_NOT_MODIFIED_SINCE, options);
1482 }
1483 > } files.ts
1484 >
1485 > export const enum FileOperationResult {
1486 > FILE_IS_DIRECTORY,
1487 > FILE_NOT_FOUND,
1488 > FILE_NOT_MODIFIED_SINCE,
1489 > FILE_MODIFIED_SINCE,
1490 > FILE_MOVE_CONFLICT,
1491 > FILE_WRITE_LOCKED,
1492 > FILE_PERMISSION_DENIED,
1493 > FILE_TOO_LARGE,
1494 > FILE_INVALID_PATH,
1495 > FILE_NOT_DIRECTORY,
1496 > FILE_OTHER_ERROR
1497 > }
1498 >
1499 > //#endregion
1500 >
1501 > //#region Settings
1502 >
1503 > export const AutoSaveConfiguration = {
1504 > OFF: 'off',
1505 > AFTER_DELAY: 'afterDelay',
1506 > ON_FOCUS_CHANGE: 'onFocusChange',
1507 > ON_WINDOW_CHANGE: 'onWindowChange'
1508 > };
1509 >
1510 > export const HotExitConfiguration = {
1511 > OFF: 'off',
1512 > ON_EXIT: 'onExit',
1513 > ON_EXIT_AND_WINDOW_CLOSE: 'onExitAndWindowClose'
1514 > };
1515 >
1516 > export const FILES_ASSOCIATIONS_CONFIG = 'files.associations';
1517 > export const FILES_EXCLUDE_CONFIG = 'files.exclude';
1518 > export const FILES_READONLY_INCLUDE_CONFIG = 'files.readonlyInclude';
1519 > export const FILES_READONLY_EXCLUDE_CONFIG = 'files.readonlyExclude';
1520 > export const FILES_READONLY_FROM_PERMISSIONS_CONFIG = 'files.readonlyFromPermissions';
1521 >
1522 > export interface IGlobPatterns {
1523 > [filepattern: string]: boolean;
1524 > }
1525 >
1526 > export interface IFilesConfiguration {
1527 > files?: IFilesConfigurationNode;
1528 > }
1529 >
1530 > export interface IFilesConfigurationNode {
1531 > associations: { [filepattern: string]: string };
1532 > exclude: IExpression;
1533 > watcherExclude: IGlobPatterns;
1534 > watcherInclude: string[];
1535 > encoding: string;
1536 > autoGuessEncoding: boolean;
1537 > candidateGuessEncodings: string[];
1538 > defaultLanguage: string;
1539 > trimTrailingWhitespace: boolean;
1540 > autoSave: string;
1541 > autoSaveDelay: number;
1542 > autoSaveWorkspaceFilesOnly: boolean;
1543 > autoSaveWhenNoErrors: boolean;
1544 > eol: string;
1545 > enableTrash: boolean;
1546 > hotExit: string;
1547 > saveConflictResolution: 'askUser' | 'overwriteFileOnDisk';
1548 > readonlyInclude: IGlobPatterns;
1549 > readonlyExclude: IGlobPatterns;
1550 > readonlyFromPermissions: boolean;
1551 > }
1552 >
1553 > //#endregion
1554 >
1555 > //#region Utilities
1556 >
1557 > export enum FileKind {
1558 > FILE,
1559 > FOLDER,
1560 > ROOT_FOLDER
1561 > }
1562 >
1563 > /**
1564 > * A hint to disable etag checking for reading/writing.
1565 > */
1566 > export const ETAG_DISABLED = '';
1567 >
1568 > export function etag(stat: { mtime: number; size: number }): string;
1569 > export function etag(stat: { mtime: number | undefined; size: number | undefined }): string | undefined;
1570 > export function etag(stat: { mtime: number | undefined; size: number | undefined }): string | undefined {
1571 > if (typeof stat.size !== 'number' || typeof stat.mtime !== 'number') { files.ts
1572 > return undefined; files.ts
1573 > }
1574 > files.ts
1575 > return stat.mtime.toString(29) + stat.size.toString(31);
1576 > }
1577 > files.ts
1578 export async function whenProviderRegistered(file: URI, fileService: IFileService): Promise<void> {
1579 if (fileService.hasProvider(URI.from({ scheme: file.scheme }))) {
1590 });
1591 }
1592 > files.ts
1593 > /**
1594 > * Helper to format a raw byte size into a human readable label.
1595 > */
1596 > export class ByteSize {
1597 >
1598 > static readonly KB = 1024;
1599 > static readonly MB = ByteSize.KB * ByteSize.KB;
1600 > static readonly GB = ByteSize.MB * ByteSize.KB;
1601 > static readonly TB = ByteSize.GB * ByteSize.KB;
1602 >
1603 > static formatSize(size: number): string {
1604 if (!isNumber(size)) {
1605 size = 0;
1624 return localize('sizeTB', "{0}TB", (size / ByteSize.TB).toFixed(2));
1625 }
1626 > } files.ts
1627 >
1628 > // File limits
1629 >
1630 > export function getLargeFileConfirmationLimit(remoteAuthority?: string): number;
1631 > export function getLargeFileConfirmationLimit(uri?: URI): number;
1632 > export function getLargeFileConfirmationLimit(arg?: string | URI): number {
1633 const isRemote = typeof arg === 'string' || arg?.scheme === Schemas.vscodeRemote;
1634 const isLocal = typeof arg !== 'string' && arg?.scheme === Schemas.file;
1655 return 1024 * ByteSize.MB;
1656 }
1657 > files.ts
1658 > //#endregion
src/vs/base/common/event.ts 1078 covered LOC · 183 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- event.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancelablePromise } from './async.js';
7 > import { CancellationToken } from './cancellation.js';
8 > import { diffSets } from './collections.js';
9 > import { onUnexpectedError } from './errors.js';
10 > import { createSingleCallFunction } from './functional.js';
11 > import { combinedDisposable, Disposable, DisposableMap, DisposableStore, IDisposable, toDisposable } from './lifecycle.js';
12 > import { LinkedList } from './linkedList.js';
13 > import { IObservable, IObservableWithChange, IObserver } from './observable.js';
14 > import { env } from './process.js';
15 > import { StopWatch } from './stopwatch.js';
16 > import { MicrotaskDelay } from './symbols.js';
17 >
18 >
19 > // -----------------------------------------------------------------------------------------------------------------------
20 > // Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell.
21 > // -----------------------------------------------------------------------------------------------------------------------
22 > const _enableDisposeWithListenerWarning = false
23 > // || Boolean("TRUE") // causes a linter warning so that it cannot be pushed
24 > ;
25 >
26 >
27 > // -----------------------------------------------------------------------------------------------------------------------
28 > // Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup.
29 > // See https://github.com/microsoft/vscode/issues/142851
30 > // -----------------------------------------------------------------------------------------------------------------------
31 > const _enableSnapshotPotentialLeakWarning = false
32 > // || Boolean("TRUE") // causes a linter warning so that it cannot be pushed
33 > ;
34 >
35 >
36 > const _bufferLeakWarnCountThreshold = 100;
37 > const _bufferLeakWarnTimeThreshold = 60_000; // 1 minute
38 >
39 function _isBufferLeakWarningEnabled(): boolean {
40 return !!env['VSCODE_DEV'];
41 }
42 > event.ts
43 > /**
44 > * An event with zero or one parameters that can be subscribed to. The event is a function itself.
45 > */
46 > export interface Event<T> {
47 > (listener: (e: T) => unknown, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;
48 > }
49 >
50 > export namespace Event {
51 > export const None: Event<any> = () => Disposable.None;
52 >
53 > function _addLeakageTraceLogic(options: EmitterOptions) {
54 > if (_enableSnapshotPotentialLeakWarning) { event.ts
55 const { onDidAddListener: origListenerDidAdd } = options;
56 const stack = Stacktrace.create();
64 };
65 }
66 > } event.ts
67 > event.ts
68 > /**
69 > * Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared
70 > * `setTimeout`. The event is converted into a signal (`Event<void>`) to avoid additional object creation as a
71 > * result of merging events and to try prevent race conditions that could arise when using related deferred and
72 > * non-deferred events.
73 > *
74 > * This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work
75 > * (eg. latency of keypress to text rendered).
76 > *
77 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
78 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
79 > * returned event causes this utility to leak a listener on the original event.
80 > *
81 > * @param event The event source for the new event.
82 > * @param flushOnListenerRemove Whether to fire all debounced events when a listener is removed. If this is not
83 > * specified, some events could go missing. Use this if it's important that all events are processed, even if the
84 > * listener gets disposed before the debounced event fires.
85 > * @param disposable A disposable store to add the new EventEmitter to.
86 > */
87 > export function defer(event: Event<unknown>, flushOnListenerRemove?: boolean, disposable?: DisposableStore): Event<void> {
88 return debounce<unknown, void>(event, () => void 0, 0, undefined, flushOnListenerRemove ?? true, undefined, disposable);
89 }
90 > event.ts
91 > /**
92 > * Given an event, returns another event which only fires once.
93 > *
94 > * @param event The event source for the new event.
95 > */
96 > export function once<T>(event: Event<T>): Event<T> {
97 > return (listener, thisArgs = null, disposables?) => { event.ts
98 > // we need this, in case the event fires during the listener call
99 > let didFire = false;
100 > let result: IDisposable | undefined = undefined;
101 > result = event(e => {
102 > if (didFire) { event.ts
103 return;
104 > } else if (result) { event.ts
105 > result.dispose(); event.ts
106 > } else { event.ts
107 didFire = true;
108 }
109 > event.ts
110 > return listener.call(thisArgs, e);
111 > }, null, disposables); event.ts
112 >
113 > if (didFire) {
114 result.dispose();
115 }
116 > event.ts
117 > return result;
118 > };
119 > }
120 > event.ts
121 > /**
122 > * Given an event, returns another event which only fires once, and only when the condition is met.
123 > *
124 > * @param event The event source for the new event.
125 > */
126 > export function onceIf<T>(event: Event<T>, condition: (e: T) => boolean): Event<T> {
127 return Event.once(Event.filter(event, condition));
128 }
129 > event.ts
130 > /**
131 > * Maps an event of one type into an event of another type using a mapping function, similar to how
132 > * `Array.prototype.map` works.
133 > *
134 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
135 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
136 > * returned event causes this utility to leak a listener on the original event.
137 > *
138 > * @param event The event source for the new event.
139 > * @param map The mapping function.
140 > * @param disposable A disposable store to add the new EventEmitter to.
141 > */
142 > export function map<I, O>(event: Event<I>, map: (i: I) => O, disposable?: DisposableStore): Event<O> {
143 return snapshot((listener, thisArgs = null, disposables?) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable);
144 }
145 > event.ts
146 > /**
147 > * Wraps an event in another event that performs some function on the event object before firing.
148 > *
149 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
150 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
151 > * returned event causes this utility to leak a listener on the original event.
152 > *
153 > * @param event The event source for the new event.
154 > * @param each The function to perform on the event object.
155 > * @param disposable A disposable store to add the new EventEmitter to.
156 > */
157 > export function forEach<I>(event: Event<I>, each: (i: I) => void, disposable?: DisposableStore): Event<I> {
158 return snapshot((listener, thisArgs = null, disposables?) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable);
159 }
160 > event.ts
161 > /**
162 > * Wraps an event in another event that fires only when some condition is met.
163 > *
164 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
165 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
166 > * returned event causes this utility to leak a listener on the original event.
167 > *
168 > * @param event The event source for the new event.
169 > * @param filter The filter function that defines the condition. The event will fire for the object if this function
170 > * returns true.
171 > * @param disposable A disposable store to add the new EventEmitter to.
172 > */
173 > export function filter<T, U>(event: Event<T | U>, filter: (e: T | U) => e is T, disposable?: DisposableStore): Event<T>;
174 > export function filter<T>(event: Event<T>, filter: (e: T) => boolean, disposable?: DisposableStore): Event<T>;
175 > export function filter<T, R>(event: Event<T | R>, filter: (e: T | R) => e is R, disposable?: DisposableStore): Event<R>;
176 > export function filter<T>(event: Event<T>, filter: (e: T) => boolean, disposable?: DisposableStore): Event<T> {
177 > return snapshot((listener, thisArgs = null, disposables?) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable); event.ts
178 > }
179 > event.ts
180 > /**
181 > * Given an event, returns the same event but typed as `Event<void>`.
182 > */
183 > export function signal<T>(event: Event<T>): Event<void> {
184 return event as Event<any> as Event<void>;
185 }
186 > event.ts
187 > /**
188 > * Given a collection of events, returns a single event which emits whenever any of the provided events emit.
189 > */
190 > export function any<T>(...events: Event<T>[]): Event<T>;
191 > export function any(...events: Event<any>[]): Event<void>;
192 > export function any<T>(...events: Event<T>[]): Event<T> {
193 > return (listener, thisArgs = null, disposables?) => { event.ts
194 > const disposable = combinedDisposable(...events.map(event => event(e => listener.call(thisArgs, e)))); event.ts
195 > return addAndReturnDisposable(disposable, disposables);
196 > };
197 > } event.ts
198 > event.ts
199 > /**
200 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
201 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
202 > * returned event causes this utility to leak a listener on the original event.
203 > */
204 > export function reduce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, initial?: O, disposable?: DisposableStore): Event<O> {
205 let output: O | undefined = initial;
206
210 }, disposable);
211 }
212 > event.ts
213 > function snapshot<T>(event: Event<T>, disposable: DisposableStore | undefined): Event<T> {
214 > let listener: IDisposable | undefined; event.ts
215 >
216 > const options: EmitterOptions | undefined = {
217 > onWillAddFirstListener() {
218 > listener = event(emitter.fire, emitter); event.ts
219 > },
220 > onDidRemoveLastListener() { event.ts
221 > listener?.dispose(); event.ts
222 > }
223 > }; event.ts
224 >
225 > if (!disposable) {
226 > _addLeakageTraceLogic(options); event.ts
227 > }
228 > event.ts
229 > const emitter = new Emitter<T>(options);
230 >
231 > disposable?.add(emitter);
232 >
233 > return emitter.event;
234 > }
235 > event.ts
236 > /**
237 > * Adds the IDisposable to the store if it's set, and returns it. Useful to
238 > * Event function implementation.
239 > */
240 > function addAndReturnDisposable<T extends IDisposable>(d: T, store: DisposableStore | IDisposable[] | undefined): T {
241 > if (store instanceof Array) { event.ts
242 store.push(d);
243 > } else if (store) { event.ts
244 store.add(d);
245 }
246 > return d; event.ts
247 > }
248 > event.ts
249 > /**
250 > * Given an event, creates a new emitter that event that will debounce events based on {@link delay} and give an
251 > * array event object of all events that fired.
252 > *
253 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
254 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
255 > * returned event causes this utility to leak a listener on the original event.
256 > *
257 > * @param event The original event to debounce.
258 > * @param merge A function that reduces all events into a single event.
259 > * @param delay The number of milliseconds to debounce.
260 > * @param leading Whether to fire a leading event without debouncing.
261 > * @param flushOnListenerRemove Whether to fire all debounced events when a listener is removed. If this is not
262 > * specified, some events could go missing. Use this if it's important that all events are processed, even if the
263 > * listener gets disposed before the debounced event fires.
264 > * @param leakWarningThreshold See {@link EmitterOptions.leakWarningThreshold}.
265 > * @param disposable A disposable store to register the debounce emitter to.
266 > */
267 > export function debounce<T>(event: Event<T>, merge: (last: T | undefined, event: T) => T, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event<T>;
268 > export function debounce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event<O>;
269 > export function debounce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, delay: number | typeof MicrotaskDelay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold?: number, disposable?: DisposableStore): Event<O> {
270 let subscription: IDisposable;
271 let output: O | undefined = undefined;
330 return emitter.event;
331 }
332 > event.ts
333 > /**
334 > * Debounces an event, firing after some delay (default=0) with an array of all event original objects.
335 > *
336 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
337 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
338 > * returned event causes this utility to leak a listener on the original event.
339 > *
340 > * @param event The event source for the new event.
341 > * @param delay The number of milliseconds to debounce.
342 > * @param flushOnListenerRemove Whether to fire all debounced events when a listener is removed. If this is not
343 > * specified, some events could go missing. Use this if it's important that all events are processed, even if the
344 > * listener gets disposed before the debounced event fires.
345 > * @param disposable A disposable store to add the new EventEmitter to.
346 > */
347 > export function accumulate<T>(event: Event<T>, delay: number | typeof MicrotaskDelay = 0, flushOnListenerRemove?: boolean, disposable?: DisposableStore): Event<T[]> {
348 return Event.debounce<T, T[]>(event, (last, e) => {
349 if (!last) {
354 }, delay, undefined, flushOnListenerRemove ?? true, undefined, disposable);
355 }
356 > event.ts
357 > /**
358 > * Throttles an event, ensuring the event is fired at most once during the specified delay period.
359 > * Unlike debounce, throttle will fire immediately on the leading edge and/or after the delay on the trailing edge.
360 > *
361 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
362 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
363 > * returned event causes this utility to leak a listener on the original event.
364 > *
365 > * @param event The event source for the new event.
366 > * @param merge An accumulator function that merges events if multiple occur during the throttle period.
367 > * @param delay The number of milliseconds to throttle.
368 > * @param leading Whether to fire on the leading edge (immediately on first event).
369 > * @param trailing Whether to fire on the trailing edge (after delay with the last value).
370 > * @param leakWarningThreshold See {@link EmitterOptions.leakWarningThreshold}.
371 > * @param disposable A disposable store to register the throttle emitter to.
372 > */
373 > export function throttle<T>(event: Event<T>, merge: (last: T | undefined, event: T) => T, delay?: number | typeof MicrotaskDelay, leading?: boolean, trailing?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event<T>;
374 > export function throttle<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, delay?: number | typeof MicrotaskDelay, leading?: boolean, trailing?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event<O>;
375 > export function throttle<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, delay: number | typeof MicrotaskDelay = 100, leading = true, trailing = true, leakWarningThreshold?: number, disposable?: DisposableStore): Event<O> {
376 let subscription: IDisposable;
377 let output: O | undefined = undefined;
437 return emitter.event;
438 }
439 > event.ts
440 > /**
441 > * Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate
442 > * event objects from different sources do not fire the same event object.
443 > *
444 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
445 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
446 > * returned event causes this utility to leak a listener on the original event.
447 > *
448 > * @param event The event source for the new event.
449 > * @param equals The equality condition.
450 > * @param disposable A disposable store to add the new EventEmitter to.
451 > *
452 > * @example
453 > * ```
454 > * // Fire only one time when a single window is opened or focused
455 > * Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow))
456 > * ```
457 > */
458 > export function latch<T>(event: Event<T>, equals: (a: T, b: T) => boolean = (a, b) => a === b, disposable?: DisposableStore): Event<T> {
459 let firstCall = true;
460 let cache: T;
467 }, disposable);
468 }
469 > event.ts
470 > /**
471 > * Splits an event whose parameter is a union type into 2 separate events for each type in the union.
472 > *
473 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
474 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
475 > * returned event causes this utility to leak a listener on the original event.
476 > *
477 > * @example
478 > * ```
479 > * const event = new EventEmitter<number | undefined>().event;
480 > * const [numberEvent, undefinedEvent] = Event.split(event, isUndefined);
481 > * ```
482 > *
483 > * @param event The event source for the new event.
484 > * @param isT A function that determines what event is of the first type.
485 > * @param disposable A disposable store to add the new EventEmitter to.
486 > */
487 > export function split<T, U>(event: Event<T | U>, isT: (e: T | U) => e is T, disposable?: DisposableStore): [Event<T>, Event<U>] {
488 return [
489 Event.filter(event, isT, disposable),
491 ];
492 }
493 > event.ts
494 > /**
495 > * Buffers an event until it has a listener attached.
496 > *
497 > * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
498 > * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
499 > * returned event causes this utility to leak a listener on the original event.
500 > *
501 > * @param event The event source for the new event.
502 > * @param debugName A name for this buffer, used in leak detection warnings.
503 > * @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a
504 > * `setTimeout` when the first event listener is added.
505 > * @param _buffer Internal: A source event array used for tests.
506 > *
507 > * @example
508 > * ```
509 > * // Start accumulating events, when the first listener is attached, flush
510 > * // the event after a timeout such that multiple listeners attached before
511 > * // the timeout would receive the event
512 > * this.onInstallExtension = Event.buffer(service.onInstallExtension, 'onInstallExtension', true);
513 > * ```
514 > */
515 > export function buffer<T>(event: Event<T>, debugName: string, flushAfterTimeout = false, _buffer: T[] = [], disposable?: DisposableStore): Event<T> {
516 let buffer: T[] | null = _buffer.slice();
517
600 return emitter.event;
601 }
602 > /** event.ts
603 > * Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style.
604 > *
605 > * @example
606 > * ```
607 > * // Normal
608 > * const onEnterPressNormal = Event.filter(
609 > * Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)),
610 > * e.keyCode === KeyCode.Enter
611 > * ).event;
612 > *
613 > * // Using chain
614 > * const onEnterPressChain = Event.chain(onKeyPress.event, $ => $
615 > * .map(e => new StandardKeyboardEvent(e))
616 > * .filter(e => e.keyCode === KeyCode.Enter)
617 > * );
618 > * ```
619 > */
620 > export function chain<T, R>(event: Event<T>, sythensize: ($: IChainableSythensis<T>) => IChainableSythensis<R>): Event<R> {
621 const fn: Event<R> = (listener, thisArgs, disposables) => {
622 const cs = sythensize(new ChainableSynthesis()) as ChainableSynthesis;
631 return fn;
632 }
633 > event.ts
634 > const HaltChainable = Symbol('HaltChainable');
635 >
636 > class ChainableSynthesis implements IChainableSythensis<any> {
637 private readonly steps: ((input: any) => unknown)[] = [];
638 > event.ts
639 > map<O>(fn: (i: any) => O): this {
640 this.steps.push(fn);
641 return this;
642 }
643 > event.ts
644 > forEach(fn: (i: any) => void): this {
645 this.steps.push(v => {
646 fn(v);
649 return this;
650 }
651 > event.ts
652 > filter(fn: (e: any) => boolean): this {
653 this.steps.push(v => fn(v) ? v : HaltChainable);
654 return this;
655 }
656 > event.ts
657 > reduce<R>(merge: (last: R | undefined, event: any) => R, initial?: R | undefined): this {
658 let last = initial;
659 this.steps.push(v => {
663 return this;
664 }
665 > event.ts
666 > latch(equals: (a: any, b: any) => boolean = (a, b) => a === b): ChainableSynthesis {
667 let firstCall = true;
668 let cache: any;
676 return this;
677 }
678 > event.ts
679 > public evaluate(value: any) {
680 for (const step of this.steps) {
681 value = step(value);
687 return value;
688 }
689 > } event.ts
690 >
691 > export interface IChainableSythensis<T> {
692 > map<O>(fn: (i: T) => O): IChainableSythensis<O>;
693 > forEach(fn: (i: T) => void): IChainableSythensis<T>;
694 > filter<R extends T>(fn: (e: T) => e is R): IChainableSythensis<R>;
695 > filter(fn: (e: T) => boolean): IChainableSythensis<T>;
696 > reduce<R>(merge: (last: R, event: T) => R, initial: R): IChainableSythensis<R>;
697 > reduce<R>(merge: (last: R | undefined, event: T) => R): IChainableSythensis<R>;
698 > latch(equals?: (a: T, b: T) => boolean): IChainableSythensis<T>;
699 > }
700 >
701 > export interface NodeEventEmitter {
702 > on(event: string | symbol, listener: Function): unknown;
703 > removeListener(event: string | symbol, listener: Function): unknown;
704 > }
705 >
706 > /**
707 > * Creates an {@link Event} from a node event emitter.
708 > */
709 > export function fromNodeEventEmitter<T>(emitter: NodeEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event<T> {
710 const fn = (...args: unknown[]) => result.fire(map(...args));
711 const onFirstListenerAdd = () => emitter.on(eventName, fn);
715 return result.event;
716 }
717 > event.ts
718 > export interface DOMEventEmitter {
719 > addEventListener(event: string | symbol, listener: Function): void;
720 > removeEventListener(event: string | symbol, listener: Function): void;
721 > }
722 >
723 > /**
724 > * Creates an {@link Event} from a DOM event emitter.
725 > */
726 > export function fromDOMEventEmitter<T>(emitter: DOMEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event<T> {
727 const fn = (...args: unknown[]) => result.fire(map(...args));
728 const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
732 return result.event;
733 }
734 > event.ts
735 > /**
736 > * Creates a promise out of an event, using the {@link Event.once} helper.
737 > */
738 > export function toPromise<T>(event: Event<T>, disposables?: IDisposable[] | DisposableStore): CancelablePromise<T> {
739 let cancelRef: () => void;
740 let listener: IDisposable;
756 return promise;
757 }
758 > event.ts
759 > /**
760 > * A convenience function for forwarding an event to another emitter which
761 > * improves readability.
762 > *
763 > * This is similar to {@link Relay} but allows instantiating and forwarding
764 > * on a single line and also allows for multiple source events.
765 > * @param from The event to forward.
766 > * @param to The emitter to forward the event to.
767 > * @example
768 > * Event.forward(event, emitter);
769 > * // equivalent to
770 > * event(e => emitter.fire(e));
771 > * // equivalent to
772 > * event(emitter.fire, emitter);
773 > */
774 > export function forward<T>(from: Event<T>, to: Emitter<T>): IDisposable {
775 return from(e => to.fire(e));
776 }
777 > event.ts
778 > /**
779 > * Adds a listener to an event and calls the listener immediately with undefined as the event object.
780 > *
781 > * @example
782 > * ```
783 > * // Initialize the UI and update it when dataChangeEvent fires
784 > * runAndSubscribe(dataChangeEvent, () => this._updateUI());
785 > * ```
786 > */
787 > export function runAndSubscribe<T>(event: Event<T>, handler: (e: T) => unknown, initial: T): IDisposable;
788 > export function runAndSubscribe<T>(event: Event<T>, handler: (e: T | undefined) => unknown): IDisposable;
789 > export function runAndSubscribe<T>(event: Event<T>, handler: (e: T | undefined) => unknown, initial?: T): IDisposable {
790 handler(initial);
791 return event(e => handler(e));
792 }
793 > event.ts
794 > class EmitterObserver<T> implements IObserver {
795 >
796 > readonly emitter: Emitter<T>;
797 >
798 > private _counter = 0;
799 > private _hasChanged = false;
800 >
801 > constructor(readonly _observable: IObservable<T>, store: DisposableStore | undefined) {
802 const options: EmitterOptions = {
803 onWillAddFirstListener: () => {
819 }
820 }
821 > event.ts
822 > beginUpdate<T>(_observable: IObservable<T>): void {
823 // assert(_observable === this.obs);
824 this._counter++;
825 }
826 > event.ts
827 > handlePossibleChange<T>(_observable: IObservable<T>): void {
828 // assert(_observable === this.obs);
829 }
830 > event.ts
831 > handleChange<T, TChange>(_observable: IObservableWithChange<T, TChange>, _change: TChange): void {
832 // assert(_observable === this.obs);
833 this._hasChanged = true;
834 }
835 > event.ts
836 > endUpdate<T>(_observable: IObservable<T>): void {
837 // assert(_observable === this.obs);
838 this._counter--;
845 }
846 }
847 > } event.ts
848 >
849 > /**
850 > * Creates an event emitter that is fired when the observable changes.
851 > * Each listeners subscribes to the emitter.
852 > */
853 > export function fromObservable<T>(obs: IObservable<T>, store?: DisposableStore): Event<T> {
854 const observer = new EmitterObserver(obs, store);
855 return observer.emitter.event;
856 }
857 > event.ts
858 > /**
859 > * Each listener is attached to the observable directly.
860 > */
861 > export function fromObservableLight(observable: IObservable<unknown>): Event<void> {
862 return (listener, thisArgs, disposables) => {
863 let count = 0;
897 };
898 }
899 > } event.ts
900 >
901 > export interface EmitterOptions {
902 > /**
903 > * Optional function that's called *before* the very first listener is added
904 > */
905 > onWillAddFirstListener?: Function;
906 > /**
907 > * Optional function that's called *after* the very first listener is added
908 > */
909 > onDidAddFirstListener?: Function;
910 > /**
911 > * Optional function that's called after a listener is added
912 > */
913 > onDidAddListener?: Function;
914 > /**
915 > * Optional function that's called *after* remove the very last listener
916 > */
917 > onDidRemoveLastListener?: Function;
918 > /**
919 > * Optional function that's called *before* a listener is removed
920 > */
921 > onWillRemoveListener?: Function;
922 > /**
923 > * Optional function that's called when a listener throws an error. Defaults to
924 > * {@link onUnexpectedError}
925 > */
926 > onListenerError?: (e: any) => void;
927 > /**
928 > * Number of listeners that are allowed before assuming a leak. Default to
929 > * a globally configured value
930 > *
931 > * @see setGlobalLeakWarningThreshold
932 > */
933 > leakWarningThreshold?: number;
934 > /**
935 > * Human-readable name for the emitter, included in leak warning error
936 > * messages to help identify which emitter is leaking in telemetry.
937 > */
938 > leakWarningName?: string;
939 > /**
940 > * Pass in a delivery queue, which is useful for ensuring
941 > * in order event delivery across multiple emitters.
942 > */
943 > deliveryQueue?: EventDeliveryQueue;
944 >
945 > /** ONLY enable this during development */
946 > _profName?: string;
947 > }
948 >
949 >
950 > export class EventProfiling {
951 >
952 > static readonly all = new Set<EventProfiling>();
953 >
954 > private static _idPool = 0;
955 >
956 > readonly name: string;
957 > public listenerCount: number = 0;
958 > public invocationCount = 0;
959 > public elapsedOverall = 0;
960 > public durations: number[] = [];
961 >
962 > private _stopWatch?: StopWatch;
963 >
964 > constructor(name: string) {
965 this.name = `${name}_${EventProfiling._idPool++}`;
966 EventProfiling.all.add(this);
967 }
968 > event.ts
969 > start(listenerCount: number): void {
970 this._stopWatch = new StopWatch();
971 this.listenerCount = listenerCount;
972 }
973 > event.ts
974 > stop(): void {
975 if (this._stopWatch) {
976 const elapsed = this._stopWatch.elapsed();
981 }
982 }
983 > } event.ts
984 >
985 > let _globalLeakWarningThreshold = -1;
986 > export function setGlobalLeakWarningThreshold(n: number): IDisposable {
987 const oldValue = _globalLeakWarningThreshold;
988 _globalLeakWarningThreshold = n;
993 };
994 }
995 > event.ts
996 > class LeakageMonitor {
997 >
998 > private static _idPool = 1;
999 >
1000 > private _stacks: Map<string, number> | undefined;
1001 > private _warnCountdown: number = 0;
1002 >
1003 > constructor(
1004 private readonly _errorHandler: (err: Error) => void,
1005 readonly threshold: number,
1006 readonly name: string = (LeakageMonitor._idPool++).toString(16).padStart(3, '0')
1007 ) { }
1008 > event.ts
1009 > dispose(): void {
1010 this._stacks?.clear();
1011 }
1012 > event.ts
1013 > check(stack: Stacktrace, listenerCount: number): undefined | (() => void) {
1014
1015 const threshold = this.threshold;
1046 };
1047 }
1048 > event.ts
1049 > getMostFrequentStack(): [string, number] | undefined {
1050 if (!this._stacks) {
1051 return undefined;
1061 return topStack;
1062 }
1063 > } event.ts
1064 >
1065 > class Stacktrace {
1066 >
1067 > static create() {
1068 > const err = new Error();
1069 > return new Stacktrace(err.stack ?? '');
1070 > }
1071 >
1072 > private constructor(readonly value: string) { }
1073 >
1074 > print() {
1075 console.warn(this.value.split('\n').slice(2).join('\n'));
1076 }
1077 > } event.ts
1078 >
1079 > // error that is logged when going over the configured listener threshold
1080 > export class ListenerLeakError extends Error {
1081 > readonly kind: string;
1082 > readonly listenerCount: number;
1083 > /**
1084 > * The detailed message including listener count and most frequent stack.
1085 > * Available locally for debugging but intentionally not used as the error
1086 > * `message`. When `emitterName` is provided, errors group by emitter name
1087 > * and kind in telemetry; otherwise they group by kind alone.
1088 > */
1089 > readonly details: string;
1090 > constructor(kind: 'dominated' | 'popular', details: string, stack: string, listenerCount: number, emitterName?: string) {
1091 super(emitterName
1092 ? `[${emitterName}] potential listener LEAK detected, ${kind}`
1098 this.stack = stack;
1099 }
1100 > event.ts
1101 > static is(err: unknown): err is ListenerLeakError {
1102 return err instanceof ListenerLeakError
1103 || (err instanceof Error && typeof (err as Error & { kind: unknown; listenerCount: unknown }).kind === 'string' && typeof (err as Error & { kind: unknown; listenerCount: unknown }).listenerCount === 'number');
1104 }
1105 > } event.ts
1106 >
1107 > // SEVERE error that is logged when having gone way over the configured listener
1108 > // threshold so that the emitter refuses to accept more listeners
1109 > export class ListenerRefusalError extends ListenerLeakError {
1110 > constructor(kind: 'dominated' | 'popular', details: string, stack: string, listenerCount: number, emitterName?: string) {
1111 super(kind, details, stack, listenerCount, emitterName);
1112 this.name = 'ListenerRefusalError';
1113 }
1114 > } event.ts
1115 >
1116 > let id = 0;
1117 > class UniqueContainer<T> {
1118 > stack?: Stacktrace;
1119 > public id = id++;
1120 > constructor(public readonly value: T) { }
1121 > }
1122 > const compactionThreshold = 2;
1123 >
1124 > type ListenerContainer<T> = UniqueContainer<(data: T) => void>;
1125 > type ListenerOrListeners<T> = (ListenerContainer<T> | undefined)[] | ListenerContainer<T>;
1126 >
1127 > const forEachListener = <T>(listeners: ListenerOrListeners<T>, fn: (c: ListenerContainer<T>) => void) => {
1128 if (listeners instanceof UniqueContainer) {
1129 fn(listeners);
1137 }
1138 };
1139 > event.ts
1140 > /**
1141 > * The Emitter can be used to expose an Event to the public
1142 > * to fire it from the insides.
1143 > * Sample:
1144 > class Document {
1145 >
1146 > private readonly _onDidChange = new Emitter<(value:string)=>any>();
1147 >
1148 > public onDidChange = this._onDidChange.event;
1149 >
1150 > // getter-style
1151 > // get onDidChange(): Event<(value:string)=>any> {
1152 > // return this._onDidChange.event;
1153 > // }
1154 >
1155 > private _doIt() {
1156 > //...
1157 > this._onDidChange.fire(value);
1158 > }
1159 > }
1160 > */
1161 > export class Emitter<T> {
1162 >
1163 > private readonly _options?: EmitterOptions;
1164 > private readonly _leakageMon?: LeakageMonitor;
1165 > private readonly _perfMon?: EventProfiling;
1166 > private _disposed?: true;
1167 > private _event?: Event<T>;
1168 >
1169 > /**
1170 > * A listener, or list of listeners. A single listener is the most common
1171 > * for event emitters (#185789), so we optimize that special case to avoid
1172 > * wrapping it in an array (just like Node.js itself.)
1173 > *
1174 > * A list of listeners never 'downgrades' back to a plain function if
1175 > * listeners are removed, for two reasons:
1176 > *
1177 > * 1. That's complicated (especially with the deliveryQueue)
1178 > * 2. A listener with >1 listener is likely to have >1 listener again at
1179 > * some point, and swapping between arrays and functions may[citation needed]
1180 > * introduce unnecessary work and garbage.
1181 > *
1182 > * The array listeners can be 'sparse', to avoid reallocating the array
1183 > * whenever any listener is added or removed. If more than `1 / compactionThreshold`
1184 > * of the array is empty, only then is it resized.
1185 > */
1186 > protected _listeners?: ListenerOrListeners<T>;
1187 >
1188 > /**
1189 > * Always to be defined if _listeners is an array. It's no longer a true
1190 > * queue, but holds the dispatching 'state'. If `fire()` is called on an
1191 > * emitter, any work left in the _deliveryQueue is finished first.
1192 > */
1193 > private _deliveryQueue?: EventDeliveryQueuePrivate;
1194 > protected _size = 0;
1195 >
1196 > constructor(options?: EmitterOptions) {
1197 > this._options = options; event.ts
1198 > this._leakageMon = (_globalLeakWarningThreshold > 0 || this._options?.leakWarningThreshold)
1199 ? new LeakageMonitor(options?.onListenerError ?? onUnexpectedError, this._options?.leakWarningThreshold ?? _globalLeakWarningThreshold, this._options?.leakWarningName) :
1200 > undefined; event.ts
1201 > this._perfMon = this._options?._profName ? new EventProfiling(this._options._profName) : undefined;
1202 > this._deliveryQueue = this._options?.deliveryQueue as EventDeliveryQueuePrivate | undefined;
1203 > }
1204 > event.ts
1205 > dispose() {
1206 > if (!this._disposed) { event.ts
1207 > this._disposed = true;
1208 >
1209 > // It is bad to have listeners at the time of disposing an emitter, it is worst to have listeners keep the emitter
1210 > // alive via the reference that's embedded in their disposables. Therefore we loop over all remaining listeners and
1211 > // unset their subscriptions/disposables. Looping and blaming remaining listeners is done on next tick because the
1212 > // the following programming pattern is very popular:
1213 > //
1214 > // const someModel = this._disposables.add(new ModelObject()); // (1) create and register model
1215 > // this._disposables.add(someModel.onDidChange(() => { ... }); // (2) subscribe and register model-event listener
1216 > // ...later...
1217 > // this._disposables.dispose(); disposes (1) then (2): don't warn after (1) but after the "overall dispose" is done
1218 >
1219 > if (this._deliveryQueue?.current === this) {
1220 this._deliveryQueue.reset();
1221 }
1222 > if (this._listeners) { event.ts
1223 > if (_enableDisposeWithListenerWarning) { event.ts
1224 const listeners = this._listeners;
1225 queueMicrotask(() => {
1227 });
1228 }
1229 > event.ts
1230 > this._listeners = undefined;
1231 > this._size = 0;
1232 > }
1233 > this._options?.onDidRemoveLastListener?.(); event.ts
1234 > this._leakageMon?.dispose();
1235 > }
1236 > }
1237 > event.ts
1238 > /**
1239 > * For the public to allow to subscribe
1240 > * to events from this Emitter
1241 > */
1242 > get event(): Event<T> {
1243 > this._event ??= (callback: (e: T) => unknown, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => { event.ts
1244 > if (this._leakageMon && this._size > this._leakageMon.threshold ** 2) { event.ts
1245 const message = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;
1246 console.warn(message);
1254 return Disposable.None;
1255 }
1256 > event.ts
1257 > if (this._disposed) {
1258 // todo: should we warn if a listener is added to a disposed emitter? This happens often
1259 return Disposable.None;
1260 }
1261 > event.ts
1262 > if (thisArgs) {
1263 callback = callback.bind(thisArgs);
1264 }
1265 > event.ts
1266 > const contained = new UniqueContainer(callback);
1267 >
1268 > let removeMonitor: Function | undefined;
1269 > let stack: Stacktrace | undefined;
1270 > if (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) {
1271 // check and record this emitter for potential leakage
1272 contained.stack = Stacktrace.create();
1273 removeMonitor = this._leakageMon.check(contained.stack, this._size + 1);
1274 }
1275 > event.ts
1276 > if (_enableDisposeWithListenerWarning) {
1277 contained.stack = stack ?? Stacktrace.create();
1278 }
1279 > event.ts
1280 > if (!this._listeners) {
1281 > this._options?.onWillAddFirstListener?.(this);
1282 > this._listeners = contained;
1283 > this._options?.onDidAddFirstListener?.(this);
1284 > } else if (this._listeners instanceof UniqueContainer) {
1285 > this._deliveryQueue ??= new EventDeliveryQueuePrivate(); event.ts
1286 > this._listeners = [this._listeners, contained];
1287 > } else {
1288 > this._listeners.push(contained); event.ts
1289 > }
1290 > this._options?.onDidAddListener?.(this); event.ts
1291 >
1292 > this._size++;
1293 >
1294 >
1295 > const result = toDisposable(() => {
1296 > removeMonitor?.(); event.ts
1297 > this._removeListener(contained);
1298 > }); event.ts
1299 > addToDisposables(result, disposables);
1300 >
1301 > return result;
1302 > };
1303 > event.ts
1304 > return this._event;
1305 > }
1306 > event.ts
1307 > private _removeListener(listener: ListenerContainer<T>) {
1308 > this._options?.onWillRemoveListener?.(this); event.ts
1309 >
1310 > if (!this._listeners) {
1311 > return; // expected if a listener gets disposed event.ts
1312 > }
1313 > event.ts
1314 > if (this._size === 1) {
1315 > this._listeners = undefined; event.ts
1316 > this._options?.onDidRemoveLastListener?.(this);
1317 > this._size = 0;
1318 > return;
1319 > }
1320 > event.ts
1321 > // size > 1 which requires that listeners be a list:
1322 > const listeners = this._listeners as (ListenerContainer<T> | undefined)[];
1323 >
1324 > const index = listeners.indexOf(listener);
1325 > if (index === -1) {
1326 console.log('disposed?', this._disposed);
1327 console.log('size?', this._size);
1329 throw new Error('Attempted to dispose unknown listener');
1330 }
1331 > event.ts
1332 > this._size--;
1333 > listeners[index] = undefined;
1334 >
1335 > const adjustDeliveryQueue = this._deliveryQueue!.current === this;
1336 > if (this._size * compactionThreshold <= listeners.length) {
1337 > let n = 0; event.ts
1338 > for (let i = 0; i < listeners.length; i++) {
1339 > if (listeners[i]) {
1340 > listeners[n++] = listeners[i];
1341 > } else if (adjustDeliveryQueue && n < this._deliveryQueue!.end) {
1342 this._deliveryQueue!.end--;
1343 if (n < this._deliveryQueue!.i) {
1345 }
1346 }
1347 > } event.ts
1348 > listeners.length = n;
1349 > }
1350 > } event.ts
1351 > event.ts
1352 > private _deliver(listener: undefined | UniqueContainer<(value: T) => void>, value: T) {
1353 > if (!listener) { event.ts
1354 > return; event.ts
1355 > }
1356 > event.ts
1357 > const errorHandler = this._options?.onListenerError || onUnexpectedError;
1358 > if (!errorHandler) {
1359 listener.value(value);
1360 return;
1361 }
1362 > event.ts
1363 > try {
1364 > listener.value(value);
1365 > } catch (e) {
1366 errorHandler(e);
1367 }
1368 > } event.ts
1369 > event.ts
1370 > /** Delivers items in the queue. Assumes the queue is ready to go. */
1371 > private _deliverQueue(dq: EventDeliveryQueuePrivate) {
1372 > const listeners = dq.current!._listeners! as (ListenerContainer<T> | undefined)[]; event.ts
1373 > while (dq.i < dq.end) {
1374 > // important: dq.i is incremented before calling deliver() because it might reenter deliverQueue()
1375 > this._deliver(listeners[dq.i++], dq.value as T);
1376 > }
1377 > dq.reset();
1378 > }
1379 > event.ts
1380 > /**
1381 > * To be kept private to fire an event to
1382 > * subscribers
1383 > */
1384 > fire(event: T): void {
1385 > if (this._deliveryQueue?.current) { event.ts
1386 this._deliverQueue(this._deliveryQueue);
1387 this._perfMon?.stop(); // last fire() will have starting perfmon, stop it before starting the next dispatch
1388 }
1389 > event.ts
1390 > this._perfMon?.start(this._size);
1391 >
1392 > if (!this._listeners) {
1393 > // no-op event.ts
1394 > } else if (this._listeners instanceof UniqueContainer) { event.ts
1395 > this._deliver(this._listeners, event); event.ts
1396 > } else { event.ts
1397 > const dq = this._deliveryQueue!; event.ts
1398 > dq.enqueue(this, event, this._listeners.length);
1399 > this._deliverQueue(dq);
1400 > }
1401 > event.ts
1402 > this._perfMon?.stop();
1403 > }
1404 > event.ts
1405 > hasListeners(): boolean {
1406 return this._size > 0;
1407 }
1408 > } event.ts
1409 >
1410 > export interface EventDeliveryQueue {
1411 > _isEventDeliveryQueue: true;
1412 > }
1413 >
1414 > export const createEventDeliveryQueue = (): EventDeliveryQueue => new EventDeliveryQueuePrivate();
1415 >
1416 > class EventDeliveryQueuePrivate implements EventDeliveryQueue { event.ts
1417 > declare _isEventDeliveryQueue: true;
1418 >
1419 > /**
1420 > * Index in current's listener list.
1421 > */
1422 > public i = -1;
1423 >
1424 > /**
1425 > * The last index in the listener's list to deliver.
1426 > */
1427 > public end = 0;
1428 > event.ts
1429 > /**
1430 > * Emitter currently being dispatched on. Emitter._listeners is always an array.
1431 > */
1432 > public current?: Emitter<any>;
1433 > /**
1434 > * Currently emitting value. Defined whenever `current` is.
1435 > */
1436 > public value?: unknown;
1437 >
1438 > public enqueue<T>(emitter: Emitter<T>, value: T, end: number) {
1439 > this.i = 0; event.ts
1440 > this.end = end;
1441 > this.current = emitter;
1442 > this.value = value;
1443 > }
1444 > event.ts
1445 > public reset() {
1446 > this.i = this.end; // force any current emission loop to stop, mainly for during dispose event.ts
1447 > this.current = undefined;
1448 > this.value = undefined;
1449 > }
1450 > } event.ts
1451 >
1452 > export interface IWaitUntil {
1453 > token: CancellationToken;
1454 > waitUntil(thenable: Promise<unknown>): void;
1455 > }
1456 >
1457 > export type IWaitUntilData<T> = Omit<Omit<T, 'waitUntil'>, 'token'>;
1458 >
1459 > export class AsyncEmitter<T extends IWaitUntil> extends Emitter<T> {
1460 >
1461 > private _asyncDeliveryQueue?: LinkedList<[(ev: T) => void, IWaitUntilData<T>]>;
1462 >
1463 > async fireAsync(data: IWaitUntilData<T>, token: CancellationToken, promiseJoin?: (p: Promise<unknown>, listener: Function) => Promise<unknown>): Promise<void> {
1464 if (!this._listeners) {
1465 return;
1512 }
1513 }
1514 > } event.ts
1515 >
1516 >
1517 > export class PauseableEmitter<T> extends Emitter<T> {
1518 >
1519 > private _isPaused = 0;
1520 > protected _eventQueue = new LinkedList<T>();
1521 > private _mergeFn?: (input: T[]) => T;
1522 >
1523 > public get isPaused(): boolean {
1524 > return this._isPaused !== 0;
1525 > }
1526 >
1527 > constructor(options?: EmitterOptions & { merge?: (input: T[]) => T }) {
1528 > super(options); event.ts
1529 > this._mergeFn = options?.merge;
1530 > }
1531 > event.ts
1532 > pause(): void {
1533 > this._isPaused++; event.ts
1534 > }
1535 > event.ts
1536 > resume(): void {
1537 > if (this._isPaused !== 0 && --this._isPaused === 0) { event.ts
1538 > if (this._mergeFn) { event.ts
1539 // use the merge function to create a single composite
1540 // event. make a copy in case firing pauses this emitter
1545 }
1546
1547 > } else { event.ts
1548 > // no merging, fire each event individually and test event.ts
1549 > // that this emitter isn't paused halfway through
1550 > while (!this._isPaused && this._eventQueue.size !== 0) {
1551 > super.fire(this._eventQueue.shift()!); event.ts
1552 > }
1553 > } event.ts
1554 > } event.ts
1555 > } event.ts
1556 > event.ts
1557 > override fire(event: T): void {
1558 > if (this._size) { event.ts
1559 > if (this._isPaused !== 0) { event.ts
1560 > this._eventQueue.push(event); event.ts
1561 > } else { event.ts
1562 > super.fire(event); event.ts
1563 > }
1564 > } event.ts
1565 > } event.ts
1566 > } event.ts
1567 >
1568 > export class DebounceEmitter<T> extends PauseableEmitter<T> {
1569 >
1570 > private readonly _delay: number;
1571 > private _handle: Timeout | undefined;
1572 >
1573 > constructor(options: EmitterOptions & { merge: (input: T[]) => T; delay?: number }) {
1574 super(options);
1575 this._delay = options.delay ?? 100;
1576 }
1577 > event.ts
1578 > override fire(event: T): void {
1579 if (!this._handle) {
1580 this.pause();
1586 super.fire(event);
1587 }
1588 > } event.ts
1589 >
1590 > /**
1591 > * An emitter which queue all events and then process them at the
1592 > * end of the event loop.
1593 > */
1594 > export class MicrotaskEmitter<T> extends Emitter<T> {
1595 > private _queuedEvents: T[] = [];
1596 > private _mergeFn?: (input: T[]) => T;
1597 >
1598 > constructor(options?: EmitterOptions & { merge?: (input: T[]) => T }) {
1599 super(options);
1600 this._mergeFn = options?.merge;
1601 }
1602 > override fire(event: T): void { event.ts
1603
1604 if (!this.hasListeners()) {
1618 }
1619 }
1620 > } event.ts
1621 >
1622 > /**
1623 > * An event emitter that multiplexes many events into a single event.
1624 > *
1625 > * @example Listen to the `onData` event of all `Thing`s, dynamically adding and removing `Thing`s
1626 > * to the multiplexer as needed.
1627 > *
1628 > * ```typescript
1629 > * const anythingDataMultiplexer = new EventMultiplexer<{ data: string }>();
1630 > *
1631 > * const thingListeners = DisposableMap<Thing, IDisposable>();
1632 > *
1633 > * thingService.onDidAddThing(thing => {
1634 > * thingListeners.set(thing, anythingDataMultiplexer.add(thing.onData);
1635 > * });
1636 > * thingService.onDidRemoveThing(thing => {
1637 > * thingListeners.deleteAndDispose(thing);
1638 > * });
1639 > *
1640 > * anythingDataMultiplexer.event(e => {
1641 > * console.log('Something fired data ' + e.data)
1642 > * });
1643 > * ```
1644 > */
1645 > export class EventMultiplexer<T> implements IDisposable {
1646 >
1647 > private readonly emitter: Emitter<T>;
1648 > private hasListeners = false;
1649 > private events: { event: Event<T>; listener: IDisposable | null }[] = [];
1650 >
1651 > constructor() {
1652 this.emitter = new Emitter<T>({
1653 onWillAddFirstListener: () => this.onFirstListenerAdd(),
1655 });
1656 }
1657 > event.ts
1658 > get event(): Event<T> {
1659 return this.emitter.event;
1660 }
1661 > event.ts
1662 > add(event: Event<T>): IDisposable {
1663 const e = { event: event, listener: null };
1664 this.events.push(e);
1679 return toDisposable(createSingleCallFunction(dispose));
1680 }
1681 > event.ts
1682 > private onFirstListenerAdd(): void {
1683 this.hasListeners = true;
1684 this.events.forEach(e => this.hook(e));
1685 }
1686 > event.ts
1687 > private onLastListenerRemove(): void {
1688 this.hasListeners = false;
1689 this.events.forEach(e => this.unhook(e));
1690 }
1691 > event.ts
1692 > private hook(e: { event: Event<T>; listener: IDisposable | null }): void {
1693 e.listener = e.event(r => this.emitter.fire(r));
1694 }
1695 > event.ts
1696 > private unhook(e: { event: Event<T>; listener: IDisposable | null }): void {
1697 e.listener?.dispose();
1698 e.listener = null;
1699 }
1700 > event.ts
1701 > dispose(): void {
1702 this.emitter.dispose();
1703
1707 this.events = [];
1708 }
1709 > } event.ts
1710 >
1711 > export interface IDynamicListEventMultiplexer<TEventType> extends IDisposable {
1712 > readonly event: Event<TEventType>;
1713 > }
1714 > export class DynamicListEventMultiplexer<TItem, TEventType> implements IDynamicListEventMultiplexer<TEventType> {
1715 > private readonly _store = new DisposableStore();
1716 >
1717 > readonly event: Event<TEventType>;
1718 >
1719 > constructor(
1720 items: TItem[],
1721 onAddItem: Event<TItem>,
1747 this.event = multiplexer.event;
1748 }
1749 > event.ts
1750 > dispose() {
1751 this._store.dispose();
1752 }
1753 > } event.ts
1754 >
1755 > /**
1756 > * The EventBufferer is useful in situations in which you want
1757 > * to delay firing your events during some code.
1758 > * You can wrap that code and be sure that the event will not
1759 > * be fired during that wrap.
1760 > *
1761 > * ```
1762 > * const emitter: Emitter;
1763 > * const delayer = new EventDelayer();
1764 > * const delayedEvent = delayer.wrapEvent(emitter.event);
1765 > *
1766 > * delayedEvent(console.log);
1767 > *
1768 > * delayer.bufferEvents(() => {
1769 > * emitter.fire(); // event will not be fired yet
1770 > * });
1771 > *
1772 > * // event will only be fired at this point
1773 > * ```
1774 > */
1775 > export class EventBufferer {
1776
1777 private data: { buffers: Function[] }[] = [];
1778 > event.ts
1779 > wrapEvent<T>(event: Event<T>): Event<T>;
1780 > wrapEvent<T>(event: Event<T>, reduce: (last: T | undefined, event: T) => T): Event<T>;
1781 > wrapEvent<T, O>(event: Event<T>, reduce: (last: O | undefined, event: T) => O, initial: O): Event<O>;
1782 > wrapEvent<T, O>(event: Event<T>, reduce?: (last: T | O | undefined, event: T) => T | O, initial?: O): Event<O | T> {
1783 return (listener, thisArgs?, disposables?) => {
1784 return event(i => {
1832 };
1833 }
1834 > event.ts
1835 > bufferEvents<R = void>(fn: () => R): R {
1836 const data = { buffers: new Array<Function>() };
1837 this.data.push(data);
1841 return r;
1842 }
1843 > } event.ts
1844 >
1845 > /**
1846 > * A Relay is an event forwarder which functions as a replugabble event pipe.
1847 > * Once created, you can connect an input event to it and it will simply forward
1848 > * events from that input event through its own `event` property. The `input`
1849 > * can be changed at any point in time.
1850 > */
1851 > export class Relay<T> implements IDisposable {
1852
1853 private listening = false;
1867
1868 readonly event: Event<T> = this.emitter.event;
1869 > event.ts
1870 > set input(event: Event<T>) {
1871 this.inputEvent = event;
1872
1876 }
1877 }
1878 > event.ts
1879 > dispose() {
1880 this.inputEventListener.dispose();
1881 this.emitter.dispose();
1882 }
1883 > } event.ts
1884 >
1885 > export interface IValueWithChangeEvent<T> {
1886 > readonly onDidChange: Event<void>;
1887 > get value(): T;
1888 > }
1889 >
1890 > export class ValueWithChangeEvent<T> implements IValueWithChangeEvent<T> {
1891 > public static const<T>(value: T): IValueWithChangeEvent<T> {
1892 > return new ConstValueWithChangeEvent(value);
1893 > }
1894 >
1895 > private readonly _onDidChange = new Emitter<void>();
1896 > readonly onDidChange: Event<void> = this._onDidChange.event;
1897 >
1898 > constructor(private _value: T) { }
1899 >
1900 > get value(): T {
1901 return this._value;
1902 }
1903 > event.ts
1904 > set value(value: T) {
1905 if (value !== this._value) {
1906 this._value = value;
1908 }
1909 }
1910 > } event.ts
1911 >
1912 > class ConstValueWithChangeEvent<T> implements IValueWithChangeEvent<T> {
1913 > public readonly onDidChange: Event<void> = Event.None;
1914 >
1915 > constructor(readonly value: T) { }
1916 > }
1917 >
1918 > /**
1919 > * @param handleItem Is called for each item in the set (but only the first time the item is seen in the set).
1920 > * The returned disposable is disposed if the item is no longer in the set.
1921 > */
1922 > export function trackSetChanges<T>(getData: () => ReadonlySet<T>, onDidChangeData: Event<unknown>, handleItem: (d: T) => IDisposable): IDisposable {
1923 const map = new DisposableMap<T, IDisposable>();
1924 let oldData = new Set(getData());
1942 return store;
1943 }
1944 > event.ts
1945 >
1946 > function addToDisposables(result: IDisposable, disposables: DisposableStore | IDisposable[] | undefined) { event.ts
1947 > if (disposables instanceof DisposableStore) {
1948 disposables.add(result);
1949 > } else if (Array.isArray(disposables)) { event.ts
1950 disposables.push(result);
1951 }
1952 > } event.ts
1953 > event.ts
1954 function disposeAndRemove(result: IDisposable, disposables: DisposableStore | IDisposable[] | undefined) {
1955 if (disposables instanceof DisposableStore) {
src/vs/platform/contextkey/common/contextkey.ts 832 covered LOC · 218 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- contextkey.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CharCode } from '../../../base/common/charCode.js';
7 > import { Event } from '../../../base/common/event.js';
8 > import { isChrome, isEdge, isFirefox, isLinux, isMacintosh, isSafari, isWeb, isWindows } from '../../../base/common/platform.js';
9 > import { isFalsyOrWhitespace } from '../../../base/common/strings.js';
10 > import { Scanner, LexingError, Token, TokenType } from './scanner.js';
11 > import { createDecorator } from '../../instantiation/common/instantiation.js';
12 > import { localize } from '../../../nls.js';
13 > import { IDisposable } from '../../../base/common/lifecycle.js';
14 > import { illegalArgument } from '../../../base/common/errors.js';
15 >
16 > const CONSTANT_VALUES = new Map<string, boolean>();
17 > CONSTANT_VALUES.set('false', false);
18 > CONSTANT_VALUES.set('true', true);
19 > CONSTANT_VALUES.set('isMac', isMacintosh);
20 > CONSTANT_VALUES.set('isLinux', isLinux);
21 > CONSTANT_VALUES.set('isWindows', isWindows);
22 > CONSTANT_VALUES.set('isWeb', isWeb);
23 > CONSTANT_VALUES.set('isMacNative', isMacintosh && !isWeb);
24 > CONSTANT_VALUES.set('isEdge', isEdge);
25 > CONSTANT_VALUES.set('isFirefox', isFirefox);
26 > CONSTANT_VALUES.set('isChrome', isChrome);
27 > CONSTANT_VALUES.set('isSafari', isSafari);
28 >
29 > /** allow register constant context keys that are known only after startup; requires running `substituteConstants` on the context key - https://github.com/microsoft/vscode/issues/174218#issuecomment-1437972127 */
30 > export function setConstant(key: string, value: boolean) {
31 if (CONSTANT_VALUES.get(key) !== undefined) { throw illegalArgument('contextkey.setConstant(k, v) invoked with already set constant `k`'); }
32
33 CONSTANT_VALUES.set(key, value);
34 }
36 > const hasOwnProperty = Object.prototype.hasOwnProperty;
37 >
38 > export const enum ContextKeyExprType {
39 > False = 0,
40 > True = 1,
41 > Defined = 2,
42 > Not = 3,
43 > Equals = 4,
44 > NotEquals = 5,
45 > And = 6,
46 > Regex = 7,
47 > NotRegex = 8,
48 > Or = 9,
49 > In = 10,
50 > NotIn = 11,
51 > Greater = 12,
52 > GreaterEquals = 13,
53 > Smaller = 14,
54 > SmallerEquals = 15,
55 > }
56 >
57 > export interface IContextKeyExprMapper {
58 > mapDefined(key: string): ContextKeyExpression;
59 > mapNot(key: string): ContextKeyExpression;
60 > mapEquals(key: string, value: any): ContextKeyExpression;
61 > mapNotEquals(key: string, value: any): ContextKeyExpression;
62 > mapGreater(key: string, value: any): ContextKeyExpression;
63 > mapGreaterEquals(key: string, value: any): ContextKeyExpression;
64 > mapSmaller(key: string, value: any): ContextKeyExpression;
65 > mapSmallerEquals(key: string, value: any): ContextKeyExpression;
66 > mapRegex(key: string, regexp: RegExp | null): ContextKeyRegexExpr;
67 > mapIn(key: string, valueKey: string): ContextKeyInExpr;
68 > mapNotIn(key: string, valueKey: string): ContextKeyNotInExpr;
69 > }
70 >
71 > export interface IContextKeyExpression {
72 > cmp(other: ContextKeyExpression): number;
73 > equals(other: ContextKeyExpression): boolean;
74 > substituteConstants(): ContextKeyExpression | undefined;
75 > evaluate(context: IContext): boolean;
76 > serialize(): string;
77 > keys(): string[];
78 > map(mapFnc: IContextKeyExprMapper): ContextKeyExpression;
79 > negate(): ContextKeyExpression;
80 >
81 > }
82 >
83 > export type ContextKeyExpression = (
84 > ContextKeyFalseExpr | ContextKeyTrueExpr | ContextKeyDefinedExpr | ContextKeyNotExpr
85 > | ContextKeyEqualsExpr | ContextKeyNotEqualsExpr | ContextKeyRegexExpr
86 > | ContextKeyNotRegexExpr | ContextKeyAndExpr | ContextKeyOrExpr | ContextKeyInExpr
87 > | ContextKeyNotInExpr | ContextKeyGreaterExpr | ContextKeyGreaterEqualsExpr
88 > | ContextKeySmallerExpr | ContextKeySmallerEqualsExpr
89 > );
90 >
91 >
92 > /*
93 >
94 > Syntax grammar:
95 >
96 > ```ebnf
97 >
98 > expression ::= or
99 >
100 > or ::= and { '||' and }*
101 >
102 > and ::= term { '&&' term }*
103 >
104 > term ::=
105 > | '!' (KEY | true | false | parenthesized)
106 > | primary
107 >
108 > primary ::=
109 > | 'true'
110 > | 'false'
111 > | parenthesized
112 > | KEY '=~' REGEX
113 > | KEY [ ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'not' 'in' | 'in') value ]
114 >
115 > parenthesized ::=
116 > | '(' expression ')'
117 >
118 > value ::=
119 > | 'true'
120 > | 'false'
121 > | 'in' // we support `in` as a value because there's an extension that uses it, ie "when": "languageId == in"
122 > | VALUE // matched by the same regex as KEY; consider putting the value in single quotes if it's a string (e.g., with spaces)
123 > | SINGLE_QUOTED_STR
124 > | EMPTY_STR // this allows "when": "foo == " which's used by existing extensions
125 >
126 > ```
127 > */
128 >
129 > export type ParserConfig = {
130 > /**
131 > * with this option enabled, the parser can recover from regex parsing errors, e.g., unescaped slashes: `/src//` is accepted as `/src\//` would be
132 > */
133 > regexParsingWithErrorRecovery: boolean;
134 > };
135 >
136 > const defaultConfig: ParserConfig = {
137 > regexParsingWithErrorRecovery: true
138 > };
139 >
140 > export type ParsingError = {
141 > message: string;
142 > offset: number;
143 > lexeme: string;
144 > additionalInfo?: string;
145 > };
146 >
147 > const errorEmptyString = localize('contextkey.parser.error.emptyString', "Empty context key expression");
148 > const hintEmptyString = localize('contextkey.parser.error.emptyString.hint', "Did you forget to write an expression? You can also put 'false' or 'true' to always evaluate to false or true, respectively.");
149 > const errorNoInAfterNot = localize('contextkey.parser.error.noInAfterNot', "'in' after 'not'.");
150 > const errorClosingParenthesis = localize('contextkey.parser.error.closingParenthesis', "closing parenthesis ')'");
151 > const errorUnexpectedToken = localize('contextkey.parser.error.unexpectedToken', "Unexpected token");
152 > const hintUnexpectedToken = localize('contextkey.parser.error.unexpectedToken.hint', "Did you forget to put && or || before the token?");
153 > const errorUnexpectedEOF = localize('contextkey.parser.error.unexpectedEOF', "Unexpected end of expression");
154 > const hintUnexpectedEOF = localize('contextkey.parser.error.unexpectedEOF.hint', "Did you forget to put a context key?");
155 >
156 > /**
157 > * A parser for context key expressions.
158 > *
159 > * Example:
160 > * ```ts
161 > * const parser = new Parser();
162 > * const expr = parser.parse('foo == "bar" && baz == true');
163 > *
164 > * if (expr === undefined) {
165 > * // there were lexing or parsing errors
166 > * // process lexing errors with `parser.lexingErrors`
167 > * // process parsing errors with `parser.parsingErrors`
168 > * } else {
169 > * // expr is a valid expression
170 > * }
171 > * ```
172 > */
173 > export class Parser {
174 > // Note: this doesn't produce an exact syntax tree but a normalized one
175 > // ContextKeyExpression's that we use as AST nodes do not expose constructors that do not normalize
176 >
177 > private static _parseError = new Error();
178 >
179 > // lifetime note: `_scanner` lives as long as the parser does, i.e., is not reset between calls to `parse`
180 > private readonly _scanner = new Scanner();
181 >
182 > // lifetime note: `_tokens`, `_current`, and `_parsingErrors` must be reset between calls to `parse`
183 > private _tokens: Token[] = [];
184 > private _current = 0; // invariant: 0 <= this._current < this._tokens.length ; any incrementation of this value must first call `_isAtEnd`
185 > private _parsingErrors: ParsingError[] = [];
186 >
187 > get lexingErrors(): Readonly<LexingError[]> {
188 return this._scanner.errors;
189 }
191 > get parsingErrors(): Readonly<ParsingError[]> {
192 return this._parsingErrors;
193 }
195 > constructor(private readonly _config: ParserConfig = defaultConfig) {
196 > }
197 >
198 > /**
199 > * Parse a context key expression.
200 > *
201 > * @param input the expression to parse
202 > * @returns the parsed expression or `undefined` if there's an error - call `lexingErrors` and `parsingErrors` to see the errors
203 > */
204 > parse(input: string): ContextKeyExpression | undefined {
205
206 if (input === '') {
231 }
232 }
234 > private _expr(): ContextKeyExpression | undefined {
235 return this._or();
236 }
238 > private _or(): ContextKeyExpression | undefined {
239 const expr = [this._and()];
240
246 return expr.length === 1 ? expr[0] : ContextKeyExpr.or(...expr);
247 }
249 > private _and(): ContextKeyExpression | undefined {
250 const expr = [this._term()];
251
257 return expr.length === 1 ? expr[0] : ContextKeyExpr.and(...expr);
258 }
260 > private _term(): ContextKeyExpression | undefined {
261 if (this._matchOne(TokenType.Neg)) {
262 const peek = this._peek();
283 return this._primary();
284 }
286 > private _primary(): ContextKeyExpression | undefined {
287
288 const peek = this._peek();
498 }
499 }
501 > private _value(): string {
502 const token = this._peek();
503 switch (token.type) {
521 }
522 }
524 > private _flagsGYRe = /g|y/g;
525 > private _removeFlagsGY(flags: string): string {
526 return flags.replaceAll(this._flagsGYRe, '');
527 }
529 > // careful: this can throw if current token is the initial one (ie index = 0)
530 > private _previous() {
531 return this._tokens[this._current - 1];
532 }
534 > private _matchOne(token: TokenType) {
535 if (this._check(token)) {
536 this._advance();
540 return false;
541 }
543 > private _advance() {
544 if (!this._isAtEnd()) {
545 this._current++;
547 return this._previous();
548 }
550 > private _consume(type: TokenType, message: string) {
551 if (this._check(type)) {
552 return this._advance();
555 throw this._errExpectedButGot(message, this._peek());
556 }
558 > private _errExpectedButGot(expected: string, got: Token, additionalInfo?: string) {
559 const message = localize('contextkey.parser.error.expectedButGot', "Expected: {0}\nReceived: '{1}'.", expected, Scanner.getLexeme(got));
560 const offset = got.offset;
563 return Parser._parseError;
564 }
566 > private _check(type: TokenType) {
567 return this._peek().type === type;
568 }
570 > private _peek() {
571 return this._tokens[this._current];
572 }
574 > private _isAtEnd() {
575 return this._peek().type === TokenType.EOF;
576 }
577 > } contextkey.ts
578 >
579 > export abstract class ContextKeyExpr {
580 >
581 > public static false(): ContextKeyExpression {
582 return ContextKeyFalseExpr.INSTANCE;
583 }
584 > public static true(): ContextKeyExpression { contextkey.ts
585 return ContextKeyTrueExpr.INSTANCE;
586 }
587 > public static has(key: string): ContextKeyExpression { contextkey.ts
588 return ContextKeyDefinedExpr.create(key);
589 }
590 > public static equals(key: string, value: any): ContextKeyExpression { contextkey.ts
591 return ContextKeyEqualsExpr.create(key, value);
592 }
593 > public static notEquals(key: string, value: any): ContextKeyExpression { contextkey.ts
594 return ContextKeyNotEqualsExpr.create(key, value);
595 }
596 > public static regex(key: string, value: RegExp): ContextKeyExpression { contextkey.ts
597 return ContextKeyRegexExpr.create(key, value);
598 }
599 > public static in(key: string, value: string): ContextKeyExpression { contextkey.ts
600 return ContextKeyInExpr.create(key, value);
601 }
602 > public static notIn(key: string, value: string): ContextKeyExpression { contextkey.ts
603 return ContextKeyNotInExpr.create(key, value);
604 }
605 > public static not(key: string): ContextKeyExpression { contextkey.ts
606 return ContextKeyNotExpr.create(key);
607 }
608 > public static and(...expr: Array<ContextKeyExpression | undefined | null>): ContextKeyExpression | undefined { contextkey.ts
609 return ContextKeyAndExpr.create(expr, null, true);
610 }
611 > public static or(...expr: Array<ContextKeyExpression | undefined | null>): ContextKeyExpression | undefined { contextkey.ts
612 return ContextKeyOrExpr.create(expr, null, true);
613 }
614 > public static greater(key: string, value: number): ContextKeyExpression { contextkey.ts
615 return ContextKeyGreaterExpr.create(key, value);
616 }
617 > public static greaterEquals(key: string, value: number): ContextKeyExpression { contextkey.ts
618 return ContextKeyGreaterEqualsExpr.create(key, value);
619 }
620 > public static smaller(key: string, value: number): ContextKeyExpression { contextkey.ts
621 return ContextKeySmallerExpr.create(key, value);
622 }
623 > public static smallerEquals(key: string, value: number): ContextKeyExpression { contextkey.ts
624 return ContextKeySmallerEqualsExpr.create(key, value);
625 }
627 > private static _parser = new Parser({ regexParsingWithErrorRecovery: false });
628 > public static deserialize(serialized: string | null | undefined): ContextKeyExpression | undefined {
629 if (serialized === undefined || serialized === null) { // an empty string needs to be handled by the parser to get a corresponding parsing error reported
630 return undefined;
634 return expr;
635 }
637 > }
638 >
639 >
640 > export function validateWhenClauses(whenClauses: string[]): any {
641
642 const parser = new Parser({ regexParsingWithErrorRecovery: false }); // we run with no recovery to guide users to use correct regexes
664 });
665 }
667 > export function expressionsAreEqualWithConstantSubstitution(a: ContextKeyExpression | null | undefined, b: ContextKeyExpression | null | undefined): boolean {
668 const aExpr = a ? a.substituteConstants() : undefined;
669 const bExpr = b ? b.substituteConstants() : undefined;
676 return aExpr.equals(bExpr);
677 }
679 function cmp(a: ContextKeyExpression, b: ContextKeyExpression): number {
680 return a.cmp(b);
681 }
683 > export class ContextKeyFalseExpr implements IContextKeyExpression {
684 > public static INSTANCE = new ContextKeyFalseExpr();
685 >
686 > public readonly type = ContextKeyExprType.False;
687 >
688 > protected constructor() {
689 > }
690 >
691 > public cmp(other: ContextKeyExpression): number {
692 return this.type - other.type;
693 }
695 > public equals(other: ContextKeyExpression): boolean {
696 return (other.type === this.type);
697 }
699 > public substituteConstants(): ContextKeyExpression | undefined {
700 return this;
701 }
703 > public evaluate(context: IContext): boolean {
704 return false;
705 }
707 > public serialize(): string {
708 return 'false';
709 }
711 > public keys(): string[] {
712 return [];
713 }
715 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
716 return this;
717 }
719 > public negate(): ContextKeyExpression {
720 return ContextKeyTrueExpr.INSTANCE;
721 }
722 > } contextkey.ts
723 >
724 > export class ContextKeyTrueExpr implements IContextKeyExpression {
725 > public static INSTANCE = new ContextKeyTrueExpr();
726 >
727 > public readonly type = ContextKeyExprType.True;
728 >
729 > protected constructor() {
730 > }
731 >
732 > public cmp(other: ContextKeyExpression): number {
733 return this.type - other.type;
734 }
736 > public equals(other: ContextKeyExpression): boolean {
737 return (other.type === this.type);
738 }
740 > public substituteConstants(): ContextKeyExpression | undefined {
741 return this;
742 }
744 > public evaluate(context: IContext): boolean {
745 return true;
746 }
748 > public serialize(): string {
749 return 'true';
750 }
752 > public keys(): string[] {
753 return [];
754 }
756 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
757 return this;
758 }
760 > public negate(): ContextKeyExpression {
761 return ContextKeyFalseExpr.INSTANCE;
762 }
763 > } contextkey.ts
764 >
765 > export class ContextKeyDefinedExpr implements IContextKeyExpression {
766 > public static create(key: string, negated: ContextKeyExpression | null = null): ContextKeyExpression {
767 > const constantValue = CONSTANT_VALUES.get(key);
768 > if (typeof constantValue === 'boolean') {
769 > return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; contextkey.ts
770 > }
771 > return new ContextKeyDefinedExpr(key, negated); contextkey.ts
772 > }
773 >
774 > public readonly type = ContextKeyExprType.Defined;
775 >
776 > protected constructor(
777 > readonly key: string, contextkey.ts
778 > private negated: ContextKeyExpression | null
779 > ) {
780 > }
782 > public cmp(other: ContextKeyExpression): number {
783 if (other.type !== this.type) {
784 return this.type - other.type;
786 return cmp1(this.key, other.key);
787 }
789 > public equals(other: ContextKeyExpression): boolean {
790 if (other.type === this.type) {
791 return (this.key === other.key);
793 return false;
794 }
796 > public substituteConstants(): ContextKeyExpression | undefined {
797 const constantValue = CONSTANT_VALUES.get(this.key);
798 if (typeof constantValue === 'boolean') {
801 return this;
802 }
804 > public evaluate(context: IContext): boolean {
805 return (!!context.getValue(this.key));
806 }
808 > public serialize(): string {
809 return this.key;
810 }
812 > public keys(): string[] {
813 return [this.key];
814 }
816 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
817 return mapFnc.mapDefined(this.key);
818 }
820 > public negate(): ContextKeyExpression {
821 if (!this.negated) {
822 this.negated = ContextKeyNotExpr.create(this.key, this);
824 return this.negated;
825 }
826 > } contextkey.ts
827 >
828 > export class ContextKeyEqualsExpr implements IContextKeyExpression {
829 >
830 > public static create(key: string, value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression {
831 > if (typeof value === 'boolean') {
832 > return (value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated)); contextkey.ts
833 > }
834 > const constantValue = CONSTANT_VALUES.get(key); contextkey.ts
835 > if (typeof constantValue === 'boolean') {
836 > const trueValue = constantValue ? 'true' : 'false'; contextkey.ts
837 > return (value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE);
838 > }
839 > return new ContextKeyEqualsExpr(key, value, negated); contextkey.ts
840 > } contextkey.ts
841 >
842 > public readonly type = ContextKeyExprType.Equals;
843 >
844 > private constructor(
845 private readonly key: string,
846 private readonly value: any,
848 ) {
849 }
851 > public cmp(other: ContextKeyExpression): number {
852 if (other.type !== this.type) {
853 return this.type - other.type;
855 return cmp2(this.key, this.value, other.key, other.value);
856 }
858 > public equals(other: ContextKeyExpression): boolean {
859 if (other.type === this.type) {
860 return (this.key === other.key && this.value === other.value);
862 return false;
863 }
865 > public substituteConstants(): ContextKeyExpression | undefined {
866 const constantValue = CONSTANT_VALUES.get(this.key);
867 if (typeof constantValue === 'boolean') {
871 return this;
872 }
874 > public evaluate(context: IContext): boolean {
875 // Intentional ==
876 // eslint-disable-next-line eqeqeq
877 return (context.getValue(this.key) == this.value);
878 }
880 > public serialize(): string {
881 return `${this.key} == '${this.value}'`;
882 }
884 > public keys(): string[] {
885 return [this.key];
886 }
888 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
889 return mapFnc.mapEquals(this.key, this.value);
890 }
892 > public negate(): ContextKeyExpression {
893 if (!this.negated) {
894 this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this);
896 return this.negated;
897 }
898 > } contextkey.ts
899 >
900 > export class ContextKeyInExpr implements IContextKeyExpression {
901 >
902 > public static create(key: string, valueKey: string): ContextKeyInExpr {
903 > return new ContextKeyInExpr(key, valueKey);
904 > }
905 >
906 > public readonly type = ContextKeyExprType.In;
907 > private negated: ContextKeyExpression | null = null;
908 >
909 > private constructor(
910 private readonly key: string,
911 private readonly valueKey: string,
912 ) {
913 }
915 > public cmp(other: ContextKeyExpression): number {
916 if (other.type !== this.type) {
917 return this.type - other.type;
919 return cmp2(this.key, this.valueKey, other.key, other.valueKey);
920 }
922 > public equals(other: ContextKeyExpression): boolean {
923 if (other.type === this.type) {
924 return (this.key === other.key && this.valueKey === other.valueKey);
926 return false;
927 }
929 > public substituteConstants(): ContextKeyExpression | undefined {
930 return this;
931 }
933 > public evaluate(context: IContext): boolean {
934 const source = context.getValue(this.valueKey);
935
964 return false;
965 }
967 > public serialize(): string {
968 return `${this.key} in '${this.valueKey}'`;
969 }
971 > public keys(): string[] {
972 return [this.key, this.valueKey];
973 }
975 > public map(mapFnc: IContextKeyExprMapper): ContextKeyInExpr {
976 return mapFnc.mapIn(this.key, this.valueKey);
977 }
979 > public negate(): ContextKeyExpression {
980 if (!this.negated) {
981 this.negated = ContextKeyNotInExpr.create(this.key, this.valueKey);
983 return this.negated;
984 }
985 > } contextkey.ts
986 >
987 > export class ContextKeyNotInExpr implements IContextKeyExpression {
988 >
989 > public static create(key: string, valueKey: string): ContextKeyNotInExpr {
990 > return new ContextKeyNotInExpr(key, valueKey);
991 > }
992 >
993 > public readonly type = ContextKeyExprType.NotIn;
994 >
995 > private readonly _negated: ContextKeyInExpr;
996 >
997 > private constructor(
998 private readonly key: string,
999 private readonly valueKey: string,
1001 this._negated = ContextKeyInExpr.create(key, valueKey);
1002 }
1003 > contextkey.ts
1004 > public cmp(other: ContextKeyExpression): number {
1005 if (other.type !== this.type) {
1006 return this.type - other.type;
1008 return this._negated.cmp(other._negated);
1009 }
1010 > contextkey.ts
1011 > public equals(other: ContextKeyExpression): boolean {
1012 if (other.type === this.type) {
1013 return this._negated.equals(other._negated);
1015 return false;
1016 }
1017 > contextkey.ts
1018 > public substituteConstants(): ContextKeyExpression | undefined {
1019 return this;
1020 }
1021 > contextkey.ts
1022 > public evaluate(context: IContext): boolean {
1023 return !this._negated.evaluate(context);
1024 }
1025 > contextkey.ts
1026 > public serialize(): string {
1027 return `${this.key} not in '${this.valueKey}'`;
1028 }
1029 > contextkey.ts
1030 > public keys(): string[] {
1031 return this._negated.keys();
1032 }
1033 > contextkey.ts
1034 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1035 return mapFnc.mapNotIn(this.key, this.valueKey);
1036 }
1037 > contextkey.ts
1038 > public negate(): ContextKeyExpression {
1039 return this._negated;
1040 }
1041 > } contextkey.ts
1042 >
1043 > export class ContextKeyNotEqualsExpr implements IContextKeyExpression {
1044 >
1045 > public static create(key: string, value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression {
1046 > if (typeof value === 'boolean') {
1047 > if (value) { contextkey.ts
1048 > return ContextKeyNotExpr.create(key, negated); contextkey.ts
1049 > }
1050 > return ContextKeyDefinedExpr.create(key, negated); contextkey.ts
1051 > }
1052 > const constantValue = CONSTANT_VALUES.get(key); contextkey.ts
1053 > if (typeof constantValue === 'boolean') {
1054 > const falseValue = constantValue ? 'true' : 'false'; contextkey.ts
1055 > return (value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE);
1056 > }
1057 > return new ContextKeyNotEqualsExpr(key, value, negated); contextkey.ts
1058 > } contextkey.ts
1059 >
1060 > public readonly type = ContextKeyExprType.NotEquals;
1061 >
1062 > private constructor(
1063 private readonly key: string,
1064 private readonly value: any,
1066 ) {
1067 }
1068 > contextkey.ts
1069 > public cmp(other: ContextKeyExpression): number {
1070 if (other.type !== this.type) {
1071 return this.type - other.type;
1073 return cmp2(this.key, this.value, other.key, other.value);
1074 }
1075 > contextkey.ts
1076 > public equals(other: ContextKeyExpression): boolean {
1077 if (other.type === this.type) {
1078 return (this.key === other.key && this.value === other.value);
1080 return false;
1081 }
1082 > contextkey.ts
1083 > public substituteConstants(): ContextKeyExpression | undefined {
1084 const constantValue = CONSTANT_VALUES.get(this.key);
1085 if (typeof constantValue === 'boolean') {
1089 return this;
1090 }
1091 > contextkey.ts
1092 > public evaluate(context: IContext): boolean {
1093 // Intentional !=
1094 // eslint-disable-next-line eqeqeq
1095 return (context.getValue(this.key) != this.value);
1096 }
1097 > contextkey.ts
1098 > public serialize(): string {
1099 return `${this.key} != '${this.value}'`;
1100 }
1101 > contextkey.ts
1102 > public keys(): string[] {
1103 return [this.key];
1104 }
1105 > contextkey.ts
1106 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1107 return mapFnc.mapNotEquals(this.key, this.value);
1108 }
1109 > contextkey.ts
1110 > public negate(): ContextKeyExpression {
1111 if (!this.negated) {
1112 this.negated = ContextKeyEqualsExpr.create(this.key, this.value, this);
1114 return this.negated;
1115 }
1116 > } contextkey.ts
1117 >
1118 > export class ContextKeyNotExpr implements IContextKeyExpression {
1119 >
1120 > public static create(key: string, negated: ContextKeyExpression | null = null): ContextKeyExpression {
1121 > const constantValue = CONSTANT_VALUES.get(key);
1122 > if (typeof constantValue === 'boolean') {
1123 > return (constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE); contextkey.ts
1124 > }
1125 > return new ContextKeyNotExpr(key, negated); contextkey.ts
1126 > }
1127 >
1128 > public readonly type = ContextKeyExprType.Not;
1129 >
1130 > private constructor(
1131 private readonly key: string,
1132 private negated: ContextKeyExpression | null
1133 ) {
1134 }
1135 > contextkey.ts
1136 > public cmp(other: ContextKeyExpression): number {
1137 if (other.type !== this.type) {
1138 return this.type - other.type;
1140 return cmp1(this.key, other.key);
1141 }
1142 > contextkey.ts
1143 > public equals(other: ContextKeyExpression): boolean {
1144 if (other.type === this.type) {
1145 return (this.key === other.key);
1147 return false;
1148 }
1149 > contextkey.ts
1150 > public substituteConstants(): ContextKeyExpression | undefined {
1151 const constantValue = CONSTANT_VALUES.get(this.key);
1152 if (typeof constantValue === 'boolean') {
1155 return this;
1156 }
1157 > contextkey.ts
1158 > public evaluate(context: IContext): boolean {
1159 return (!context.getValue(this.key));
1160 }
1161 > contextkey.ts
1162 > public serialize(): string {
1163 return `!${this.key}`;
1164 }
1165 > contextkey.ts
1166 > public keys(): string[] {
1167 return [this.key];
1168 }
1169 > contextkey.ts
1170 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1171 return mapFnc.mapNot(this.key);
1172 }
1173 > contextkey.ts
1174 > public negate(): ContextKeyExpression {
1175 if (!this.negated) {
1176 this.negated = ContextKeyDefinedExpr.create(this.key, this);
1178 return this.negated;
1179 }
1180 > } contextkey.ts
1181 >
1182 function withFloatOrStr<T extends ContextKeyExpression>(value: any, callback: (value: number | string) => T): T | ContextKeyFalseExpr {
1183 if (typeof value === 'string') {
1192 return ContextKeyFalseExpr.INSTANCE;
1193 }
1194 > contextkey.ts
1195 > export class ContextKeyGreaterExpr implements IContextKeyExpression {
1196 >
1197 > public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression {
1198 > return withFloatOrStr(_value, (value) => new ContextKeyGreaterExpr(key, value, negated));
1199 > }
1200 >
1201 > public readonly type = ContextKeyExprType.Greater;
1202 >
1203 > private constructor(
1204 private readonly key: string,
1205 private readonly value: number | string,
1206 private negated: ContextKeyExpression | null
1207 ) { }
1208 > contextkey.ts
1209 > public cmp(other: ContextKeyExpression): number {
1210 if (other.type !== this.type) {
1211 return this.type - other.type;
1213 return cmp2(this.key, this.value, other.key, other.value);
1214 }
1215 > contextkey.ts
1216 > public equals(other: ContextKeyExpression): boolean {
1217 if (other.type === this.type) {
1218 return (this.key === other.key && this.value === other.value);
1220 return false;
1221 }
1222 > contextkey.ts
1223 > public substituteConstants(): ContextKeyExpression | undefined {
1224 return this;
1225 }
1226 > contextkey.ts
1227 > public evaluate(context: IContext): boolean {
1228 if (typeof this.value === 'string') {
1229 return false;
1231 return (parseFloat(context.getValue<any>(this.key)) > this.value);
1232 }
1233 > contextkey.ts
1234 > public serialize(): string {
1235 return `${this.key} > ${this.value}`;
1236 }
1237 > contextkey.ts
1238 > public keys(): string[] {
1239 return [this.key];
1240 }
1241 > contextkey.ts
1242 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1243 return mapFnc.mapGreater(this.key, this.value);
1244 }
1245 > contextkey.ts
1246 > public negate(): ContextKeyExpression {
1247 if (!this.negated) {
1248 this.negated = ContextKeySmallerEqualsExpr.create(this.key, this.value, this);
1250 return this.negated;
1251 }
1252 > } contextkey.ts
1253 >
1254 > export class ContextKeyGreaterEqualsExpr implements IContextKeyExpression {
1255 >
1256 > public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression {
1257 > return withFloatOrStr(_value, (value) => new ContextKeyGreaterEqualsExpr(key, value, negated));
1258 > }
1259 >
1260 > public readonly type = ContextKeyExprType.GreaterEquals;
1261 >
1262 > private constructor(
1263 private readonly key: string,
1264 private readonly value: number | string,
1265 private negated: ContextKeyExpression | null
1266 ) { }
1267 > contextkey.ts
1268 > public cmp(other: ContextKeyExpression): number {
1269 if (other.type !== this.type) {
1270 return this.type - other.type;
1272 return cmp2(this.key, this.value, other.key, other.value);
1273 }
1274 > contextkey.ts
1275 > public equals(other: ContextKeyExpression): boolean {
1276 if (other.type === this.type) {
1277 return (this.key === other.key && this.value === other.value);
1279 return false;
1280 }
1281 > contextkey.ts
1282 > public substituteConstants(): ContextKeyExpression | undefined {
1283 return this;
1284 }
1285 > contextkey.ts
1286 > public evaluate(context: IContext): boolean {
1287 if (typeof this.value === 'string') {
1288 return false;
1290 return (parseFloat(context.getValue<any>(this.key)) >= this.value);
1291 }
1292 > contextkey.ts
1293 > public serialize(): string {
1294 return `${this.key} >= ${this.value}`;
1295 }
1296 > contextkey.ts
1297 > public keys(): string[] {
1298 return [this.key];
1299 }
1300 > contextkey.ts
1301 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1302 return mapFnc.mapGreaterEquals(this.key, this.value);
1303 }
1304 > contextkey.ts
1305 > public negate(): ContextKeyExpression {
1306 if (!this.negated) {
1307 this.negated = ContextKeySmallerExpr.create(this.key, this.value, this);
1309 return this.negated;
1310 }
1311 > } contextkey.ts
1312 >
1313 > export class ContextKeySmallerExpr implements IContextKeyExpression {
1314 >
1315 > public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression {
1316 > return withFloatOrStr(_value, (value) => new ContextKeySmallerExpr(key, value, negated));
1317 > }
1318 >
1319 > public readonly type = ContextKeyExprType.Smaller;
1320 >
1321 > private constructor(
1322 private readonly key: string,
1323 private readonly value: number | string,
1325 ) {
1326 }
1327 > contextkey.ts
1328 > public cmp(other: ContextKeyExpression): number {
1329 if (other.type !== this.type) {
1330 return this.type - other.type;
1332 return cmp2(this.key, this.value, other.key, other.value);
1333 }
1334 > contextkey.ts
1335 > public equals(other: ContextKeyExpression): boolean {
1336 if (other.type === this.type) {
1337 return (this.key === other.key && this.value === other.value);
1339 return false;
1340 }
1341 > contextkey.ts
1342 > public substituteConstants(): ContextKeyExpression | undefined {
1343 return this;
1344 }
1345 > contextkey.ts
1346 > public evaluate(context: IContext): boolean {
1347 if (typeof this.value === 'string') {
1348 return false;
1350 return (parseFloat(context.getValue<any>(this.key)) < this.value);
1351 }
1352 > contextkey.ts
1353 > public serialize(): string {
1354 return `${this.key} < ${this.value}`;
1355 }
1356 > contextkey.ts
1357 > public keys(): string[] {
1358 return [this.key];
1359 }
1360 > contextkey.ts
1361 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1362 return mapFnc.mapSmaller(this.key, this.value);
1363 }
1364 > contextkey.ts
1365 > public negate(): ContextKeyExpression {
1366 if (!this.negated) {
1367 this.negated = ContextKeyGreaterEqualsExpr.create(this.key, this.value, this);
1369 return this.negated;
1370 }
1371 > } contextkey.ts
1372 >
1373 > export class ContextKeySmallerEqualsExpr implements IContextKeyExpression {
1374 >
1375 > public static create(key: string, _value: any, negated: ContextKeyExpression | null = null): ContextKeyExpression {
1376 > return withFloatOrStr(_value, (value) => new ContextKeySmallerEqualsExpr(key, value, negated));
1377 > }
1378 >
1379 > public readonly type = ContextKeyExprType.SmallerEquals;
1380 >
1381 > private constructor(
1382 private readonly key: string,
1383 private readonly value: number | string,
1385 ) {
1386 }
1387 > contextkey.ts
1388 > public cmp(other: ContextKeyExpression): number {
1389 if (other.type !== this.type) {
1390 return this.type - other.type;
1392 return cmp2(this.key, this.value, other.key, other.value);
1393 }
1394 > contextkey.ts
1395 > public equals(other: ContextKeyExpression): boolean {
1396 if (other.type === this.type) {
1397 return (this.key === other.key && this.value === other.value);
1399 return false;
1400 }
1401 > contextkey.ts
1402 > public substituteConstants(): ContextKeyExpression | undefined {
1403 return this;
1404 }
1405 > contextkey.ts
1406 > public evaluate(context: IContext): boolean {
1407 if (typeof this.value === 'string') {
1408 return false;
1410 return (parseFloat(context.getValue<any>(this.key)) <= this.value);
1411 }
1412 > contextkey.ts
1413 > public serialize(): string {
1414 return `${this.key} <= ${this.value}`;
1415 }
1416 > contextkey.ts
1417 > public keys(): string[] {
1418 return [this.key];
1419 }
1420 > contextkey.ts
1421 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1422 return mapFnc.mapSmallerEquals(this.key, this.value);
1423 }
1424 > contextkey.ts
1425 > public negate(): ContextKeyExpression {
1426 if (!this.negated) {
1427 this.negated = ContextKeyGreaterExpr.create(this.key, this.value, this);
1429 return this.negated;
1430 }
1431 > } contextkey.ts
1432 >
1433 > export class ContextKeyRegexExpr implements IContextKeyExpression {
1434 >
1435 > public static create(key: string, regexp: RegExp | null): ContextKeyRegexExpr {
1436 > return new ContextKeyRegexExpr(key, regexp);
1437 > }
1438 >
1439 > public readonly type = ContextKeyExprType.Regex;
1440 > private negated: ContextKeyExpression | null = null;
1441 >
1442 > private constructor(
1443 private readonly key: string,
1444 private readonly regexp: RegExp | null
1446 //
1447 }
1448 > contextkey.ts
1449 > public cmp(other: ContextKeyExpression): number {
1450 if (other.type !== this.type) {
1451 return this.type - other.type;
1467 return 0;
1468 }
1469 > contextkey.ts
1470 > public equals(other: ContextKeyExpression): boolean {
1471 if (other.type === this.type) {
1472 const thisSource = this.regexp ? this.regexp.source : '';
1476 return false;
1477 }
1478 > contextkey.ts
1479 > public substituteConstants(): ContextKeyExpression | undefined {
1480 return this;
1481 }
1482 > contextkey.ts
1483 > public evaluate(context: IContext): boolean {
1484 const value = context.getValue<any>(this.key);
1485 return this.regexp ? this.regexp.test(value) : false;
1486 }
1487 > contextkey.ts
1488 > public serialize(): string {
1489 const value = this.regexp
1490 ? `/${this.regexp.source}/${this.regexp.flags}`
1492 return `${this.key} =~ ${value}`;
1493 }
1494 > contextkey.ts
1495 > public keys(): string[] {
1496 return [this.key];
1497 }
1498 > contextkey.ts
1499 > public map(mapFnc: IContextKeyExprMapper): ContextKeyRegexExpr {
1500 return mapFnc.mapRegex(this.key, this.regexp);
1501 }
1502 > contextkey.ts
1503 > public negate(): ContextKeyExpression {
1504 if (!this.negated) {
1505 this.negated = ContextKeyNotRegexExpr.create(this);
1507 return this.negated;
1508 }
1509 > } contextkey.ts
1510 >
1511 > export class ContextKeyNotRegexExpr implements IContextKeyExpression {
1512 >
1513 > public static create(actual: ContextKeyRegexExpr): ContextKeyExpression {
1514 > return new ContextKeyNotRegexExpr(actual);
1515 > }
1516 >
1517 > public readonly type = ContextKeyExprType.NotRegex;
1518 >
1519 > private constructor(private readonly _actual: ContextKeyRegexExpr) {
1520 //
1521 }
1522 > contextkey.ts
1523 > public cmp(other: ContextKeyExpression): number {
1524 if (other.type !== this.type) {
1525 return this.type - other.type;
1527 return this._actual.cmp(other._actual);
1528 }
1529 > contextkey.ts
1530 > public equals(other: ContextKeyExpression): boolean {
1531 if (other.type === this.type) {
1532 return this._actual.equals(other._actual);
1534 return false;
1535 }
1536 > contextkey.ts
1537 > public substituteConstants(): ContextKeyExpression | undefined {
1538 return this;
1539 }
1540 > contextkey.ts
1541 > public evaluate(context: IContext): boolean {
1542 return !this._actual.evaluate(context);
1543 }
1544 > contextkey.ts
1545 > public serialize(): string {
1546 return `!(${this._actual.serialize()})`;
1547 }
1548 > contextkey.ts
1549 > public keys(): string[] {
1550 return this._actual.keys();
1551 }
1552 > contextkey.ts
1553 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1554 return new ContextKeyNotRegexExpr(this._actual.map(mapFnc));
1555 }
1556 > contextkey.ts
1557 > public negate(): ContextKeyExpression {
1558 return this._actual;
1559 }
1560 > } contextkey.ts
1561 >
1562 > /**
1563 > * @returns the same instance if nothing changed.
1564 > */
1565 function eliminateConstantsInArray(arr: ContextKeyExpression[]): (ContextKeyExpression | undefined)[] {
1566 // Allocate array only if there is a difference
1591 return newArr;
1592 }
1593 > contextkey.ts
1594 > export class ContextKeyAndExpr implements IContextKeyExpression {
1595 >
1596 > public static create(_expr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined {
1597 > return ContextKeyAndExpr._normalizeArr(_expr, negated, extraRedundantCheck);
1598 > }
1599 >
1600 > public readonly type = ContextKeyExprType.And;
1601 >
1602 > private constructor(
1603 public readonly expr: ContextKeyExpression[],
1604 private negated: ContextKeyExpression | null
1605 ) {
1606 }
1607 > contextkey.ts
1608 > public cmp(other: ContextKeyExpression): number {
1609 if (other.type !== this.type) {
1610 return this.type - other.type;
1624 return 0;
1625 }
1626 > contextkey.ts
1627 > public equals(other: ContextKeyExpression): boolean {
1628 if (other.type === this.type) {
1629 if (this.expr.length !== other.expr.length) {
1639 return false;
1640 }
1641 > contextkey.ts
1642 > public substituteConstants(): ContextKeyExpression | undefined {
1643 const exprArr = eliminateConstantsInArray(this.expr);
1644 if (exprArr === this.expr) {
1648 return ContextKeyAndExpr.create(exprArr, this.negated, false);
1649 }
1650 > contextkey.ts
1651 > public evaluate(context: IContext): boolean {
1652 for (let i = 0, len = this.expr.length; i < len; i++) {
1653 if (!this.expr[i].evaluate(context)) {
1657 return true;
1658 }
1659 > contextkey.ts
1660 > private static _normalizeArr(arr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined {
1661 const expr: ContextKeyExpression[] = [];
1662 let hasTrue = false;
1762 return new ContextKeyAndExpr(expr, negated);
1763 }
1764 > contextkey.ts
1765 > public serialize(): string {
1766 return this.expr.map(e => e.serialize()).join(' && ');
1767 }
1768 > contextkey.ts
1769 > public keys(): string[] {
1770 const result: string[] = [];
1771 for (const expr of this.expr) {
1774 return result;
1775 }
1776 > contextkey.ts
1777 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1778 return new ContextKeyAndExpr(this.expr.map(expr => expr.map(mapFnc)), null);
1779 }
1780 > contextkey.ts
1781 > public negate(): ContextKeyExpression {
1782 if (!this.negated) {
1783 const result: ContextKeyExpression[] = [];
1789 return this.negated;
1790 }
1791 > } contextkey.ts
1792 >
1793 > export class ContextKeyOrExpr implements IContextKeyExpression {
1794 >
1795 > public static create(_expr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined {
1796 > return ContextKeyOrExpr._normalizeArr(_expr, negated, extraRedundantCheck);
1797 > }
1798 >
1799 > public readonly type = ContextKeyExprType.Or;
1800 >
1801 > private constructor(
1802 public readonly expr: ContextKeyExpression[],
1803 private negated: ContextKeyExpression | null
1804 ) {
1805 }
1806 > contextkey.ts
1807 > public cmp(other: ContextKeyExpression): number {
1808 if (other.type !== this.type) {
1809 return this.type - other.type;
1823 return 0;
1824 }
1825 > contextkey.ts
1826 > public equals(other: ContextKeyExpression): boolean {
1827 if (other.type === this.type) {
1828 if (this.expr.length !== other.expr.length) {
1838 return false;
1839 }
1840 > contextkey.ts
1841 > public substituteConstants(): ContextKeyExpression | undefined {
1842 const exprArr = eliminateConstantsInArray(this.expr);
1843 if (exprArr === this.expr) {
1847 return ContextKeyOrExpr.create(exprArr, this.negated, false);
1848 }
1849 > contextkey.ts
1850 > public evaluate(context: IContext): boolean {
1851 for (let i = 0, len = this.expr.length; i < len; i++) {
1852 if (this.expr[i].evaluate(context)) {
1856 return false;
1857 }
1858 > contextkey.ts
1859 > private static _normalizeArr(arr: ReadonlyArray<ContextKeyExpression | null | undefined>, negated: ContextKeyExpression | null, extraRedundantCheck: boolean): ContextKeyExpression | undefined {
1860 let expr: ContextKeyExpression[] = [];
1861 let hasFalse = false;
1932 return new ContextKeyOrExpr(expr, negated);
1933 }
1934 > contextkey.ts
1935 > public serialize(): string {
1936 return this.expr.map(e => e.serialize()).join(' || ');
1937 }
1938 > contextkey.ts
1939 > public keys(): string[] {
1940 const result: string[] = [];
1941 for (const expr of this.expr) {
1944 return result;
1945 }
1946 > contextkey.ts
1947 > public map(mapFnc: IContextKeyExprMapper): ContextKeyExpression {
1948 return new ContextKeyOrExpr(this.expr.map(expr => expr.map(mapFnc)), null);
1949 }
1950 > contextkey.ts
1951 > public negate(): ContextKeyExpression {
1952 if (!this.negated) {
1953 const result: ContextKeyExpression[] = [];
1976 return this.negated;
1977 }
1978 > } contextkey.ts
1979 >
1980 > export interface ContextKeyInfo {
1981 > readonly key: string;
1982 > readonly type?: string;
1983 > readonly description?: string;
1984 > }
1985 >
1986 > export class RawContextKey<T extends ContextKeyValue> extends ContextKeyDefinedExpr {
1987 >
1988 > private static _info: ContextKeyInfo[] = [];
1989 >
1990 > static all(): IterableIterator<ContextKeyInfo> {
1991 return RawContextKey._info.values();
1992 }
1993 > contextkey.ts
1994 > private readonly _defaultValue: T | undefined;
1995 >
1996 > constructor(key: string, defaultValue: T | undefined, metaOrHide?: string | true | { type: string; description: string }) {
1997 > super(key, null); contextkey.ts
1998 > this._defaultValue = defaultValue;
1999 >
2000 > // collect all context keys into a central place
2001 > if (typeof metaOrHide === 'object') {
2002 RawContextKey._info.push({ ...metaOrHide, key });
2003 > } else if (metaOrHide !== true) { contextkey.ts
2004 > RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== undefined ? typeof defaultValue : undefined }); contextkey.ts
2005 > }
2006 > } contextkey.ts
2007 > contextkey.ts
2008 > public bindTo(target: IContextKeyService): IContextKey<T> {
2009 return target.createKey(this.key, this._defaultValue);
2010 }
2011 > contextkey.ts
2012 > public getValue(target: IContextKeyService): T | undefined {
2013 return target.getContextKeyValue<T>(this.key);
2014 }
2015 > contextkey.ts
2016 > public toNegated(): ContextKeyExpression {
2017 return this.negate();
2018 }
2019 > contextkey.ts
2020 > public isEqualTo(value: any): ContextKeyExpression {
2021 return ContextKeyEqualsExpr.create(this.key, value);
2022 }
2023 > contextkey.ts
2024 > public notEqualsTo(value: any): ContextKeyExpression {
2025 return ContextKeyNotEqualsExpr.create(this.key, value);
2026 }
2027 > contextkey.ts
2028 > public greater(value: any): ContextKeyExpression {
2029 return ContextKeyGreaterExpr.create(this.key, value);
2030 }
2031 > } contextkey.ts
2032 >
2033 > export type ContextKeyValue = null | undefined | boolean | number | string
2034 > | Array<null | undefined | boolean | number | string>
2035 > | Record<string, null | undefined | boolean | number | string>;
2036 >
2037 > export interface IContext {
2038 > getValue<T extends ContextKeyValue = ContextKeyValue>(key: string): T | undefined;
2039 > }
2040 >
2041 > export interface IContextKey<T extends ContextKeyValue = ContextKeyValue> {
2042 > set(value: T): void;
2043 > reset(): void;
2044 > get(): T | undefined;
2045 > }
2046 >
2047 > export interface IContextKeyServiceTarget {
2048 > parentElement: IContextKeyServiceTarget | null;
2049 > setAttribute(attr: string, value: string): void;
2050 > removeAttribute(attr: string): void;
2051 > hasAttribute(attr: string): boolean;
2052 > getAttribute(attr: string): string | null;
2053 > }
2054 >
2055 > export const IContextKeyService = createDecorator<IContextKeyService>('contextKeyService');
2056 >
2057 > export interface IReadableSet<T> {
2058 > has(value: T): boolean;
2059 > }
2060 >
2061 > export interface IContextKeyChangeEvent {
2062 > affectsSome(keys: IReadableSet<string>): boolean;
2063 > allKeysContainedIn(keys: IReadableSet<string>): boolean;
2064 > }
2065 >
2066 > export type IScopedContextKeyService = IContextKeyService & IDisposable;
2067 >
2068 > export interface IContextKeyService {
2069 > readonly _serviceBrand: undefined;
2070 >
2071 > readonly onDidChangeContext: Event<IContextKeyChangeEvent>;
2072 > bufferChangeEvents(callback: Function): void;
2073 >
2074 > createKey<T extends ContextKeyValue>(key: string, defaultValue: T | undefined): IContextKey<T>;
2075 > contextMatchesRules(rules: ContextKeyExpression | undefined): boolean;
2076 > getContextKeyValue<T>(key: string): T | undefined;
2077 >
2078 > createScoped(target: IContextKeyServiceTarget): IScopedContextKeyService;
2079 > createOverlay(overlay: Iterable<[string, any]>): IContextKeyService;
2080 > getContext(target: IContextKeyServiceTarget | null): IContext;
2081 >
2082 > updateParent(parentContextKeyService: IContextKeyService): void;
2083 > }
2084 >
2085 function cmp1(key1: string, key2: string): number {
2086 if (key1 < key2) {
2092 return 0;
2093 }
2094 > contextkey.ts
2095 function cmp2(key1: string, value1: any, key2: string, value2: any): number {
2096 if (key1 < key2) {
2108 return 0;
2109 }
2110 > contextkey.ts
2111 > /**
2112 > * Returns true if it is provable `p` implies `q`.
2113 > */
2114 > export function implies(p: ContextKeyExpression, q: ContextKeyExpression): boolean {
2115
2116 if (p.type === ContextKeyExprType.False || q.type === ContextKeyExprType.True) {
2152 return p.equals(q);
2153 }
2154 > contextkey.ts
2155 > /**
2156 > * Returns true if all elements in `p` are also present in `q`.
2157 > * The two arrays are assumed to be sorted
2158 > */
2159 function allElementsIncluded(p: ContextKeyExpression[], q: ContextKeyExpression[]): boolean {
2160 let pIndex = 0;
2175 return (pIndex === p.length);
2176 }
2177 > contextkey.ts
2178 function getTerminals(node: ContextKeyExpression) {
2179 if (node.type === ContextKeyExprType.Or) {
src/vs/platform/files/common/fileService.ts 786 covered LOC · 230 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- fileService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { coalesce } from '../../../base/common/arrays.js';
7 > import { Promises, ResourceQueue } from '../../../base/common/async.js';
8 > import { bufferedStreamToBuffer, bufferToReadable, newWriteableBufferStream, readableToBuffer, streamToBuffer, VSBuffer, VSBufferReadable, VSBufferReadableBufferedStream, VSBufferReadableStream } from '../../../base/common/buffer.js';
9 > import { CancellationToken, CancellationTokenSource } from '../../../base/common/cancellation.js';
10 > import { Emitter } from '../../../base/common/event.js';
11 > import { hash } from '../../../base/common/hash.js';
12 > import { Iterable } from '../../../base/common/iterator.js';
13 > import { Disposable, DisposableStore, dispose, IDisposable, toDisposable } from '../../../base/common/lifecycle.js';
14 > import { TernarySearchTree } from '../../../base/common/ternarySearchTree.js';
15 > import { Schemas } from '../../../base/common/network.js';
16 > import { mark } from '../../../base/common/performance.js';
17 > import { extUri, extUriIgnorePathCase, IExtUri, isAbsolutePath } from '../../../base/common/resources.js';
18 > import { consumeStream, isReadableBufferedStream, isReadableStream, listenStream, newWriteableStream, peekReadable, peekStream, transform } from '../../../base/common/stream.js';
19 > import { URI } from '../../../base/common/uri.js';
20 > import { localize } from '../../../nls.js';
21 > import { ensureFileSystemProviderError, etag, ETAG_DISABLED, FileChangesEvent, IFileDeleteOptions, FileOperation, FileOperationError, FileOperationEvent, FileOperationResult, FilePermission, FileSystemProviderCapabilities, FileSystemProviderErrorCode, FileType, hasFileAppendCapability, hasFileAtomicReadCapability, hasFileFolderCopyCapability, hasFileReadStreamCapability, hasOpenReadWriteCloseCapability, hasReadWriteCapability, ICreateFileOptions, IFileContent, IFileService, IFileStat, IFileStatWithMetadata, IFileStreamContent, IFileSystemProvider, IFileSystemProviderActivationEvent, IFileSystemProviderCapabilitiesChangeEvent, IFileSystemProviderRegistrationEvent, IFileSystemProviderWithFileAtomicReadCapability, IFileSystemProviderWithFileReadStreamCapability, IFileSystemProviderWithFileReadWriteCapability, IFileSystemProviderWithOpenReadWriteCloseCapability, IReadFileOptions, IReadFileStreamOptions, IResolveFileOptions, IFileStatResult, IFileStatResultWithMetadata, IResolveMetadataFileOptions, IStat, IFileStatWithPartialMetadata, IWatchOptions, IWriteFileOptions, NotModifiedSinceFileOperationError, toFileOperationResult, toFileSystemProviderErrorCode, hasFileCloneCapability, TooLargeFileOperationError, hasFileAtomicDeleteCapability, hasFileAtomicWriteCapability, IWatchOptionsWithCorrelation, IFileSystemWatcher, IWatchOptionsWithoutCorrelation, hasFileRealpathCapability } from './files.js';
22 > import { readFileIntoStream } from './io.js';
23 > import { ILogService } from '../../log/common/log.js';
24 > import { ErrorNoTelemetry } from '../../../base/common/errors.js';
25 >
26 > export class FileService extends Disposable implements IFileService {
27 >
28 > declare readonly _serviceBrand: undefined;
29 >
30 > // Choose a buffer size that is a balance between memory needs and
31 > // manageable IPC overhead. The larger the buffer size, the less
32 > // roundtrips we have to do for reading/writing data.
33 > private readonly BUFFER_SIZE = 256 * 1024;
34 >
35 > constructor(@ILogService private readonly logService: ILogService) {
36 > super(); fileService.ts
37 > }
38 >
39 > //#region File System Provider
40 >
41 > private readonly _onDidChangeFileSystemProviderRegistrations = this._register(new Emitter<IFileSystemProviderRegistrationEvent>());
42 > readonly onDidChangeFileSystemProviderRegistrations = this._onDidChangeFileSystemProviderRegistrations.event;
43 >
44 > private readonly _onWillActivateFileSystemProvider = this._register(new Emitter<IFileSystemProviderActivationEvent>());
45 > readonly onWillActivateFileSystemProvider = this._onWillActivateFileSystemProvider.event;
46 >
47 > private readonly _onDidChangeFileSystemProviderCapabilities = this._register(new Emitter<IFileSystemProviderCapabilitiesChangeEvent>());
48 > readonly onDidChangeFileSystemProviderCapabilities = this._onDidChangeFileSystemProviderCapabilities.event;
49 >
50 > private readonly provider = new Map<string, IFileSystemProvider>();
51 >
52 > registerProvider(scheme: string, provider: IFileSystemProvider): IDisposable {
53 > if (this.provider.has(scheme)) { fileService.ts
54 throw new Error(`A filesystem provider for the scheme '${scheme}' is already registered.`);
55 }
57 > mark(`code/registerFilesystem/${scheme}`);
58 >
59 > const providerDisposables = new DisposableStore();
60 >
61 > // Add provider with event
62 > this.provider.set(scheme, provider);
63 > this._onDidChangeFileSystemProviderRegistrations.fire({ added: true, scheme, provider });
64 >
65 > // Forward events from provider
66 > providerDisposables.add(provider.onDidChangeFile(changes => {
67 const event = new FileChangesEvent(changes, !this.isPathCaseSensitive(provider));
68
74 this._onDidUncorrelatedFilesChange.fire(event);
75 }
76 > })); fileService.ts
77 > if (typeof provider.onDidWatchError === 'function') {
78 providerDisposables.add(provider.onDidWatchError(error => this._onDidWatchError.fire(new Error(error))));
79 }
80 > providerDisposables.add(provider.onDidChangeCapabilities(() => this._onDidChangeFileSystemProviderCapabilities.fire({ provider, scheme }))); fileService.ts
81 >
82 > return toDisposable(() => {
83 > this._onDidChangeFileSystemProviderRegistrations.fire({ added: false, scheme, provider }); fileService.ts
84 > this.provider.delete(scheme);
85 >
86 > dispose(providerDisposables);
87 > }); fileService.ts
88 > }
90 > getProvider(scheme: string): IFileSystemProvider | undefined {
91 return this.provider.get(scheme);
92 }
94 > async activateProvider(scheme: string): Promise<void> {
96 > // Emit an event that we are about to activate a provider with the given scheme.
97 > // Listeners can participate in the activation by registering a provider for it.
98 > const joiners: Promise<void>[] = [];
99 > this._onWillActivateFileSystemProvider.fire({
100 > scheme,
101 > join(promise) {
102 joiners.push(promise);
103 },
104 > }); fileService.ts
105 >
106 > if (this.provider.has(scheme)) {
107 > return; // provider is already here so we can return directly fileService.ts
108 > }
109
110 // If the provider is not yet there, make sure to join on the listeners assuming
111 // that it takes a bit longer to register the file system provider.
112 await Promises.settled(joiners);
113 > } fileService.ts
115 > async canHandleResource(resource: URI): Promise<boolean> {
116
117 // Await activation of potentially extension contributed providers
120 return this.hasProvider(resource);
121 }
123 > hasProvider(resource: URI): boolean {
124 > return this.provider.has(resource.scheme); fileService.ts
125 > }
127 > hasCapability(resource: URI, capability: FileSystemProviderCapabilities): boolean {
128 > const provider = this.provider.get(resource.scheme); fileService.ts
129 >
130 > return !!(provider && (provider.capabilities & capability));
131 > }
133 > listCapabilities(): Iterable<{ scheme: string; capabilities: FileSystemProviderCapabilities }> {
134 return Iterable.map(this.provider, ([scheme, provider]) => ({ scheme, capabilities: provider.capabilities }));
135 }
137 > protected async withProvider(resource: URI): Promise<IFileSystemProvider> {
139 > // Assert path is absolute
140 > if (!isAbsolutePath(resource)) {
141 throw new FileOperationError(localize('invalidPath', "Unable to resolve filesystem provider with relative file path '{0}'", this.resourceForError(resource)), FileOperationResult.FILE_INVALID_PATH);
142 }
144 > // Activate provider
145 > await this.activateProvider(resource.scheme);
146 >
147 > // Assert provider
148 > const provider = this.provider.get(resource.scheme);
149 > if (!provider) {
150 const error = new ErrorNoTelemetry();
151 error.message = localize('noProviderFound', "ENOPRO: No file system provider found for resource '{0}'", resource.toString());
153 throw error;
154 }
156 > return provider;
157 > } fileService.ts
159 > private async withReadProvider(resource: URI): Promise<IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithOpenReadWriteCloseCapability | IFileSystemProviderWithFileReadStreamCapability> {
160 > const provider = await this.withProvider(resource); fileService.ts
161 >
162 > if (hasOpenReadWriteCloseCapability(provider) || hasReadWriteCapability(provider) || hasFileReadStreamCapability(provider)) {
163 > return provider;
164 > }
165
166 throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite, FileReadStream nor FileOpenReadWriteClose capability which is needed for the read operation.`);
167 > } fileService.ts
169 > private async withWriteProvider(resource: URI): Promise<IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithOpenReadWriteCloseCapability> {
170 > const provider = await this.withProvider(resource); fileService.ts
171 >
172 > if (hasOpenReadWriteCloseCapability(provider) || hasReadWriteCapability(provider)) {
173 > return provider;
174 > }
175
176 throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`);
177 > } fileService.ts
179 > //#endregion
180 >
181 > //#region Operation events
182 >
183 > private readonly _onDidRunOperation = this._register(new Emitter<FileOperationEvent>());
184 > readonly onDidRunOperation = this._onDidRunOperation.event;
185 >
186 > //#endregion
187 >
188 > //#region File Metadata Resolving
189 >
190 > async resolve(resource: URI, options: IResolveMetadataFileOptions): Promise<IFileStatWithMetadata>;
191 > async resolve(resource: URI, options?: IResolveFileOptions): Promise<IFileStat>;
192 > async resolve(resource: URI, options?: IResolveFileOptions): Promise<IFileStat> {
193 > try { fileService.ts
194 > return await this.doResolveFile(resource, options);
195 > } catch (error) {
197 > // Specially handle file not found case as file operation result
198 > if (toFileSystemProviderErrorCode(error) === FileSystemProviderErrorCode.FileNotFound) {
199 > throw new FileOperationError(localize('fileNotFoundError', "Unable to resolve nonexistent file '{0}'", this.resourceForError(resource)), FileOperationResult.FILE_NOT_FOUND); fileService.ts
200 > }
201
202 // Bubble up any other error as is
203 throw ensureFileSystemProviderError(error);
204 }
205 > } fileService.ts
207 > private async doResolveFile(resource: URI, options: IResolveMetadataFileOptions): Promise<IFileStatWithMetadata>;
208 > private async doResolveFile(resource: URI, options?: IResolveFileOptions): Promise<IFileStat>;
209 > private async doResolveFile(resource: URI, options?: IResolveFileOptions): Promise<IFileStat> {
210 > const provider = await this.withProvider(resource); fileService.ts
211 > const isPathCaseSensitive = this.isPathCaseSensitive(provider); fileService.ts
212 >
213 > const resolveTo = options?.resolveTo;
214 > const resolveSingleChildDescendants = options?.resolveSingleChildDescendants; fileService.ts
215 > const resolveMetadata = options?.resolveMetadata;
216 >
217 > const stat = await provider.stat(resource);
219 > let trie: TernarySearchTree<URI, boolean> | undefined;
220 >
221 > return this.toFileStat(provider, resource, stat, undefined, !!resolveMetadata, (stat, siblings) => {
223 > // lazy trie to check for recursive resolving
224 > if (!trie) {
225 > trie = TernarySearchTree.forUris<true>(() => !isPathCaseSensitive);
226 > trie.set(resource, true);
227 > if (resolveTo) {
228 trie.fill(true, resolveTo);
229 }
230 > } fileService.ts
231 >
232 > // check for recursive resolving
233 > if (trie.get(stat.resource) || trie.findSuperstr(stat.resource.with({ query: null, fragment: null } /* required for https://github.com/microsoft/vscode/issues/128151 */))) {
234 > return true;
235 > }
236
237 // check for resolving single child folders
238 > if (stat.isDirectory && resolveSingleChildDescendants) { fileService.ts
239 return siblings === 1;
240 }
241
242 return false;
243 > }); fileService.ts
244 > } fileService.ts
246 > private async toFileStat(provider: IFileSystemProvider, resource: URI, stat: IStat | { type: FileType } & Partial<IStat>, siblings: number | undefined, resolveMetadata: boolean, recurse: (stat: IFileStat, siblings?: number) => boolean): Promise<IFileStat>;
247 > private async toFileStat(provider: IFileSystemProvider, resource: URI, stat: IStat, siblings: number | undefined, resolveMetadata: true, recurse: (stat: IFileStat, siblings?: number) => boolean): Promise<IFileStatWithMetadata>;
248 > private async toFileStat(provider: IFileSystemProvider, resource: URI, stat: IStat | { type: FileType } & Partial<IStat>, siblings: number | undefined, resolveMetadata: boolean, recurse: (stat: IFileStat, siblings?: number) => boolean): Promise<IFileStat> {
249 > const { providerExtUri } = this.getExtUri(provider); fileService.ts
250 >
251 > // convert to file stat
252 > const fileStat: IFileStat = {
253 > resource,
254 > name: providerExtUri.basename(resource),
255 > isFile: (stat.type & FileType.File) !== 0,
256 > isDirectory: (stat.type & FileType.Directory) !== 0,
257 > isSymbolicLink: (stat.type & FileType.SymbolicLink) !== 0,
258 > mtime: stat.mtime,
259 > ctime: stat.ctime,
260 > size: stat.size,
261 > readonly: Boolean((stat.permissions ?? 0) & FilePermission.Readonly) || Boolean(provider.capabilities & FileSystemProviderCapabilities.Readonly),
262 > locked: Boolean((stat.permissions ?? 0) & FilePermission.Locked),
263 > executable: Boolean((stat.permissions ?? 0) & FilePermission.Executable),
264 > etag: etag({ mtime: stat.mtime, size: stat.size }),
265 > children: undefined
266 > };
267 >
268 > // check to recurse for directories
269 > if (fileStat.isDirectory && recurse(fileStat, siblings)) {
270 > try { fileService.ts
271 > const entries = await provider.readdir(resource);
272 > const resolvedEntries = await Promises.settled(entries.map(async ([name, type]) => {
273 > try { fileService.ts
274 > const childResource = providerExtUri.joinPath(resource, name);
275 > const childStat = resolveMetadata ? await provider.stat(childResource) : { type };
276 >
277 > return await this.toFileStat(provider, childResource, childStat, entries.length, resolveMetadata, recurse);
278 > } catch (error) {
279 this.logService.trace(error);
280
281 return null; // can happen e.g. due to permission errors
282 }
283 > })); fileService.ts
284 >
285 > // make sure to get rid of null values that signal a failure to resolve a particular entry
286 > fileStat.children = coalesce(resolvedEntries);
287 > } catch (error) {
288 this.logService.trace(error);
289
290 fileStat.children = []; // gracefully handle errors, we may not have permissions to read
291 }
293 > return fileStat;
294 > }
296 > return fileStat;
297 > } fileService.ts
299 > async resolveAll(toResolve: { resource: URI; options?: IResolveFileOptions }[]): Promise<IFileStatResult[]>;
300 > async resolveAll(toResolve: { resource: URI; options: IResolveMetadataFileOptions }[]): Promise<IFileStatResultWithMetadata[]>;
301 > async resolveAll(toResolve: { resource: URI; options?: IResolveFileOptions }[]): Promise<IFileStatResult[]> {
302 return Promises.settled(toResolve.map(async entry => {
303 try {
310 }));
311 }
313 > async stat(resource: URI): Promise<IFileStatWithPartialMetadata> {
314 const provider = await this.withProvider(resource);
315
318 return this.toFileStat(provider, resource, stat, undefined, true, () => false /* Do not resolve any children */);
319 }
321 > async realpath(resource: URI): Promise<URI | undefined> {
322 const provider = await this.withProvider(resource);
323
330 return undefined;
331 }
333 > async exists(resource: URI): Promise<boolean> {
334 > const provider = await this.withProvider(resource); fileService.ts
336 > try {
337 > const stat = await provider.stat(resource);
338
339 return !!stat;
340 > } catch (error) { fileService.ts
341 > return false; fileService.ts
342 > }
343 > } fileService.ts
345 > //#endregion
346 >
347 > //#region File Reading/Writing
348 >
349 > async canCreateFile(resource: URI, options?: ICreateFileOptions): Promise<Error | true> {
350 try {
351 await this.doValidateCreateFile(resource, options);
356 return true;
357 }
359 > private async doValidateCreateFile(resource: URI, options?: ICreateFileOptions): Promise<void> {
360
361 // validate overwrite
364 }
365 }
367 > async createFile(resource: URI, bufferOrReadableOrStream: VSBuffer | VSBufferReadable | VSBufferReadableStream = VSBuffer.fromString(''), options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {
368
369 // validate
378 return fileStat;
379 }
381 > async writeFile(resource: URI, bufferOrReadableOrStream: VSBuffer | VSBufferReadable | VSBufferReadableStream, options?: IWriteFileOptions): Promise<IFileStatWithMetadata> {
382 > const provider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(resource), resource); fileService.ts
383 > const { providerExtUri } = this.getExtUri(provider);
384 >
385 > let writeFileOptions = options;
386 > if (hasFileAtomicWriteCapability(provider) && !writeFileOptions?.atomic) {
387 const enforcedAtomicWrite = provider.enforceAtomicWriteFile?.(resource);
388 if (enforcedAtomicWrite) {
390 }
391 }
393 > try {
394 >
395 > // validate write (this may already return a peeked-at buffer)
396 > let { stat, buffer: bufferOrReadableOrStreamOrBufferedStream } = await this.validateWriteFile(provider, resource, bufferOrReadableOrStream, writeFileOptions);
397 >
398 > // mkdir recursively as needed
399 > if (!stat) {
400 > await this.mkdirp(provider, providerExtUri.dirname(resource)); fileService.ts
401 > }
403 > // optimization: if the provider has unbuffered write capability and the data
404 > // to write is not a buffer, we consume up to 3 chunks and try to write the data
405 > // unbuffered to reduce the overhead. If the stream or readable has more data
406 > // to provide we continue to write buffered.
407 > if (!bufferOrReadableOrStreamOrBufferedStream) {
408 > bufferOrReadableOrStreamOrBufferedStream = await this.peekBufferForWriting(provider, bufferOrReadableOrStream);
409 > }
410 >
411 > // write file: unbuffered
412 > if (
413 > !hasOpenReadWriteCloseCapability(provider) || // buffered writing is unsupported
414 > (hasReadWriteCapability(provider) && bufferOrReadableOrStreamOrBufferedStream instanceof VSBuffer) || // data is a full buffer already
415 (hasReadWriteCapability(provider) && hasFileAtomicWriteCapability(provider) && writeFileOptions?.atomic) // atomic write forces unbuffered write if the provider supports it
416 > ) { fileService.ts
417 > await this.doWriteUnbuffered(provider, resource, writeFileOptions, bufferOrReadableOrStreamOrBufferedStream);
418 > }
419
420 // write file: buffered
422 await this.doWriteBuffered(provider, resource, writeFileOptions, bufferOrReadableOrStreamOrBufferedStream instanceof VSBuffer ? bufferToReadable(bufferOrReadableOrStreamOrBufferedStream) : bufferOrReadableOrStreamOrBufferedStream);
423 }
425 > // events
426 > this._onDidRunOperation.fire(new FileOperationEvent(resource, FileOperation.WRITE));
427 > } catch (error) {
428 throw new FileOperationError(localize('err.write', "Unable to write file '{0}' ({1})", this.resourceForError(resource), ensureFileSystemProviderError(error).toString()), toFileOperationResult(error), writeFileOptions);
429 }
431 > return this.resolve(resource, { resolveMetadata: true });
432 > }
434 >
435 > private async peekBufferForWriting(provider: IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithOpenReadWriteCloseCapability, bufferOrReadableOrStream: VSBuffer | VSBufferReadable | VSBufferReadableStream): Promise<VSBuffer | VSBufferReadable | VSBufferReadableStream | VSBufferReadableBufferedStream> {
436 > let peekResult: VSBuffer | VSBufferReadable | VSBufferReadableStream | VSBufferReadableBufferedStream; fileService.ts
437 > if (hasReadWriteCapability(provider) && !(bufferOrReadableOrStream instanceof VSBuffer)) {
438 if (isReadableStream(bufferOrReadableOrStream)) {
439 const bufferedStream = await peekStream(bufferOrReadableOrStream, 3);
446 peekResult = peekReadable(bufferOrReadableOrStream, data => VSBuffer.concat(data), 3);
447 }
448 > } else { fileService.ts
449 > peekResult = bufferOrReadableOrStream;
450 > }
451 >
452 > return peekResult;
453 > }
455 > private async validateWriteFile(provider: IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithOpenReadWriteCloseCapability, resource: URI, bufferOrReadableOrStream: VSBuffer | VSBufferReadable | VSBufferReadableStream, options?: IWriteFileOptions): Promise<{ stat: IStat | undefined; buffer: VSBuffer | VSBufferReadable | VSBufferReadableStream | VSBufferReadableBufferedStream | undefined }> {
457 > // Validate unlock support
458 > const unlock = !!options?.unlock;
459 > if (unlock && !(provider.capabilities & FileSystemProviderCapabilities.FileWriteUnlock)) {
460 throw new Error(localize('writeFailedUnlockUnsupported', "Unable to unlock file '{0}' because provider does not support it.", this.resourceForError(resource)));
461 }
463 > // Validate append support
464 > if (options?.append && !hasFileAppendCapability(provider)) {
465 throw new FileOperationError(localize('err.noAppend', "Filesystem provider for scheme '{0}' does not does not support append", this.resourceForError(resource)), FileOperationResult.FILE_PERMISSION_DENIED);
466 }
468 > // Validate atomic support
469 > const atomic = !!options?.atomic;
470 > if (atomic) {
471 if (!(provider.capabilities & FileSystemProviderCapabilities.FileAtomicWrite)) {
472 throw new Error(localize('writeFailedAtomicUnsupported1', "Unable to atomically write file '{0}' because provider does not support it.", this.resourceForError(resource)));
481 }
482 }
484 > // Validate via file stat meta data
485 > let stat: IStat | undefined = undefined;
486 > try {
487 > stat = await provider.stat(resource);
488 > } catch (error) {
489 > return Object.create(null); // file might not exist fileService.ts
490 > }
491
492 // File cannot be directory
516 let buffer: VSBuffer | VSBufferReadable | VSBufferReadableStream | VSBufferReadableBufferedStream | undefined;
517 if (
518 > typeof options?.mtime === 'number' && typeof options.etag === 'string' && options.etag !== ETAG_DISABLED && fileService.ts
519 > typeof stat.mtime === 'number' && typeof stat.size === 'number' &&
520 > options.mtime < stat.mtime && options.etag !== etag({ mtime: options.mtime /* not using stat.mtime for a reason, see above */, size: stat.size })
521 > ) {
522 buffer = await this.peekBufferForWriting(provider, bufferOrReadableOrStream);
523 if (buffer instanceof VSBuffer && buffer.byteLength === stat.size) {
536
537 return { stat, buffer };
538 > } fileService.ts
540 > async readFile(resource: URI, options?: IReadFileOptions, token?: CancellationToken): Promise<IFileContent> {
541 > const provider = await this.withReadProvider(resource); fileService.ts
542 >
543 > if (options?.atomic) {
544 return this.doReadFileAtomic(provider, resource, options, token);
545 }
547 > return this.doReadFile(provider, resource, options, token);
548 > }
550 > private async doReadFileAtomic(provider: IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithOpenReadWriteCloseCapability | IFileSystemProviderWithFileReadStreamCapability, resource: URI, options?: IReadFileOptions, token?: CancellationToken): Promise<IFileContent> {
551 return new Promise<IFileContent>((resolve, reject) => {
552 this.writeQueue.queueFor(resource, async () => {
560 });
561 }
563 > private async doReadFile(provider: IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithOpenReadWriteCloseCapability | IFileSystemProviderWithFileReadStreamCapability, resource: URI, options?: IReadFileOptions, token?: CancellationToken): Promise<IFileContent> {
564 > const stream = await this.doReadFileStream(provider, resource, { fileService.ts
565 > ...options,
566 > // optimization: since we know that the caller does not
567 > // care about buffering, we indicate this to the reader.
568 > // this reduces all the overhead the buffered reading
569 > // has (open, read, close) if the provider supports
570 > // unbuffered reading.
571 > preferUnbuffered: true
572 > }, token);
574 > return {
575 > ...stream,
576 > value: await streamToBuffer(stream.value)
577 > };
578 > } fileService.ts
580 > async readFileStream(resource: URI, options?: IReadFileStreamOptions, token?: CancellationToken): Promise<IFileStreamContent> {
581 const provider = await this.withReadProvider(resource);
582
583 return this.doReadFileStream(provider, resource, options, token);
584 }
586 > private async doReadFileStream(provider: IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithOpenReadWriteCloseCapability | IFileSystemProviderWithFileReadStreamCapability, resource: URI, options?: IReadFileOptions & IReadFileStreamOptions & { preferUnbuffered?: boolean }, token?: CancellationToken): Promise<IFileStreamContent> {
588 > // install a cancellation token that gets cancelled
589 > // when any error occurs. this allows us to resolve
590 > // the content of the file while resolving metadata
591 > // but still cancel the operation in certain cases.
592 > //
593 > // in addition, we pass the optional token in that
594 > // we got from the outside to even allow for external
595 > // cancellation of the read operation.
596 > const cancellableSource = new CancellationTokenSource(token);
597 >
598 > let readFileOptions = options;
599 > if (hasFileAtomicReadCapability(provider) && provider.enforceAtomicReadFile?.(resource)) {
600 readFileOptions = { ...options, atomic: true };
601 }
603 > // validate read operation
604 > const statPromise = this.validateReadFile(resource, readFileOptions).then(stat => stat, error => {
605 > cancellableSource.dispose(true); fileService.ts
606 >
607 > throw error;
608 > }); fileService.ts
609 >
610 > let fileStream: VSBufferReadableStream | undefined = undefined;
611 > try {
612 >
613 > // if the etag is provided, we await the result of the validation
614 > // due to the likelihood of hitting a NOT_MODIFIED_SINCE result.
615 > // otherwise, we let it run in parallel to the file reading for
616 > // optimal startup performance.
617 > if (typeof readFileOptions?.etag === 'string' && readFileOptions.etag !== ETAG_DISABLED) {
618 await statPromise;
619 }
621 > // read unbuffered
622 > if (
623 > (readFileOptions?.atomic && hasFileAtomicReadCapability(provider)) || // atomic reads are always unbuffered
624 > !(hasOpenReadWriteCloseCapability(provider) || hasFileReadStreamCapability(provider)) || // provider has no buffered capability
625 > (hasReadWriteCapability(provider) && readFileOptions?.preferUnbuffered) // unbuffered read is preferred
626 > ) {
627 > fileStream = this.readFileUnbuffered(provider, resource, readFileOptions); fileService.ts
628 > }
629
630 // read streamed (always prefer over primitive buffered read)
637 fileStream = this.readFileBuffered(provider, resource, cancellableSource.token, readFileOptions);
638 }
640 > fileStream.on('end', () => cancellableSource.dispose());
641 > fileStream.on('error', () => cancellableSource.dispose());
642 >
643 > const fileStat = await statPromise;
645 > return {
646 > ...fileStat,
647 > value: fileStream
648 > };
649 > } catch (error) { fileService.ts
651 > // Await the stream to finish so that we exit this method
652 > // in a consistent state with file handles closed
653 > // (https://github.com/microsoft/vscode/issues/114024)
654 > if (fileStream) {
655 > await consumeStream(fileStream);
656 > }
657 >
658 > // Re-throw errors as file operation errors but preserve
659 > // specific errors (such as not modified since)
660 > throw this.restoreReadError(error, resource, readFileOptions);
661 > }
662 > } fileService.ts
664 > private restoreReadError(error: Error, resource: URI, options?: IReadFileStreamOptions): FileOperationError {
665 > const message = localize('err.read', "Unable to read file '{0}' ({1})", this.resourceForError(resource), ensureFileSystemProviderError(error).toString()); fileService.ts
666 >
667 > if (error instanceof NotModifiedSinceFileOperationError) {
668 return new NotModifiedSinceFileOperationError(message, error.stat, options);
669 }
671 > if (error instanceof TooLargeFileOperationError) {
672 return new TooLargeFileOperationError(message, error.fileOperationResult, error.size, error.options as IReadFileOptions);
673 }
675 > return new FileOperationError(message, toFileOperationResult(error), options);
676 > }
678 > private readFileStreamed(provider: IFileSystemProviderWithFileReadStreamCapability, resource: URI, token: CancellationToken, options: IReadFileStreamOptions = Object.create(null)): VSBufferReadableStream {
679 const fileStream = provider.readFileStream(resource, options, token);
680
684 }, data => VSBuffer.concat(data));
685 }
687 > private readFileBuffered(provider: IFileSystemProviderWithOpenReadWriteCloseCapability, resource: URI, token: CancellationToken, options: IReadFileStreamOptions = Object.create(null)): VSBufferReadableStream {
688 const stream = newWriteableBufferStream();
689
696 return stream;
697 }
699 > private readFileUnbuffered(provider: IFileSystemProviderWithFileReadWriteCapability | IFileSystemProviderWithFileAtomicReadCapability, resource: URI, options?: IReadFileOptions & IReadFileStreamOptions): VSBufferReadableStream {
700 > const stream = newWriteableStream<VSBuffer>(data => VSBuffer.concat(data)); fileService.ts
701 >
702 > // Read the file into the stream async but do not wait for
703 > // this to complete because streams work via events
704 > (async () => {
705 > try {
706 > let buffer: Uint8Array;
707 > if (options?.atomic && hasFileAtomicReadCapability(provider)) {
708 buffer = await provider.readFile(resource, { atomic: true });
709 > } else { fileService.ts
710 > buffer = await provider.readFile(resource);
711 > } fileService.ts
712 >
713 > // respect position option
714 > if (typeof options?.position === 'number') { fileService.ts
715 buffer = buffer.slice(options.position);
716 }
718 > // respect length option
719 > if (typeof options?.length === 'number') { fileService.ts
720 buffer = buffer.slice(0, options.length);
721 }
723 > // Throw if file is too large to load
724 > this.validateReadFileLimits(resource, buffer.byteLength, options);
725 >
726 > // End stream with data
727 > stream.end(VSBuffer.wrap(buffer));
728 > } catch (err) { fileService.ts
729 > stream.error(err); fileService.ts
730 > stream.end();
731 > }
732 > })(); fileService.ts
733 >
734 > return stream;
735 > }
737 > private async validateReadFile(resource: URI, options?: IReadFileStreamOptions): Promise<IFileStatWithMetadata> {
738 > const stat = await this.resolve(resource, { resolveMetadata: true }); fileService.ts
740 > // Throw if resource is a directory
741 > if (stat.isDirectory) {
742 throw new FileOperationError(localize('fileIsDirectoryReadError', "Unable to read file '{0}' that is actually a directory", this.resourceForError(resource)), FileOperationResult.FILE_IS_DIRECTORY, options);
743 }
745 > // Throw if file not modified since (unless disabled)
746 > if (typeof options?.etag === 'string' && options.etag !== ETAG_DISABLED && options.etag === stat.etag) { fileService.ts
747 throw new NotModifiedSinceFileOperationError(localize('fileNotModifiedError', "File not modified since"), stat, options);
748 }
750 > // Throw if file is too large to load
751 > this.validateReadFileLimits(resource, stat.size, options);
752 >
753 > return stat;
754 > } fileService.ts
756 > private validateReadFileLimits(resource: URI, size: number, options?: IReadFileStreamOptions): void {
757 > if (typeof options?.limits?.size === 'number' && size > options.limits.size) { fileService.ts
758 throw new TooLargeFileOperationError(localize('fileTooLargeError', "Unable to read file '{0}' that is too large to open", this.resourceForError(resource)), FileOperationResult.FILE_TOO_LARGE, size, options);
759 }
760 > } fileService.ts
762 > //#endregion
763 >
764 > //#region Move/Copy/Delete/Create Folder
765 >
766 > async canMove(source: URI, target: URI, overwrite?: boolean): Promise<Error | true> {
767 return this.doCanMoveCopy(source, target, 'move', overwrite);
768 }
770 > async canCopy(source: URI, target: URI, overwrite?: boolean): Promise<Error | true> {
771 return this.doCanMoveCopy(source, target, 'copy', overwrite);
772 }
774 > private async doCanMoveCopy(source: URI, target: URI, mode: 'move' | 'copy', overwrite?: boolean): Promise<Error | true> {
775 if (source.toString() !== target.toString()) {
776 try {
786 return true;
787 }
789 > async move(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {
790 const sourceProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(source), source);
791 const targetProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(target), target);
800 return fileStat;
801 }
803 > async copy(source: URI, target: URI, overwrite?: boolean): Promise<IFileStatWithMetadata> {
804 const sourceProvider = await this.withReadProvider(source);
805 const targetProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(target), target);
814 return fileStat;
815 }
817 > private async doMoveCopy(sourceProvider: IFileSystemProvider, source: URI, targetProvider: IFileSystemProvider, target: URI, mode: 'move' | 'copy', overwrite: boolean): Promise<'move' | 'copy'> {
818 if (source.toString() === target.toString()) {
819 return mode; // simulate node.js behaviour here and do a no-op if paths match
872 }
873 }
875 > private async doCopyFile(sourceProvider: IFileSystemProvider, source: URI, targetProvider: IFileSystemProvider, target: URI): Promise<void> {
876
877 // copy: source (buffered) => target (buffered)
895 }
896 }
898 > private async doCopyFolder(sourceProvider: IFileSystemProvider, sourceFolder: IFileStat, targetProvider: IFileSystemProvider, targetFolder: URI): Promise<void> {
899
900 // create folder in target
913 }
914 }
916 > private async doValidateMoveCopy(sourceProvider: IFileSystemProvider, source: URI, targetProvider: IFileSystemProvider, target: URI, mode: 'move' | 'copy', overwrite?: boolean): Promise<{ exists: boolean; isSameResourceWithDifferentPathCase: boolean }> {
917 let isSameResourceWithDifferentPathCase = false;
918
954 return { exists, isSameResourceWithDifferentPathCase };
955 }
957 > private getExtUri(provider: IFileSystemProvider): { providerExtUri: IExtUri; isPathCaseSensitive: boolean } {
958 > const isPathCaseSensitive = this.isPathCaseSensitive(provider); fileService.ts
959 >
960 > return {
961 > providerExtUri: isPathCaseSensitive ? extUri : extUriIgnorePathCase,
962 > isPathCaseSensitive
963 > };
964 > }
966 > private isPathCaseSensitive(provider: IFileSystemProvider): boolean {
967 > return !!(provider.capabilities & FileSystemProviderCapabilities.PathCaseSensitive); fileService.ts
968 > }
970 > async createFolder(resource: URI): Promise<IFileStatWithMetadata> {
971 const provider = this.throwIfFileSystemIsReadonly(await this.withProvider(resource), resource);
972
980 return fileStat;
981 }
983 > private async mkdirp(provider: IFileSystemProvider, directory: URI): Promise<void> {
984 > const directoriesToCreate: string[] = []; fileService.ts
985 >
986 > // mkdir until we reach root
987 > const { providerExtUri } = this.getExtUri(provider);
988 > while (!providerExtUri.isEqual(directory, providerExtUri.dirname(directory))) {
989 > try { fileService.ts
990 > const stat = await provider.stat(directory);
991 > if ((stat.type & FileType.Directory) === 0) { fileService.ts
992 throw new Error(localize('mkdirExistsError', "Unable to create folder '{0}' that already exists but is not a directory", this.resourceForError(directory)));
993 }
995 > break; // we have hit a directory that exists -> good
996 > } catch (error) { fileService.ts
997 >
998 > // Bubble up any other error that is not file not found
999 > if (toFileSystemProviderErrorCode(error) !== FileSystemProviderErrorCode.FileNotFound) {
1000 throw error;
1001 }
1003 > // Upon error, remember directories that need to be created
1004 > directoriesToCreate.push(providerExtUri.basename(directory));
1005 >
1006 > // Continue up
1007 > directory = providerExtUri.dirname(directory);
1008 > }
1009 > }
1011 > // Create directories as needed
1012 > for (let i = directoriesToCreate.length - 1; i >= 0; i--) {
1013 > directory = providerExtUri.joinPath(directory, directoriesToCreate[i]); fileService.ts
1014 >
1015 > try {
1016 > await provider.mkdir(directory);
1017 > } catch (error) {
1018 if (toFileSystemProviderErrorCode(error) !== FileSystemProviderErrorCode.FileExists) {
1019 // For mkdirp() we tolerate that the mkdir() call fails
1028 }
1029 }
1030 > } fileService.ts
1031 > } fileService.ts
1033 > async canDelete(resource: URI, options?: Partial<IFileDeleteOptions>): Promise<Error | true> {
1034 try {
1035 await this.doValidateDelete(resource, options);
1040 return true;
1041 }
1043 > private async doValidateDelete(resource: URI, options?: Partial<IFileDeleteOptions>): Promise<IFileSystemProvider> {
1044 > const provider = this.throwIfFileSystemIsReadonly(await this.withProvider(resource), resource); fileService.ts
1045 >
1046 > // Validate trash support
1047 > const useTrash = !!options?.useTrash;
1048 > if (useTrash && !(provider.capabilities & FileSystemProviderCapabilities.Trash)) {
1049 throw new Error(localize('deleteFailedTrashUnsupported', "Unable to delete file '{0}' via trash because provider does not support it.", this.resourceForError(resource)));
1050 }
1052 > // Validate atomic support
1053 > const atomic = options?.atomic;
1054 > if (atomic && !(provider.capabilities & FileSystemProviderCapabilities.FileAtomicDelete)) {
1055 throw new Error(localize('deleteFailedAtomicUnsupported', "Unable to delete file '{0}' atomically because provider does not support it.", this.resourceForError(resource)));
1056 }
1058 > if (useTrash && atomic) {
1059 throw new Error(localize('deleteFailedTrashAndAtomicUnsupported', "Unable to atomically delete file '{0}' because using trash is enabled.", this.resourceForError(resource)));
1060 }
1062 > // Validate delete
1063 > let stat: IStat | undefined = undefined;
1064 > try {
1065 > stat = await provider.stat(resource);
1066 > } catch (error) {
1067 > // Handled later fileService.ts
1068 > }
1070 > if (stat) {
1071 > this.throwIfFileIsReadonly(resource, stat); fileService.ts
1072 > } else { fileService.ts
1073 > throw new FileOperationError(localize('deleteFailedNotFound', "Unable to delete nonexistent file '{0}'", this.resourceForError(resource)), FileOperationResult.FILE_NOT_FOUND); fileService.ts
1074 > }
1076 > // Validate recursive
1077 > const recursive = !!options?.recursive;
1078 > if (!recursive) { fileService.ts
1079 > const stat = await this.resolve(resource); fileService.ts
1080 > if (stat.isDirectory && Array.isArray(stat.children) && stat.children.length > 0) {
1081 throw new Error(localize('deleteFailedNonEmptyFolder', "Unable to delete non-empty folder '{0}'.", this.resourceForError(resource)));
1082 }
1083 > } fileService.ts
1085 > return provider;
1086 > } fileService.ts
1088 > async del(resource: URI, options?: Partial<IFileDeleteOptions>): Promise<void> {
1089 > const provider = await this.doValidateDelete(resource, options); fileService.ts
1091 > let deleteFileOptions = options;
1092 > if (hasFileAtomicDeleteCapability(provider) && !deleteFileOptions?.atomic) { fileService.ts
1093 const enforcedAtomicDelete = provider.enforceAtomicDelete?.(resource);
1094 if (enforcedAtomicDelete) {
1096 }
1097 }
1099 > const useTrash = !!deleteFileOptions?.useTrash;
1100 > const recursive = !!deleteFileOptions?.recursive; fileService.ts
1101 > const atomic = deleteFileOptions?.atomic ?? false;
1102 >
1103 > // Delete through provider
1104 > await provider.delete(resource, { recursive, useTrash, atomic });
1106 > // Events
1107 > this._onDidRunOperation.fire(new FileOperationEvent(resource, FileOperation.DELETE));
1108 > } fileService.ts
1110 > //#endregion
1111 >
1112 > //#region Clone File
1113 >
1114 > async cloneFile(source: URI, target: URI): Promise<void> {
1115 const sourceProvider = await this.withProvider(source);
1116 const targetProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(target), target);
1142 return this.writeQueue.queueFor(source, () => this.doCopyFile(sourceProvider, source, targetProvider, target), this.getExtUri(sourceProvider).providerExtUri);
1143 }
1145 > //#endregion
1146 >
1147 > //#region File Watching
1148 >
1149 > private readonly internalOnDidFilesChange = this._register(new Emitter<FileChangesEvent>());
1150 >
1151 > private readonly _onDidUncorrelatedFilesChange = this._register(new Emitter<FileChangesEvent>());
1152 > readonly onDidFilesChange = this._onDidUncorrelatedFilesChange.event; // global `onDidFilesChange` skips correlated events
1153 >
1154 > private readonly _onDidWatchError = this._register(new Emitter<Error>());
1155 > readonly onDidWatchError = this._onDidWatchError.event;
1156 >
1157 > private readonly activeWatchers = new Map<number /* watch request hash */, { disposable: IDisposable; count: number }>();
1158 >
1159 > private static WATCHER_CORRELATION_IDS = 0;
1160 >
1161 > createWatcher(resource: URI, options: IWatchOptionsWithoutCorrelation & { recursive: false }): IFileSystemWatcher {
1162 return this.watch(resource, {
1163 ...options,
1168 });
1169 }
1171 > watch(resource: URI, options: IWatchOptionsWithCorrelation): IFileSystemWatcher;
1172 > watch(resource: URI, options?: IWatchOptionsWithoutCorrelation): IDisposable;
1173 > watch(resource: URI, options: IWatchOptions = { recursive: false, excludes: [] }): IFileSystemWatcher | IDisposable {
1174 > const disposables = new DisposableStore(); fileService.ts
1175 >
1176 > // Forward watch request to provider and wire in disposables
1177 > let watchDisposed = false;
1178 > let disposeWatch = () => { watchDisposed = true; };
1179 > disposables.add(toDisposable(() => disposeWatch()));
1180 >
1181 > // Watch and wire in disposable which is async but
1182 > // check if we got disposed meanwhile and forward
1183 > (async () => {
1184 > try {
1185 > const disposable = await this.doWatch(resource, options);
1186 > if (watchDisposed) { fileService.ts
1187 dispose(disposable);
1188 > } else { fileService.ts
1189 > disposeWatch = () => dispose(disposable); fileService.ts
1190 > }
1191 > } catch (error) { fileService.ts
1192 this.logService.error(error);
1193 }
1194 > })(); fileService.ts
1195 >
1196 > // When a correlation identifier is set, return a specific
1197 > // watcher that only emits events matching that correalation.
1198 > const correlationId = options.correlationId;
1199 > if (typeof correlationId === 'number') {
1200 const fileChangeEmitter = disposables.add(new Emitter<FileChangesEvent>());
1201 disposables.add(this.internalOnDidFilesChange.event(e => {
1212 return watcher;
1213 }
1215 > return disposables;
1216 > } fileService.ts
1218 > private async doWatch(resource: URI, options: IWatchOptions): Promise<IDisposable> {
1219 > const provider = await this.withProvider(resource); fileService.ts
1221 > // Deduplicate identical watch requests
1222 > const watchHash = hash([this.getExtUri(provider).providerExtUri.getComparisonKey(resource), options]);
1223 > let watcher = this.activeWatchers.get(watchHash);
1224 > if (!watcher) {
1225 > watcher = {
1226 > count: 0,
1227 > disposable: provider.watch(resource, options)
1228 > };
1229 >
1230 > this.activeWatchers.set(watchHash, watcher);
1231 > }
1232 >
1233 > // Increment usage counter
1234 > watcher.count += 1;
1235 >
1236 > return toDisposable(() => {
1237 > if (watcher) {
1238 >
1239 > // Unref
1240 > watcher.count--;
1241 >
1242 > // Dispose only when last user is reached
1243 > if (watcher.count === 0) {
1244 > dispose(watcher.disposable);
1245 > this.activeWatchers.delete(watchHash);
1246 > }
1247 > }
1248 > });
1249 > } fileService.ts
1251 > override dispose(): void {
1252 > super.dispose(); fileService.ts
1253 >
1254 > for (const [, watcher] of this.activeWatchers) {
1255 > dispose(watcher.disposable); fileService.ts
1256 > }
1258 > this.activeWatchers.clear();
1259 > }
1261 > //#endregion
1262 >
1263 > //#region Helpers
1264 >
1265 > private readonly writeQueue = this._register(new ResourceQueue());
1267 > private async doWriteBuffered(provider: IFileSystemProviderWithOpenReadWriteCloseCapability, resource: URI, options: IWriteFileOptions | undefined, readableOrStreamOrBufferedStream: VSBufferReadable | VSBufferReadableStream | VSBufferReadableBufferedStream): Promise<void> {
1268 return this.writeQueue.queueFor(resource, async () => {
1269
1287 }, this.getExtUri(provider).providerExtUri);
1288 }
1290 > private async doWriteStreamBufferedQueued(provider: IFileSystemProviderWithOpenReadWriteCloseCapability, handle: number, streamOrBufferedStream: VSBufferReadableStream | VSBufferReadableBufferedStream): Promise<void> {
1291 let posInFile = 0;
1292 let stream: VSBufferReadableStream;
1341 });
1342 }
1344 > private async doWriteReadableBufferedQueued(provider: IFileSystemProviderWithOpenReadWriteCloseCapability, handle: number, readable: VSBufferReadable): Promise<void> {
1345 let posInFile = 0;
1346
1352 }
1353 }
1355 > private async doWriteBuffer(provider: IFileSystemProviderWithOpenReadWriteCloseCapability, handle: number, buffer: VSBuffer, length: number, posInFile: number, posInBuffer: number): Promise<void> {
1356 let totalBytesWritten = 0;
1357 while (totalBytesWritten < length) {
1362 }
1363 }
1365 > private async doWriteUnbuffered(provider: IFileSystemProviderWithFileReadWriteCapability, resource: URI, options: IWriteFileOptions | undefined, bufferOrReadableOrStreamOrBufferedStream: VSBuffer | VSBufferReadable | VSBufferReadableStream | VSBufferReadableBufferedStream): Promise<void> {
1366 > return this.writeQueue.queueFor(resource, () => this.doWriteUnbufferedQueued(provider, resource, options, bufferOrReadableOrStreamOrBufferedStream), this.getExtUri(provider).providerExtUri); fileService.ts
1367 > }
1369 > private async doWriteUnbufferedQueued(provider: IFileSystemProviderWithFileReadWriteCapability, resource: URI, options: IWriteFileOptions | undefined, bufferOrReadableOrStreamOrBufferedStream: VSBuffer | VSBufferReadable | VSBufferReadableStream | VSBufferReadableBufferedStream): Promise<void> {
1370 > let buffer: VSBuffer; fileService.ts
1371 > if (bufferOrReadableOrStreamOrBufferedStream instanceof VSBuffer) {
1372 > buffer = bufferOrReadableOrStreamOrBufferedStream;
1373 > } else if (isReadableStream(bufferOrReadableOrStreamOrBufferedStream)) {
1374 buffer = await streamToBuffer(bufferOrReadableOrStreamOrBufferedStream);
1375 } else if (isReadableBufferedStream(bufferOrReadableOrStreamOrBufferedStream)) {
1378 buffer = readableToBuffer(bufferOrReadableOrStreamOrBufferedStream);
1379 }
1381 > // Write through the provider
1382 > await provider.writeFile(resource, buffer.buffer, { create: true, overwrite: true, unlock: options?.unlock ?? false, atomic: options?.atomic ?? false, append: options?.append ?? false });
1383 > }
1385 > private async doPipeBuffered(sourceProvider: IFileSystemProviderWithOpenReadWriteCloseCapability, source: URI, targetProvider: IFileSystemProviderWithOpenReadWriteCloseCapability, target: URI): Promise<void> {
1386 return this.writeQueue.queueFor(target, () => this.doPipeBufferedQueued(sourceProvider, source, targetProvider, target), this.getExtUri(targetProvider).providerExtUri);
1387 }
1389 > private async doPipeBufferedQueued(sourceProvider: IFileSystemProviderWithOpenReadWriteCloseCapability, source: URI, targetProvider: IFileSystemProviderWithOpenReadWriteCloseCapability, target: URI): Promise<void> {
1390 let sourceHandle: number | undefined = undefined;
1391 let targetHandle: number | undefined = undefined;
1428 }
1429 }
1431 > private async doPipeUnbuffered(sourceProvider: IFileSystemProviderWithFileReadWriteCapability, source: URI, targetProvider: IFileSystemProviderWithFileReadWriteCapability, target: URI): Promise<void> {
1432 return this.writeQueue.queueFor(target, () => this.doPipeUnbufferedQueued(sourceProvider, source, targetProvider, target), this.getExtUri(targetProvider).providerExtUri);
1433 }
1435 > private async doPipeUnbufferedQueued(sourceProvider: IFileSystemProviderWithFileReadWriteCapability, source: URI, targetProvider: IFileSystemProviderWithFileReadWriteCapability, target: URI): Promise<void> {
1436 return targetProvider.writeFile(target, await sourceProvider.readFile(source), { create: true, overwrite: true, unlock: false, atomic: false });
1437 }
1439 > private async doPipeUnbufferedToBuffered(sourceProvider: IFileSystemProviderWithFileReadWriteCapability, source: URI, targetProvider: IFileSystemProviderWithOpenReadWriteCloseCapability, target: URI): Promise<void> {
1440 return this.writeQueue.queueFor(target, () => this.doPipeUnbufferedToBufferedQueued(sourceProvider, source, targetProvider, target), this.getExtUri(targetProvider).providerExtUri);
1441 }
1443 > private async doPipeUnbufferedToBufferedQueued(sourceProvider: IFileSystemProviderWithFileReadWriteCapability, source: URI, targetProvider: IFileSystemProviderWithOpenReadWriteCloseCapability, target: URI): Promise<void> {
1444
1445 // Open handle
1456 }
1457 }
1459 > private async doPipeBufferedToUnbuffered(sourceProvider: IFileSystemProviderWithOpenReadWriteCloseCapability, source: URI, targetProvider: IFileSystemProviderWithFileReadWriteCapability, target: URI): Promise<void> {
1460
1461 // Read buffer via stream buffered
1465 await this.doWriteUnbuffered(targetProvider, target, undefined, buffer);
1466 }
1468 > protected throwIfFileSystemIsReadonly<T extends IFileSystemProvider>(provider: T, resource: URI): T {
1469 > if (provider.capabilities & FileSystemProviderCapabilities.Readonly) { fileService.ts
1470 throw new FileOperationError(localize('err.readonly', "Unable to modify read-only file '{0}'", this.resourceForError(resource)), FileOperationResult.FILE_PERMISSION_DENIED);
1471 }
1473 > return provider;
1474 > }
1476 > private throwIfFileIsReadonly(resource: URI, stat: IStat): void {
1477 > if ((stat.permissions ?? 0) & FilePermission.Readonly) { fileService.ts
1478 throw new FileOperationError(localize('err.readonly', "Unable to modify read-only file '{0}'", this.resourceForError(resource)), FileOperationResult.FILE_PERMISSION_DENIED);
1479 }
1480 > } fileService.ts
1482 > private resourceForError(resource: URI): string {
1483 > if (resource.scheme === Schemas.file) { fileService.ts
1484 return resource.fsPath;
1485 }
1487 > return resource.toString(true);
1488 > } fileService.ts
1490 > //#endregion
1491 > }
src/vs/base/common/json.ts 738 covered LOC · 135 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- json.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export const enum ScanError {
7 > None = 0,
8 > UnexpectedEndOfComment = 1,
9 > UnexpectedEndOfString = 2,
10 > UnexpectedEndOfNumber = 3,
11 > InvalidUnicode = 4,
12 > InvalidEscapeCharacter = 5,
13 > InvalidCharacter = 6
14 > }
15 >
16 > export const enum SyntaxKind {
17 > OpenBraceToken = 1,
18 > CloseBraceToken = 2,
19 > OpenBracketToken = 3,
20 > CloseBracketToken = 4,
21 > CommaToken = 5,
22 > ColonToken = 6,
23 > NullKeyword = 7,
24 > TrueKeyword = 8,
25 > FalseKeyword = 9,
26 > StringLiteral = 10,
27 > NumericLiteral = 11,
28 > LineCommentTrivia = 12,
29 > BlockCommentTrivia = 13,
30 > LineBreakTrivia = 14,
31 > Trivia = 15,
32 > Unknown = 16,
33 > EOF = 17
34 > }
35 >
36 > /**
37 > * The scanner object, representing a JSON scanner at a position in the input string.
38 > */
39 > export interface JSONScanner {
40 > /**
41 > * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
42 > */
43 > setPosition(pos: number): void;
44 > /**
45 > * Read the next token. Returns the token code.
46 > */
47 > scan(): SyntaxKind;
48 > /**
49 > * Returns the current scan position, which is after the last read token.
50 > */
51 > getPosition(): number;
52 > /**
53 > * Returns the last read token.
54 > */
55 > getToken(): SyntaxKind;
56 > /**
57 > * Returns the last read token value. The value for strings is the decoded string content. For numbers its of type number, for boolean it's true or false.
58 > */
59 > getTokenValue(): string;
60 > /**
61 > * The start offset of the last read token.
62 > */
63 > getTokenOffset(): number;
64 > /**
65 > * The length of the last read token.
66 > */
67 > getTokenLength(): number;
68 > /**
69 > * An error code of the last scan.
70 > */
71 > getTokenError(): ScanError;
72 > }
73 >
74 >
75 >
76 > export interface ParseError {
77 > error: ParseErrorCode;
78 > offset: number;
79 > length: number;
80 > }
81 >
82 > export const enum ParseErrorCode {
83 > InvalidSymbol = 1,
84 > InvalidNumberFormat = 2,
85 > PropertyNameExpected = 3,
86 > ValueExpected = 4,
87 > ColonExpected = 5,
88 > CommaExpected = 6,
89 > CloseBraceExpected = 7,
90 > CloseBracketExpected = 8,
91 > EndOfFileExpected = 9,
92 > InvalidCommentToken = 10,
93 > UnexpectedEndOfComment = 11,
94 > UnexpectedEndOfString = 12,
95 > UnexpectedEndOfNumber = 13,
96 > InvalidUnicode = 14,
97 > InvalidEscapeCharacter = 15,
98 > InvalidCharacter = 16
99 > }
100 >
101 > export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null';
102 >
103 > export interface Node {
104 > readonly type: NodeType;
105 > readonly value?: any;
106 > readonly offset: number;
107 > readonly length: number;
108 > readonly colonOffset?: number;
109 > readonly parent?: Node;
110 > readonly children?: Node[];
111 > }
112 >
113 > export type Segment = string | number;
114 > export type JSONPath = Segment[];
115 >
116 > export interface Location {
117 > /**
118 > * The previous property key or literal value (string, number, boolean or null) or undefined.
119 > */
120 > previousNode?: Node;
121 > /**
122 > * The path describing the location in the JSON document. The path consists of a sequence strings
123 > * representing an object property or numbers for array indices.
124 > */
125 > path: JSONPath;
126 > /**
127 > * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
128 > * '*' will match a single segment, of any property name or index.
129 > * '**' will match a sequence of segments or no segment, of any property name or index.
130 > */
131 > matches: (patterns: JSONPath) => boolean;
132 > /**
133 > * If set, the location's offset is at a property key.
134 > */
135 > isAtPropertyKey: boolean;
136 > }
137 >
138 > export interface ParseOptions {
139 > disallowComments?: boolean;
140 > allowTrailingComma?: boolean;
141 > allowEmptyContent?: boolean;
142 > }
143 >
144 > export namespace ParseOptions {
145 > export const DEFAULT = {
146 > allowTrailingComma: true
147 > };
148 > }
149 >
150 > export interface JSONVisitor {
151 > /**
152 > * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
153 > */
154 > onObjectBegin?: (offset: number, length: number) => void;
155 >
156 > /**
157 > * Invoked when a property is encountered. The offset and length represent the location of the property name.
158 > */
159 > onObjectProperty?: (property: string, offset: number, length: number) => void;
160 >
161 > /**
162 > * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
163 > */
164 > onObjectEnd?: (offset: number, length: number) => void;
165 >
166 > /**
167 > * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
168 > */
169 > onArrayBegin?: (offset: number, length: number) => void;
170 >
171 > /**
172 > * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
173 > */
174 > onArrayEnd?: (offset: number, length: number) => void;
175 >
176 > /**
177 > * Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
178 > */
179 > onLiteralValue?: (value: any, offset: number, length: number) => void;
180 >
181 > /**
182 > * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
183 > */
184 > onSeparator?: (character: string, offset: number, length: number) => void;
185 >
186 > /**
187 > * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
188 > */
189 > onComment?: (offset: number, length: number) => void;
190 >
191 > /**
192 > * Invoked on an error.
193 > */
194 > onError?: (error: ParseErrorCode, offset: number, length: number) => void;
195 > }
196 >
197 > /**
198 > * Creates a JSON scanner on the given text.
199 > * If ignoreTrivia is set, whitespaces or comments are ignored.
200 > */
201 > export function createScanner(text: string, ignoreTrivia: boolean = false): JSONScanner {
202 > json.ts
203 > let pos = 0;
204 > const len = text.length;
205 > let value: string = '';
206 > let tokenOffset = 0;
207 > let token: SyntaxKind = SyntaxKind.Unknown;
208 > let scanError: ScanError = ScanError.None;
209 >
210 > function scanHexDigits(count: number): number {
211 let digits = 0;
212 let hexValue = 0;
233 return hexValue;
234 }
235 > json.ts
236 > function setPosition(newPosition: number) {
237 pos = newPosition;
238 value = '';
241 scanError = ScanError.None;
242 }
243 > json.ts
244 > function scanNumber(): string {
245 const start = pos;
246 if (text.charCodeAt(pos) === CharacterCodes._0) {
282 return text.substring(start, end);
283 }
284 > json.ts
285 > function scanString(): string {
286 > json.ts
287 > let result = '',
288 > start = pos;
289 >
290 > while (true) {
291 > if (pos >= len) {
292 result += text.substring(start, pos);
293 scanError = ScanError.UnexpectedEndOfString;
294 break;
295 }
296 > const ch = text.charCodeAt(pos); json.ts
297 > if (ch === CharacterCodes.doubleQuote) {
298 > result += text.substring(start, pos);
299 > pos++;
300 > break;
301 > }
302 > if (ch === CharacterCodes.backslash) { json.ts
303 result += text.substring(start, pos);
304 pos++;
348 continue;
349 }
350 > if (ch >= 0 && ch <= 0x1F) { json.ts
351 if (isLineBreak(ch)) {
352 result += text.substring(start, pos);
358 }
359 }
360 > pos++; json.ts
361 > }
362 > return result; json.ts
363 > }
364 > json.ts
365 > function scanNext(): SyntaxKind {
366 >
367 > value = '';
368 > scanError = ScanError.None;
369 >
370 > tokenOffset = pos;
371 >
372 > if (pos >= len) {
373 > // at the end json.ts
374 > tokenOffset = len;
375 > return token = SyntaxKind.EOF;
376 > }
377 > json.ts
378 > let code = text.charCodeAt(pos);
379 > // trivia: whitespace
380 > if (isWhitespace(code)) {
381 do {
382 pos++;
387 return token = SyntaxKind.Trivia;
388 }
389 > json.ts
390 > // trivia: newlines
391 > if (isLineBreak(code)) {
392 pos++;
393 value += String.fromCharCode(code);
398 return token = SyntaxKind.LineBreakTrivia;
399 }
400 > json.ts
401 > switch (code) {
402 > // tokens: []{}:,
403 > case CharacterCodes.openBrace:
404 > pos++; json.ts
405 > return token = SyntaxKind.OpenBraceToken;
406 > case CharacterCodes.closeBrace: json.ts
407 > pos++; json.ts
408 > return token = SyntaxKind.CloseBraceToken;
409 > case CharacterCodes.openBracket: json.ts
410 > pos++; json.ts
411 > return token = SyntaxKind.OpenBracketToken;
412 > case CharacterCodes.closeBracket: json.ts
413 > pos++; json.ts
414 > return token = SyntaxKind.CloseBracketToken;
415 > case CharacterCodes.colon: json.ts
416 > pos++; json.ts
417 > return token = SyntaxKind.ColonToken;
418 > case CharacterCodes.comma: json.ts
419 pos++;
420 return token = SyntaxKind.CommaToken;
421 > json.ts
422 > // strings
423 > case CharacterCodes.doubleQuote:
424 > pos++; json.ts
425 > value = scanString();
426 > return token = SyntaxKind.StringLiteral;
427 > json.ts
428 > // comments
429 > case CharacterCodes.slash: {
430 const start = pos - 1;
431 // Single-line comment
474 return token = SyntaxKind.Unknown;
475 }
476 > // numbers json.ts
477 > case CharacterCodes.minus:
478 value += String.fromCharCode(code);
479 pos++;
481 return token = SyntaxKind.Unknown;
482 }
483 > // found a minus, followed by a number so json.ts
484 > // we fall through to proceed with scanning
485 > // numbers
486 > case CharacterCodes._0:
487 > case CharacterCodes._1:
488 > case CharacterCodes._2:
489 > case CharacterCodes._3:
490 > case CharacterCodes._4:
491 > case CharacterCodes._5:
492 > case CharacterCodes._6:
493 > case CharacterCodes._7:
494 > case CharacterCodes._8:
495 > case CharacterCodes._9:
496 value += scanNumber();
497 return token = SyntaxKind.NumericLiteral;
498 > // literals and unknown symbols json.ts
499 > default:
500 // is a literal? Read the full word.
501 while (pos < len && isUnknownContentCharacter(code)) {
517 pos++;
518 return token = SyntaxKind.Unknown;
519 > } json.ts
520 > }
521 >
522 > function isUnknownContentCharacter(code: CharacterCodes) {
523 if (isWhitespace(code) || isLineBreak(code)) {
524 return false;
537 return true;
538 }
539 > json.ts
540 >
541 > function scanNextNonTrivia(): SyntaxKind {
542 let result: SyntaxKind;
543 do {
546 return result;
547 }
548 > json.ts
549 > return {
550 > setPosition: setPosition,
551 > getPosition: () => pos,
552 > scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
553 > getToken: () => token,
554 > getTokenValue: () => value,
555 > getTokenOffset: () => tokenOffset,
556 > getTokenLength: () => pos - tokenOffset,
557 > getTokenError: () => scanError
558 > };
559 > }
560 > json.ts
561 > function isWhitespace(ch: number): boolean { json.ts
562 > return ch === CharacterCodes.space || ch === CharacterCodes.tab || ch === CharacterCodes.verticalTab || ch === CharacterCodes.formFeed ||
563 > ch === CharacterCodes.nonBreakingSpace || ch === CharacterCodes.ogham || ch >= CharacterCodes.enQuad && ch <= CharacterCodes.zeroWidthSpace ||
564 > ch === CharacterCodes.narrowNoBreakSpace || ch === CharacterCodes.mathematicalSpace || ch === CharacterCodes.ideographicSpace || ch === CharacterCodes.byteOrderMark;
565 > }
566 > json.ts
567 > function isLineBreak(ch: number): boolean { json.ts
568 > return ch === CharacterCodes.lineFeed || ch === CharacterCodes.carriageReturn || ch === CharacterCodes.lineSeparator || ch === CharacterCodes.paragraphSeparator;
569 > }
570 > json.ts
571 function isDigit(ch: number): boolean {
572 return ch >= CharacterCodes._0 && ch <= CharacterCodes._9;
573 }
574 > json.ts
575 > const enum CharacterCodes {
576 > nullCharacter = 0,
577 > maxAsciiCharacter = 0x7F,
578 >
579 > lineFeed = 0x0A, // \n
580 > carriageReturn = 0x0D, // \r
581 > lineSeparator = 0x2028,
582 > paragraphSeparator = 0x2029,
583 >
584 > // REVIEW: do we need to support this? The scanner doesn't, but our IText does. This seems
585 > // like an odd disparity? (Or maybe it's completely fine for them to be different).
586 > nextLine = 0x0085,
587 >
588 > // Unicode 3.0 space characters
589 > space = 0x0020, // " "
590 > nonBreakingSpace = 0x00A0, //
591 > enQuad = 0x2000,
592 > emQuad = 0x2001,
593 > enSpace = 0x2002,
594 > emSpace = 0x2003,
595 > threePerEmSpace = 0x2004,
596 > fourPerEmSpace = 0x2005,
597 > sixPerEmSpace = 0x2006,
598 > figureSpace = 0x2007,
599 > punctuationSpace = 0x2008,
600 > thinSpace = 0x2009,
601 > hairSpace = 0x200A,
602 > zeroWidthSpace = 0x200B,
603 > narrowNoBreakSpace = 0x202F,
604 > ideographicSpace = 0x3000,
605 > mathematicalSpace = 0x205F,
606 > ogham = 0x1680,
607 >
608 > _ = 0x5F,
609 > $ = 0x24,
610 >
611 > _0 = 0x30,
612 > _1 = 0x31,
613 > _2 = 0x32,
614 > _3 = 0x33,
615 > _4 = 0x34,
616 > _5 = 0x35,
617 > _6 = 0x36,
618 > _7 = 0x37,
619 > _8 = 0x38,
620 > _9 = 0x39,
621 >
622 > a = 0x61,
623 > b = 0x62,
624 > c = 0x63,
625 > d = 0x64,
626 > e = 0x65,
627 > f = 0x66,
628 > g = 0x67,
629 > h = 0x68,
630 > i = 0x69,
631 > j = 0x6A,
632 > k = 0x6B,
633 > l = 0x6C,
634 > m = 0x6D,
635 > n = 0x6E,
636 > o = 0x6F,
637 > p = 0x70,
638 > q = 0x71,
639 > r = 0x72,
640 > s = 0x73,
641 > t = 0x74,
642 > u = 0x75,
643 > v = 0x76,
644 > w = 0x77,
645 > x = 0x78,
646 > y = 0x79,
647 > z = 0x7A,
648 >
649 > A = 0x41,
650 > B = 0x42,
651 > C = 0x43,
652 > D = 0x44,
653 > E = 0x45,
654 > F = 0x46,
655 > G = 0x47,
656 > H = 0x48,
657 > I = 0x49,
658 > J = 0x4A,
659 > K = 0x4B,
660 > L = 0x4C,
661 > M = 0x4D,
662 > N = 0x4E,
663 > O = 0x4F,
664 > P = 0x50,
665 > Q = 0x51,
666 > R = 0x52,
667 > S = 0x53,
668 > T = 0x54,
669 > U = 0x55,
670 > V = 0x56,
671 > W = 0x57,
672 > X = 0x58,
673 > Y = 0x59,
674 > Z = 0x5A,
675 >
676 > ampersand = 0x26, // &
677 > asterisk = 0x2A, // *
678 > at = 0x40, // @
679 > backslash = 0x5C, // \
680 > bar = 0x7C, // |
681 > caret = 0x5E, // ^
682 > closeBrace = 0x7D, // }
683 > closeBracket = 0x5D, // ]
684 > closeParen = 0x29, // )
685 > colon = 0x3A, // :
686 > comma = 0x2C, // ,
687 > dot = 0x2E, // .
688 > doubleQuote = 0x22, // "
689 > equals = 0x3D, // =
690 > exclamation = 0x21, // !
691 > greaterThan = 0x3E, // >
692 > lessThan = 0x3C, // <
693 > minus = 0x2D, // -
694 > openBrace = 0x7B, // {
695 > openBracket = 0x5B, // [
696 > openParen = 0x28, // (
697 > percent = 0x25, // %
698 > plus = 0x2B, // +
699 > question = 0x3F, // ?
700 > semicolon = 0x3B, // ;
701 > singleQuote = 0x27, // '
702 > slash = 0x2F, // /
703 > tilde = 0x7E, // ~
704 >
705 > backspace = 0x08, // \b
706 > formFeed = 0x0C, // \f
707 > byteOrderMark = 0xFEFF,
708 > tab = 0x09, // \t
709 > verticalTab = 0x0B, // \v
710 > }
711 >
712 > interface NodeImpl extends Node {
713 > type: NodeType;
714 > value?: any;
715 > offset: number;
716 > length: number;
717 > colonOffset?: number;
718 > parent?: NodeImpl;
719 > children?: NodeImpl[];
720 > }
721 >
722 > /**
723 > * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
724 > */
725 > export function getLocation(text: string, position: number): Location {
726 const segments: Segment[] = []; // strings or numbers
727 const earlyReturnException = new Object();
838 };
839 }
840 > json.ts
841 >
842 > /**
843 > * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
844 > * Therefore always check the errors list to find out if the input was valid.
845 > */
846 > export function parse(text: string, errors: ParseError[] = [], options: ParseOptions = ParseOptions.DEFAULT): any {
847 > let currentProperty: string | null = null; json.ts
848 > let currentParent: any = [];
849 > const previousParents: any[] = [];
850 >
851 > function onValue(value: unknown) {
852 > if (Array.isArray(currentParent)) { json.ts
853 > currentParent.push(value);
854 > } else if (currentProperty !== null) {
855 > currentParent[currentProperty] = value; json.ts
856 > }
857 > } json.ts
858 > json.ts
859 > const visitor: JSONVisitor = {
860 > onObjectBegin: () => {
861 > const object = {}; json.ts
862 > onValue(object);
863 > previousParents.push(currentParent);
864 > currentParent = object;
865 > currentProperty = null;
866 > },
867 > onObjectProperty: (name: string) => { json.ts
868 > currentProperty = name; json.ts
869 > },
870 > onObjectEnd: () => { json.ts
871 > currentParent = previousParents.pop(); json.ts
872 > },
873 > onArrayBegin: () => { json.ts
874 > const array: any[] = []; json.ts
875 > onValue(array);
876 > previousParents.push(currentParent);
877 > currentParent = array;
878 > currentProperty = null;
879 > },
880 > onArrayEnd: () => { json.ts
881 > currentParent = previousParents.pop(); json.ts
882 > },
883 > onLiteralValue: onValue, json.ts
884 > onError: (error: ParseErrorCode, offset: number, length: number) => {
885 errors.push({ error, offset, length });
886 }
887 > }; json.ts
888 > visit(text, visitor, options);
889 > return currentParent[0];
890 > }
891 > json.ts
892 >
893 > /**
894 > * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
895 > */
896 > export function parseTree(text: string, errors: ParseError[] = [], options: ParseOptions = ParseOptions.DEFAULT): Node {
897 > let currentParent: NodeImpl = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root json.ts
898 >
899 > function ensurePropertyComplete(endOffset: number) {
900 > if (currentParent.type === 'property') {
901 currentParent.length = endOffset - currentParent.offset;
902 currentParent = currentParent.parent!;
903 }
904 > } json.ts
905 >
906 > function onValue(valueNode: Node): Node {
907 > currentParent.children!.push(valueNode);
908 > return valueNode;
909 > }
910 >
911 > const visitor: JSONVisitor = {
912 > onObjectBegin: (offset: number) => {
913 > currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); json.ts
914 > },
915 > onObjectProperty: (name: string, offset: number, length: number) => { json.ts
916 currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });
917 currentParent.children!.push({ type: 'string', value: name, offset, length, parent: currentParent });
918 },
919 > onObjectEnd: (offset: number, length: number) => { json.ts
920 > currentParent.length = offset + length - currentParent.offset; json.ts
921 > currentParent = currentParent.parent!;
922 > ensurePropertyComplete(offset + length);
923 > },
924 > onArrayBegin: (offset: number, length: number) => { json.ts
925 currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });
926 },
927 > onArrayEnd: (offset: number, length: number) => { json.ts
928 currentParent.length = offset + length - currentParent.offset;
929 currentParent = currentParent.parent!;
930 ensurePropertyComplete(offset + length);
931 },
932 > onLiteralValue: (value: unknown, offset: number, length: number) => { json.ts
933 onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
934 ensurePropertyComplete(offset + length);
935 },
936 > onSeparator: (sep: string, offset: number, length: number) => { json.ts
937 if (currentParent.type === 'property') {
938 if (sep === ':') {
943 }
944 },
945 > onError: (error: ParseErrorCode, offset: number, length: number) => { json.ts
946 errors.push({ error, offset, length });
947 }
948 > }; json.ts
949 > visit(text, visitor, options);
950 >
951 > const result = currentParent.children![0];
952 > if (result) {
953 > delete result.parent;
954 > }
955 > return result;
956 > }
957 > json.ts
958 > /**
959 > * Finds the node at the given path in a JSON DOM.
960 > */
961 > export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined {
962 > if (!root) { json.ts
963 return undefined;
964 }
965 > let node = root; json.ts
966 > for (const segment of path) {
967 > if (typeof segment === 'string') { json.ts
968 > if (node.type !== 'object' || !Array.isArray(node.children)) {
969 return undefined;
970 }
971 > let found = false; json.ts
972 > for (const propertyNode of node.children) {
973 if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) {
974 node = propertyNode.children[1];
977 }
978 }
979 > if (!found) { json.ts
980 > return undefined; json.ts
981 > }
982 > } else { json.ts
983 const index = segment;
984 if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
987 node = node.children[index];
988 }
989 > } json.ts
990 > return node; json.ts
991 > }
992 > json.ts
993 > /**
994 > * Gets the JSON path of the given JSON DOM node
995 > */
996 > export function getNodePath(node: Node): JSONPath {
997 if (!node.parent || !node.parent.children) {
998 return [];
1010 return path;
1011 }
1012 > json.ts
1013 > /**
1014 > * Evaluates the JavaScript object of the given JSON DOM node
1015 > */
1016 > export function getNodeValue(node: Node): any {
1017 switch (node.type) {
1018 case 'array':
1038
1039 }
1040 > json.ts
1041 > export function contains(node: Node, offset: number, includeRightBound = false): boolean {
1042 return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));
1043 }
1044 > json.ts
1045 > /**
1046 > * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.
1047 > */
1048 > export function findNodeAtOffset(node: Node, offset: number, includeRightBound = false): Node | undefined {
1049 if (contains(node, offset, includeRightBound)) {
1050 const children = node.children;
1062 return undefined;
1063 }
1064 > json.ts
1065 >
1066 > /**
1067 > * Parses the given text and invokes the visitor functions for each object, array and literal reached.
1068 > */
1069 > export function visit(text: string, visitor: JSONVisitor, options: ParseOptions = ParseOptions.DEFAULT): any {
1070 > json.ts
1071 > const _scanner = createScanner(text, false);
1072 >
1073 > function toNoArgVisit(visitFunction?: (offset: number, length: number) => void): () => void {
1074 > return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
1075 > }
1076 > function toOneArgVisit<T>(visitFunction?: (arg: T, offset: number, length: number) => void): (arg: T) => void {
1077 > return visitFunction ? (arg: T) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()) : () => true;
1078 > }
1079 >
1080 > const onObjectBegin = toNoArgVisit(visitor.onObjectBegin),
1081 > onObjectProperty = toOneArgVisit(visitor.onObjectProperty),
1082 > onObjectEnd = toNoArgVisit(visitor.onObjectEnd),
1083 > onArrayBegin = toNoArgVisit(visitor.onArrayBegin),
1084 > onArrayEnd = toNoArgVisit(visitor.onArrayEnd),
1085 > onLiteralValue = toOneArgVisit(visitor.onLiteralValue),
1086 > onSeparator = toOneArgVisit(visitor.onSeparator),
1087 > onComment = toNoArgVisit(visitor.onComment),
1088 > onError = toOneArgVisit(visitor.onError);
1089 >
1090 > const disallowComments = options && options.disallowComments;
1091 > const allowTrailingComma = options && options.allowTrailingComma;
1092 > function scanNext(): SyntaxKind {
1093 > while (true) {
1094 > const token = _scanner.scan();
1095 > switch (_scanner.getTokenError()) {
1096 > case ScanError.InvalidUnicode:
1097 handleError(ParseErrorCode.InvalidUnicode);
1098 break;
1099 > case ScanError.InvalidEscapeCharacter: json.ts
1100 handleError(ParseErrorCode.InvalidEscapeCharacter);
1101 break;
1102 > case ScanError.UnexpectedEndOfNumber: json.ts
1103 handleError(ParseErrorCode.UnexpectedEndOfNumber);
1104 break;
1105 > case ScanError.UnexpectedEndOfComment: json.ts
1106 if (!disallowComments) {
1107 handleError(ParseErrorCode.UnexpectedEndOfComment);
1108 }
1109 break;
1110 > case ScanError.UnexpectedEndOfString: json.ts
1111 handleError(ParseErrorCode.UnexpectedEndOfString);
1112 break;
1113 > case ScanError.InvalidCharacter: json.ts
1114 handleError(ParseErrorCode.InvalidCharacter);
1115 break;
1116 > } json.ts
1117 > switch (token) {
1118 > case SyntaxKind.LineCommentTrivia:
1119 > case SyntaxKind.BlockCommentTrivia:
1120 if (disallowComments) {
1121 handleError(ParseErrorCode.InvalidCommentToken);
1124 }
1125 break;
1126 > case SyntaxKind.Unknown: json.ts
1127 handleError(ParseErrorCode.InvalidSymbol);
1128 break;
1129 > case SyntaxKind.Trivia: json.ts
1130 > case SyntaxKind.LineBreakTrivia:
1131 break;
1132 > default: json.ts
1133 > return token;
1134 > }
1135 > }
1136 > }
1137 >
1138 > function handleError(error: ParseErrorCode, skipUntilAfter: SyntaxKind[] = [], skipUntil: SyntaxKind[] = []): void {
1139 onError(error);
1140 if (skipUntilAfter.length + skipUntil.length > 0) {
1151 }
1152 }
1153 > json.ts
1154 > function parseString(isValue: boolean): boolean {
1155 > const value = _scanner.getTokenValue(); json.ts
1156 > if (isValue) {
1157 > onLiteralValue(value); json.ts
1158 > } else { json.ts
1159 > onObjectProperty(value); json.ts
1160 > }
1161 > scanNext(); json.ts
1162 > return true;
1163 > }
1164 > json.ts
1165 > function parseLiteral(): boolean {
1166 switch (_scanner.getToken()) {
1167 case SyntaxKind.NumericLiteral: {
1194 return true;
1195 }
1196 > json.ts
1197 > function parseProperty(): boolean {
1198 > if (_scanner.getToken() !== SyntaxKind.StringLiteral) { json.ts
1199 handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
1200 return false;
1201 }
1202 > parseString(false); json.ts
1203 > if (_scanner.getToken() === SyntaxKind.ColonToken) {
1204 > onSeparator(':');
1205 > scanNext(); // consume colon
1206 >
1207 > if (!parseValue()) {
1208 handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
1209 }
1210 > } else { json.ts
1211 handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
1212 }
1213 > return true; json.ts
1214 > }
1215 > json.ts
1216 > function parseObject(): boolean {
1217 > onObjectBegin(); json.ts
1218 > scanNext(); // consume open brace
1219 >
1220 > let needsComma = false;
1221 > while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) {
1222 > if (_scanner.getToken() === SyntaxKind.CommaToken) { json.ts
1223 if (!needsComma) {
1224 handleError(ParseErrorCode.ValueExpected, [], []);
1229 break;
1230 }
1231 > } else if (needsComma) { json.ts
1232 handleError(ParseErrorCode.CommaExpected, [], []);
1233 }
1234 > if (!parseProperty()) { json.ts
1235 handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);
1236 }
1237 > needsComma = true; json.ts
1238 > }
1239 > onObjectEnd(); json.ts
1240 > if (_scanner.getToken() !== SyntaxKind.CloseBraceToken) {
1241 handleError(ParseErrorCode.CloseBraceExpected, [SyntaxKind.CloseBraceToken], []);
1242 > } else { json.ts
1243 > scanNext(); // consume close brace
1244 > }
1245 > return true;
1246 > } json.ts
1247 > json.ts
1248 > function parseArray(): boolean {
1249 > onArrayBegin(); json.ts
1250 > scanNext(); // consume open bracket
1251 >
1252 > let needsComma = false;
1253 > while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) {
1254 if (_scanner.getToken() === SyntaxKind.CommaToken) {
1255 if (!needsComma) {
1269 needsComma = true;
1270 }
1271 > onArrayEnd(); json.ts
1272 > if (_scanner.getToken() !== SyntaxKind.CloseBracketToken) {
1273 handleError(ParseErrorCode.CloseBracketExpected, [SyntaxKind.CloseBracketToken], []);
1274 > } else { json.ts
1275 > scanNext(); // consume close bracket
1276 > }
1277 > return true;
1278 > }
1279 > json.ts
1280 > function parseValue(): boolean {
1281 > switch (_scanner.getToken()) { json.ts
1282 > case SyntaxKind.OpenBracketToken:
1283 > return parseArray(); json.ts
1284 > case SyntaxKind.OpenBraceToken: json.ts
1285 > return parseObject(); json.ts
1286 > case SyntaxKind.StringLiteral: json.ts
1287 > return parseString(true); json.ts
1288 > default: json.ts
1289 return parseLiteral();
1290 > } json.ts
1291 > }
1292 > json.ts
1293 > scanNext();
1294 > if (_scanner.getToken() === SyntaxKind.EOF) {
1295 if (options.allowEmptyContent) {
1296 return true;
1299 return false;
1300 }
1301 > if (!parseValue()) { json.ts
1302 handleError(ParseErrorCode.ValueExpected, [], []);
1303 return false;
1304 }
1305 > if (_scanner.getToken() !== SyntaxKind.EOF) { json.ts
1306 handleError(ParseErrorCode.EndOfFileExpected, [], []);
1307 }
1308 > return true; json.ts
1309 > }
1310 > json.ts
1311 > export function getNodeType(value: unknown): NodeType {
1312 switch (typeof value) {
1313 case 'boolean': return 'boolean';
src/vs/platform/configuration/common/configurationModels.ts 675 covered LOC · 223 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- configurationModels.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as arrays from '../../../base/common/arrays.js';
7 > import { IStringDictionary } from '../../../base/common/collections.js';
8 > import { Emitter, Event } from '../../../base/common/event.js';
9 > import * as json from '../../../base/common/json.js';
10 > import { Disposable } from '../../../base/common/lifecycle.js';
11 > import { getOrSet, ResourceMap } from '../../../base/common/map.js';
12 > import * as objects from '../../../base/common/objects.js';
13 > import { IExtUri } from '../../../base/common/resources.js';
14 > import * as types from '../../../base/common/types.js';
15 > import { URI, UriComponents } from '../../../base/common/uri.js';
16 > import { addToValueTree, ConfigurationTarget, getConfigurationValue, IConfigurationChange, IConfigurationChangeEvent, IConfigurationCompareResult, IConfigurationData, IConfigurationModel, IConfigurationOverrides, IConfigurationUpdateOverrides, IConfigurationValue, IInspectValue, IOverrides, removeFromValueTree, toValuesTree } from './configuration.js';
17 > import { ConfigurationScope, Extensions, IConfigurationPropertySchema, IConfigurationRegistry, overrideIdentifiersFromKey, OVERRIDE_PROPERTY_REGEX, IRegisteredConfigurationPropertySchema } from './configurationRegistry.js';
18 > import { FileOperation, IFileService } from '../../files/common/files.js';
19 > import { ILogService } from '../../log/common/log.js';
20 > import { Registry } from '../../registry/common/platform.js';
21 > import { Workspace } from '../../workspace/common/workspace.js';
22 >
23 > function freeze<T>(data: T): T { configurationModels.ts
24 > return Object.isFrozen(data) ? data : objects.deepFreeze(data);
25 > }
27 > type InspectValue<V> = IInspectValue<V> & { merged?: V };
28 >
29 > export class ConfigurationModel implements IConfigurationModel {
30 >
31 > static createEmptyModel(logService: ILogService): ConfigurationModel {
32 > return new ConfigurationModel({}, [], [], undefined, logService);
33 > }
34 >
35 > private readonly overrideConfigurations = new Map<string, ConfigurationModel>();
36 >
37 > constructor(
38 > private readonly _contents: IStringDictionary<unknown>, configurationModels.ts
39 > private readonly _keys: string[],
40 > private readonly _overrides: IOverrides[],
41 > private readonly _raw: IStringDictionary<unknown> | ReadonlyArray<IStringDictionary<unknown> | ConfigurationModel> | undefined,
42 > private readonly logService: ILogService
43 > ) {
44 > }
46 > private _rawConfiguration: ConfigurationModel | undefined;
47 > get rawConfiguration(): ConfigurationModel {
48 > if (!this._rawConfiguration) { configurationModels.ts
49 > if (this._raw) {
50 const rawConfigurationModels = (Array.isArray(this._raw) ? this._raw : [this._raw]).map(raw => {
51 if (raw instanceof ConfigurationModel) {
57 });
58 this._rawConfiguration = rawConfigurationModels.reduce((previous, current) => current === previous ? current : previous.merge(current), rawConfigurationModels[0]);
59 > } else { configurationModels.ts
60 > // raw is same as current configurationModels.ts
61 > this._rawConfiguration = this;
62 > }
64 > return this._rawConfiguration;
65 > }
67 > get contents(): IStringDictionary<unknown> {
68 > return this._contents; configurationModels.ts
69 > }
71 > get overrides(): IOverrides[] {
72 > return this._overrides; configurationModels.ts
73 > }
75 > get keys(): string[] {
76 > return this._keys; configurationModels.ts
77 > }
79 > get raw(): IStringDictionary<unknown> | IStringDictionary<unknown>[] | undefined {
80 > if (!this._raw) { configurationModels.ts
81 > return undefined; configurationModels.ts
82 > }
83 > if (Array.isArray(this._raw) && this._raw.every(raw => raw instanceof ConfigurationModel)) { configurationModels.ts
84 return undefined;
85 }
86 return this._raw as IStringDictionary<unknown> | IStringDictionary<unknown>[];
89 > isEmpty(): boolean {
90 > return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0; configurationModels.ts
91 > }
93 > getValue<V>(section: string | undefined): V | undefined {
94 > return section ? getConfigurationValue<V>(this.contents, section) : this.contents as V; configurationModels.ts
95 > }
97 > inspect<V>(section: string | undefined, overrideIdentifier?: string | null): InspectValue<V> {
98 > const that = this; configurationModels.ts
99 > return {
100 > get value() {
101 return freeze(that.rawConfiguration.getValue<V>(section));
102 },
103 > get override() { configurationModels.ts
104 return overrideIdentifier ? freeze(that.rawConfiguration.getOverrideValue<V>(section, overrideIdentifier)) : undefined;
105 },
106 > get merged() { configurationModels.ts
107 > return freeze(overrideIdentifier ? that.rawConfiguration.override(overrideIdentifier).getValue<V>(section) : that.rawConfiguration.getValue<V>(section)); configurationModels.ts
108 > },
109 > get overrides() { configurationModels.ts
110 const overrides: { readonly identifiers: string[]; readonly value: V }[] = [];
111 for (const { contents, identifiers, keys } of that.rawConfiguration.overrides) {
117 return overrides.length ? freeze(overrides) : undefined;
118 }
120 > }
122 > getOverrideValue<V>(section: string | undefined, overrideIdentifier: string): V | undefined {
123 const overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier);
124 return overrideContents
126 : undefined;
127 }
129 > getKeysForOverrideIdentifier(identifier: string): string[] {
130 const keys: string[] = [];
131 for (const override of this.overrides) {
136 return arrays.distinct(keys);
137 }
139 > getAllOverrideIdentifiers(): string[] {
140 > const result: string[] = []; configurationModels.ts
141 > for (const override of this.overrides) {
142 result.push(...override.identifiers);
143 }
144 > return arrays.distinct(result); configurationModels.ts
145 > }
147 > override(identifier: string): ConfigurationModel {
148 let overrideConfigurationModel = this.overrideConfigurations.get(identifier);
149 if (!overrideConfigurationModel) {
153 return overrideConfigurationModel;
154 }
156 > merge(...others: ConfigurationModel[]): ConfigurationModel {
157 > const contents = objects.deepClone(this.contents); configurationModels.ts
158 > const overrides = objects.deepClone(this.overrides);
159 > const keys = [...this.keys];
160 > const raws = this._raw ? Array.isArray(this._raw) ? [...this._raw] : [this._raw] : [this];
161 >
162 > for (const other of others) {
163 > raws.push(...(other._raw ? Array.isArray(other._raw) ? other._raw : [other._raw] : [other]));
164 > if (other.isEmpty()) {
165 > continue; configurationModels.ts
166 > }
167 this.mergeContents(contents, other.contents);
168
183 }
184 }
185 > return new ConfigurationModel(contents, keys, overrides, !raws.length || raws.every(raw => raw instanceof ConfigurationModel) ? undefined : raws, this.logService); configurationModels.ts
186 > }
188 > private createOverrideConfigurationModel(identifier: string): ConfigurationModel {
189 const overrideContents = this.getContentsForOverrideIdentifer(identifier);
190
216 return new ConfigurationModel(contents, this.keys, this.overrides, undefined, this.logService);
217 }
219 > private mergeContents(source: IStringDictionary<unknown>, target: IStringDictionary<unknown>): void {
220 for (const key of Object.keys(target)) {
221 if (key in source) {
228 }
229 }
231 > private getContentsForOverrideIdentifer(identifier: string): IStringDictionary<unknown> | null {
232 let contentsForIdentifierOnly: IStringDictionary<unknown> | null = null;
233 let contents: IStringDictionary<unknown> | null = null;
252 return contents;
253 }
255 > toJSON(): IConfigurationModel {
256 return {
257 contents: this.contents,
260 };
261 }
263 > // Update methods
264 >
265 > public addValue(key: string, value: unknown): void {
266 this.updateValue(key, value, true);
267 }
269 > public setValue(key: string, value: unknown): void {
270 > this.updateValue(key, value, false); configurationModels.ts
271 > }
273 > public removeValue(key: string): void {
274 const index = this.keys.indexOf(key);
275 if (index === -1) {
282 }
283 }
285 > private updateValue(key: string, value: unknown, add: boolean): void {
286 > addToValueTree(this.contents, key, value, e => this.logService.error(e)); configurationModels.ts
287 > add = add || this.keys.indexOf(key) === -1;
288 > if (add) {
289 > this.keys.push(key); configurationModels.ts
290 > }
291 > if (OVERRIDE_PROPERTY_REGEX.test(key)) { configurationModels.ts
292 const overrideContents = this.contents[key] as IStringDictionary<unknown>;
293 const identifiers = overrideIdentifiersFromKey(key);
304 }
305 }
308 >
309 > export interface ConfigurationParseOptions {
310 > skipUnregistered?: boolean;
311 > scopes?: ConfigurationScope[];
312 > skipRestricted?: boolean;
313 > include?: string[];
314 > exclude?: string[];
315 > }
316 >
317 > export class ConfigurationModelParser {
318 >
319 > private _raw: IStringDictionary<unknown> | null = null;
320 > private _configurationModel: ConfigurationModel | null = null;
321 > private _restrictedConfigurations: string[] = [];
322 > private _parseErrors: json.ParseError[] = [];
323 >
324 > constructor(
325 > protected readonly _name: string, configurationModels.ts
326 > protected readonly logService: ILogService
327 > ) { }
329 > get configurationModel(): ConfigurationModel {
330 > return this._configurationModel || ConfigurationModel.createEmptyModel(this.logService); configurationModels.ts
331 > }
333 > get restrictedConfigurations(): string[] {
334 return this._restrictedConfigurations;
335 }
337 > get errors(): json.ParseError[] {
338 return this._parseErrors;
339 }
341 > public parse(content: string | null | undefined, options?: ConfigurationParseOptions): void {
342 > if (!types.isUndefinedOrNull(content)) { configurationModels.ts
343 > const raw = this.doParseContent(content);
344 > this.parseRaw(raw, options);
345 > }
346 > }
348 > public reparse(options: ConfigurationParseOptions): void {
349 if (this._raw) {
350 this.parseRaw(this._raw, options);
351 }
352 }
354 > public parseRaw(raw: IStringDictionary<unknown>, options?: ConfigurationParseOptions): void {
355 > this._raw = raw; configurationModels.ts
356 > const { contents, keys, overrides, restricted, hasExcludedProperties } = this.doParseRaw(raw, options);
357 > this._configurationModel = new ConfigurationModel(contents, keys, overrides, hasExcludedProperties ? [raw] : undefined /* raw has not changed */, this.logService);
358 > this._restrictedConfigurations = restricted || [];
359 > }
361 > private doParseContent(content: string): IStringDictionary<unknown> {
362 > let raw: IStringDictionary<unknown> = {}; configurationModels.ts
363 > let currentProperty: string | null = null;
364 > let currentParent: unknown[] | IStringDictionary<unknown> = [];
365 > const previousParents: (unknown[] | IStringDictionary<unknown>)[] = [];
366 > const parseErrors: json.ParseError[] = [];
367 >
368 > function onValue(value: unknown) {
369 > if (Array.isArray(currentParent)) { configurationModels.ts
370 > currentParent.push(value);
371 > } else if (currentProperty !== null) {
372 currentParent[currentProperty] = value;
373 }
376 > const visitor: json.JSONVisitor = {
377 > onObjectBegin: () => {
378 > const object = {}; configurationModels.ts
379 > onValue(object);
380 > previousParents.push(currentParent);
381 > currentParent = object;
382 > currentProperty = null;
383 > },
384 > onObjectProperty: (name: string) => { configurationModels.ts
385 currentProperty = name;
386 },
387 > onObjectEnd: () => { configurationModels.ts
388 > currentParent = previousParents.pop()!; configurationModels.ts
389 > },
390 > onArrayBegin: () => { configurationModels.ts
391 const array: unknown[] = [];
392 onValue(array);
395 currentProperty = null;
396 },
397 > onArrayEnd: () => { configurationModels.ts
398 currentParent = previousParents.pop()!;
399 },
400 > onLiteralValue: onValue, configurationModels.ts
401 > onError: (error: json.ParseErrorCode, offset: number, length: number) => {
402 parseErrors.push({ error, offset, length });
403 }
405 > if (content) {
407 > json.visit(content, visitor);
408 > raw = (currentParent[0] as IStringDictionary<unknown>) || {};
409 > } catch (e) {
410 this.logService.error(`Error while parsing settings file ${this._name}: ${e}`);
411 this._parseErrors = [e as json.ParseError];
412 }
415 > return raw;
416 > }
418 > protected doParseRaw(raw: IStringDictionary<unknown>, options?: ConfigurationParseOptions): IConfigurationModel & { restricted?: string[]; hasExcludedProperties?: boolean } {
419 > const registry = Registry.as<IConfigurationRegistry>(Extensions.Configuration); configurationModels.ts
420 > const configurationProperties = registry.getConfigurationProperties();
421 > const excludedConfigurationProperties = registry.getExcludedConfigurationProperties();
422 > const filtered = this.filter(raw, configurationProperties, excludedConfigurationProperties, true, options);
423 > raw = filtered.raw;
424 > const contents = toValuesTree(raw, message => this.logService.error(`Conflict in settings file ${this._name}: ${message}`));
425 > const keys = Object.keys(raw);
426 > const overrides = this.toOverrides(raw, message => this.logService.error(`Conflict in settings file ${this._name}: ${message}`));
427 > return { contents, keys, overrides, restricted: filtered.restricted, hasExcludedProperties: filtered.hasExcludedProperties };
428 > }
430 > private filter(properties: IStringDictionary<unknown>, configurationProperties: IStringDictionary<IRegisteredConfigurationPropertySchema>, excludedConfigurationProperties: IStringDictionary<IRegisteredConfigurationPropertySchema>, filterOverriddenProperties: boolean, options?: ConfigurationParseOptions): { raw: IStringDictionary<unknown>; restricted: string[]; hasExcludedProperties: boolean } {
431 > let hasExcludedProperties = false; configurationModels.ts
432 > if (!options?.scopes && !options?.skipRestricted && !options?.skipUnregistered && !options?.exclude?.length) {
433 > return { raw: properties, restricted: [], hasExcludedProperties }; configurationModels.ts
434 > }
435 const raw: IStringDictionary<unknown> = {};
436 const restricted: string[] = [];
454 }
455 return { raw, restricted, hasExcludedProperties };
458 > private shouldInclude(key: string, propertySchema: IConfigurationPropertySchema | undefined, excludedConfigurationProperties: IStringDictionary<IRegisteredConfigurationPropertySchema>, options: ConfigurationParseOptions): boolean {
459 if (options.exclude?.includes(key)) {
460 return false;
481 return options.scopes.includes(scope);
482 }
484 > private toOverrides(raw: IStringDictionary<unknown>, conflictReporter: (message: string) => void): IOverrides[] {
485 > const overrides: IOverrides[] = []; configurationModels.ts
486 > for (const key of Object.keys(raw)) {
487 if (OVERRIDE_PROPERTY_REGEX.test(key)) {
488 const overrideRaw: IStringDictionary<unknown> = {};
498 }
499 }
500 > return overrides; configurationModels.ts
501 > }
503 > }
504 >
505 > export class UserSettings extends Disposable {
506 >
507 > private readonly parser: ConfigurationModelParser;
508 > protected readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
509 > readonly onDidChange: Event<void> = this._onDidChange.event;
510 >
511 > constructor(
512 > private readonly userSettingsResource: URI, configurationModels.ts
513 > protected parseOptions: ConfigurationParseOptions,
514 > extUri: IExtUri,
515 > private readonly fileService: IFileService,
516 > private readonly logService: ILogService,
517 > ) {
518 > super();
519 > this.parser = new ConfigurationModelParser(this.userSettingsResource.toString(), logService);
520 > this._register(this.fileService.watch(extUri.dirname(this.userSettingsResource)));
521 > // Also listen to the resource incase the resource is a symlink - https://github.com/microsoft/vscode/issues/118134
522 > this._register(this.fileService.watch(this.userSettingsResource));
523 > this._register(Event.any(
524 > Event.filter(this.fileService.onDidFilesChange, e => e.contains(this.userSettingsResource)),
525 > Event.filter(this.fileService.onDidRunOperation, e => (e.isOperation(FileOperation.CREATE) || e.isOperation(FileOperation.COPY) || e.isOperation(FileOperation.DELETE) || e.isOperation(FileOperation.WRITE)) && extUri.isEqual(e.resource, userSettingsResource))
526 > )(() => this._onDidChange.fire()));
527 > }
529 > async loadConfiguration(): Promise<ConfigurationModel> {
531 > const content = await this.fileService.readFile(this.userSettingsResource);
532 > this.parser.parse(content.value.toString() || '{}', this.parseOptions);
533 > return this.parser.configurationModel;
534 > } catch (e) {
535 > return ConfigurationModel.createEmptyModel(this.logService); configurationModels.ts
536 > }
539 > reparse(parseOptions?: ConfigurationParseOptions): ConfigurationModel {
540 if (parseOptions) {
541 this.parseOptions = parseOptions;
544 return this.parser.configurationModel;
545 }
547 > getRestrictedSettings(): string[] {
548 return this.parser.restrictedConfigurations;
549 }
551 >
552 > class ConfigurationInspectValue<V> implements IConfigurationValue<V> {
553 >
554 > constructor(
555 > private readonly key: string, configurationModels.ts
556 > private readonly overrides: IConfigurationOverrides,
557 > private readonly _value: V | undefined,
558 > readonly overrideIdentifiers: string[] | undefined,
559 > private readonly defaultConfiguration: ConfigurationModel,
560 > private readonly policyConfiguration: ConfigurationModel | undefined,
561 > private readonly applicationConfiguration: ConfigurationModel | undefined,
562 > private readonly userConfiguration: ConfigurationModel,
563 > private readonly localUserConfiguration: ConfigurationModel,
564 > private readonly remoteUserConfiguration: ConfigurationModel,
565 > private readonly workspaceConfiguration: ConfigurationModel | undefined,
566 > private readonly folderConfigurationModel: ConfigurationModel | undefined,
567 > private readonly memoryConfigurationModel: ConfigurationModel
568 > ) {
569 > }
571 > get value(): V | undefined {
572 return freeze(this._value);
573 }
575 > private toInspectValue(inspectValue: IInspectValue<V> | undefined | null): IInspectValue<V> | undefined {
576 return inspectValue?.value !== undefined || inspectValue?.override !== undefined || inspectValue?.overrides !== undefined ? inspectValue : undefined;
577 }
579 > private _defaultInspectValue: InspectValue<V> | undefined;
580 > private get defaultInspectValue(): InspectValue<V> {
581 if (!this._defaultInspectValue) {
582 this._defaultInspectValue = this.defaultConfiguration.inspect<V>(this.key, this.overrides.overrideIdentifier);
584 return this._defaultInspectValue;
585 }
587 > get defaultValue(): V | undefined {
588 return this.defaultInspectValue.merged;
589 }
591 > get default(): IInspectValue<V> | undefined {
592 return this.toInspectValue(this.defaultInspectValue);
593 }
595 > private _policyInspectValue: InspectValue<V> | undefined | null;
596 > private get policyInspectValue(): InspectValue<V> | null {
597 if (this._policyInspectValue === undefined) {
598 this._policyInspectValue = this.policyConfiguration ? this.policyConfiguration.inspect<V>(this.key) : null;
600 return this._policyInspectValue;
601 }
603 > get policyValue(): V | undefined {
604 return this.policyInspectValue?.merged;
605 }
607 > get policy(): IInspectValue<V> | undefined {
608 return this.policyInspectValue?.value !== undefined ? { value: this.policyInspectValue.value } : undefined;
609 }
611 > private _applicationInspectValue: InspectValue<V> | undefined | null;
612 > private get applicationInspectValue(): InspectValue<V> | null {
613 if (this._applicationInspectValue === undefined) {
614 this._applicationInspectValue = this.applicationConfiguration ? this.applicationConfiguration.inspect<V>(this.key) : null;
616 return this._applicationInspectValue;
617 }
619 > get applicationValue(): V | undefined {
620 return this.applicationInspectValue?.merged;
621 }
623 > get application(): IInspectValue<V> | undefined {
624 return this.toInspectValue(this.applicationInspectValue);
625 }
627 > private _userInspectValue: InspectValue<V> | undefined;
628 > private get userInspectValue(): InspectValue<V> {
629 > if (!this._userInspectValue) { configurationModels.ts
630 > this._userInspectValue = this.userConfiguration.inspect<V>(this.key, this.overrides.overrideIdentifier);
631 > }
632 > return this._userInspectValue;
633 > }
635 > get userValue(): V | undefined {
636 > return this.userInspectValue.merged; configurationModels.ts
637 > }
639 > get user(): IInspectValue<V> | undefined {
640 return this.toInspectValue(this.userInspectValue);
641 }
643 > private _userLocalInspectValue: InspectValue<V> | undefined;
644 > private get userLocalInspectValue(): InspectValue<V> {
645 if (!this._userLocalInspectValue) {
646 this._userLocalInspectValue = this.localUserConfiguration.inspect<V>(this.key, this.overrides.overrideIdentifier);
648 return this._userLocalInspectValue;
649 }
651 > get userLocalValue(): V | undefined {
652 return this.userLocalInspectValue.merged;
653 }
655 > get userLocal(): IInspectValue<V> | undefined {
656 return this.toInspectValue(this.userLocalInspectValue);
657 }
659 > private _userRemoteInspectValue: InspectValue<V> | undefined;
660 > private get userRemoteInspectValue(): InspectValue<V> {
661 if (!this._userRemoteInspectValue) {
662 this._userRemoteInspectValue = this.remoteUserConfiguration.inspect<V>(this.key, this.overrides.overrideIdentifier);
664 return this._userRemoteInspectValue;
665 }
667 > get userRemoteValue(): V | undefined {
668 return this.userRemoteInspectValue.merged;
669 }
671 > get userRemote(): IInspectValue<V> | undefined {
672 return this.toInspectValue(this.userRemoteInspectValue);
673 }
675 > private _workspaceInspectValue: InspectValue<V> | undefined | null;
676 > private get workspaceInspectValue(): InspectValue<V> | null {
677 if (this._workspaceInspectValue === undefined) {
678 this._workspaceInspectValue = this.workspaceConfiguration ? this.workspaceConfiguration.inspect<V>(this.key, this.overrides.overrideIdentifier) : null;
680 return this._workspaceInspectValue;
681 }
683 > get workspaceValue(): V | undefined {
684 return this.workspaceInspectValue?.merged;
685 }
687 > get workspace(): IInspectValue<V> | undefined {
688 return this.toInspectValue(this.workspaceInspectValue);
689 }
691 > private _workspaceFolderInspectValue: InspectValue<V> | undefined | null;
692 > private get workspaceFolderInspectValue(): InspectValue<V> | null {
693 if (this._workspaceFolderInspectValue === undefined) {
694 this._workspaceFolderInspectValue = this.folderConfigurationModel ? this.folderConfigurationModel.inspect<V>(this.key, this.overrides.overrideIdentifier) : null;
696 return this._workspaceFolderInspectValue;
697 }
699 > get workspaceFolderValue(): V | undefined {
700 return this.workspaceFolderInspectValue?.merged;
701 }
703 > get workspaceFolder(): IInspectValue<V> | undefined {
704 return this.toInspectValue(this.workspaceFolderInspectValue);
705 }
707 > private _memoryInspectValue: InspectValue<V> | undefined;
708 > private get memoryInspectValue(): InspectValue<V> {
709 if (this._memoryInspectValue === undefined) {
710 this._memoryInspectValue = this.memoryConfigurationModel.inspect<V>(this.key, this.overrides.overrideIdentifier);
712 return this._memoryInspectValue;
713 }
715 > get memoryValue(): V | undefined {
716 return this.memoryInspectValue.merged;
717 }
719 > get memory(): IInspectValue<V> | undefined {
720 return this.toInspectValue(this.memoryInspectValue);
721 }
723 > }
724 >
725 > export class Configuration {
726 >
727 > private _workspaceConsolidatedConfiguration: ConfigurationModel | null = null;
728 > private _foldersConsolidatedConfigurations = new ResourceMap<ConfigurationModel>();
729 >
730 > constructor(
731 > private _defaultConfiguration: ConfigurationModel, configurationModels.ts
732 > private _policyConfiguration: ConfigurationModel,
733 > private _applicationConfiguration: ConfigurationModel,
734 > private _localUserConfiguration: ConfigurationModel,
735 > private _remoteUserConfiguration: ConfigurationModel,
736 > private _workspaceConfiguration: ConfigurationModel,
737 > private _folderConfigurations: ResourceMap<ConfigurationModel>,
738 > private _memoryConfiguration: ConfigurationModel,
739 > private _memoryConfigurationByResource: ResourceMap<ConfigurationModel>,
740 > private readonly logService: ILogService
741 > ) {
742 > }
743 >
744 > getValue(section: string | undefined, overrides: IConfigurationOverrides, workspace: Workspace | undefined): unknown {
745 > const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(section, overrides, workspace); configurationModels.ts
746 > return consolidateConfigurationModel.getValue(section);
747 > }
749 > updateValue(key: string, value: unknown, overrides: IConfigurationUpdateOverrides = {}): void {
750 let memoryConfiguration: ConfigurationModel | undefined;
751 if (overrides.resource) {
769 }
770 }
772 > inspect<C>(key: string, overrides: IConfigurationOverrides, workspace: Workspace | undefined): IConfigurationValue<C> {
773 > const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(key, overrides, workspace); configurationModels.ts
774 > const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
775 > const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
776 > const overrideIdentifiers = new Set<string>();
777 > for (const override of consolidateConfigurationModel.overrides) {
778 for (const overrideIdentifier of override.identifiers) {
779 if (consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== undefined) {
782 }
783 }
785 > return new ConfigurationInspectValue<C>(
786 > key,
787 > overrides,
788 > consolidateConfigurationModel.getValue<C>(key),
789 > overrideIdentifiers.size ? [...overrideIdentifiers] : undefined,
790 > this._defaultConfiguration,
791 > this._policyConfiguration.isEmpty() ? undefined : this._policyConfiguration,
792 > this.applicationConfiguration.isEmpty() ? undefined : this.applicationConfiguration,
793 > this.userConfiguration,
794 > this.localUserConfiguration,
795 > this.remoteUserConfiguration,
796 > workspace ? this._workspaceConfiguration : undefined,
797 > folderConfigurationModel ? folderConfigurationModel : undefined,
798 > memoryConfigurationModel
799 > );
800 >
801 > }
803 > keys(workspace: Workspace | undefined): {
804 default: string[];
805 policy: string[];
817 };
818 }
820 > updateDefaultConfiguration(defaultConfiguration: ConfigurationModel): void {
821 this._defaultConfiguration = defaultConfiguration;
822 this._workspaceConsolidatedConfiguration = null;
823 this._foldersConsolidatedConfigurations.clear();
824 }
826 > updatePolicyConfiguration(policyConfiguration: ConfigurationModel): void {
827 this._policyConfiguration = policyConfiguration;
828 }
830 > updateApplicationConfiguration(applicationConfiguration: ConfigurationModel): void {
831 this._applicationConfiguration = applicationConfiguration;
832 this._workspaceConsolidatedConfiguration = null;
833 this._foldersConsolidatedConfigurations.clear();
834 }
836 > updateLocalUserConfiguration(localUserConfiguration: ConfigurationModel): void {
837 this._localUserConfiguration = localUserConfiguration;
838 this._userConfiguration = null;
840 this._foldersConsolidatedConfigurations.clear();
841 }
843 > updateRemoteUserConfiguration(remoteUserConfiguration: ConfigurationModel): void {
844 this._remoteUserConfiguration = remoteUserConfiguration;
845 this._userConfiguration = null;
847 this._foldersConsolidatedConfigurations.clear();
848 }
850 > updateWorkspaceConfiguration(workspaceConfiguration: ConfigurationModel): void {
851 this._workspaceConfiguration = workspaceConfiguration;
852 this._workspaceConsolidatedConfiguration = null;
853 this._foldersConsolidatedConfigurations.clear();
854 }
856 > updateFolderConfiguration(resource: URI, configuration: ConfigurationModel): void {
857 this._folderConfigurations.set(resource, configuration);
858 this._foldersConsolidatedConfigurations.delete(resource);
859 }
861 > deleteFolderConfiguration(resource: URI): void {
862 this.folderConfigurations.delete(resource);
863 this._foldersConsolidatedConfigurations.delete(resource);
864 }
866 > compareAndUpdateDefaultConfiguration(defaults: ConfigurationModel, keys?: string[]): IConfigurationChange {
867 const overrides: [string, string[]][] = [];
868 if (!keys) {
885 return { keys, overrides };
886 }
888 > compareAndUpdatePolicyConfiguration(policyConfiguration: ConfigurationModel): IConfigurationChange {
889 const { added, updated, removed } = compare(this._policyConfiguration, policyConfiguration);
890 const keys = [...added, ...updated, ...removed];
894 return { keys, overrides: [] };
895 }
897 > compareAndUpdateApplicationConfiguration(application: ConfigurationModel): IConfigurationChange {
898 const { added, updated, removed, overrides } = compare(this.applicationConfiguration, application);
899 const keys = [...added, ...updated, ...removed];
903 return { keys, overrides };
904 }
906 > compareAndUpdateLocalUserConfiguration(user: ConfigurationModel): IConfigurationChange {
907 > const { added, updated, removed, overrides } = compare(this.localUserConfiguration, user); configurationModels.ts
908 > const keys = [...added, ...updated, ...removed];
909 > if (keys.length) {
910 this.updateLocalUserConfiguration(user);
911 }
912 > return { keys, overrides }; configurationModels.ts
913 > }
915 > compareAndUpdateRemoteUserConfiguration(user: ConfigurationModel): IConfigurationChange {
916 const { added, updated, removed, overrides } = compare(this.remoteUserConfiguration, user);
917 const keys = [...added, ...updated, ...removed];
921 return { keys, overrides };
922 }
924 > compareAndUpdateWorkspaceConfiguration(workspaceConfiguration: ConfigurationModel): IConfigurationChange {
925 const { added, updated, removed, overrides } = compare(this.workspaceConfiguration, workspaceConfiguration);
926 const keys = [...added, ...updated, ...removed];
930 return { keys, overrides };
931 }
933 > compareAndUpdateFolderConfiguration(resource: URI, folderConfiguration: ConfigurationModel): IConfigurationChange {
934 const currentFolderConfiguration = this.folderConfigurations.get(resource);
935 const { added, updated, removed, overrides } = compare(currentFolderConfiguration, folderConfiguration);
940 return { keys, overrides };
941 }
943 > compareAndDeleteFolderConfiguration(folder: URI): IConfigurationChange {
944 const folderConfig = this.folderConfigurations.get(folder);
945 if (!folderConfig) {
950 return { keys: [...added, ...updated, ...removed], overrides };
951 }
953 > get defaults(): ConfigurationModel {
954 return this._defaultConfiguration;
955 }
957 > get applicationConfiguration(): ConfigurationModel {
958 > return this._applicationConfiguration; configurationModels.ts
959 > }
961 > private _userConfiguration: ConfigurationModel | null = null;
962 > get userConfiguration(): ConfigurationModel { configurationModels.ts
963 > if (!this._userConfiguration) { configurationModels.ts
964 > if (this._remoteUserConfiguration.isEmpty()) {
965 > this._userConfiguration = this._localUserConfiguration; configurationModels.ts
966 > } else { configurationModels.ts
967 const merged = this._localUserConfiguration.merge(this._remoteUserConfiguration);
968 this._userConfiguration = new ConfigurationModel(merged.contents, merged.keys, merged.overrides, undefined, this.logService);
969 }
971 > return this._userConfiguration;
972 > }
974 > get localUserConfiguration(): ConfigurationModel {
975 > return this._localUserConfiguration; configurationModels.ts
976 > }
978 > get remoteUserConfiguration(): ConfigurationModel {
979 > return this._remoteUserConfiguration; configurationModels.ts
980 > }
982 > get workspaceConfiguration(): ConfigurationModel {
983 return this._workspaceConfiguration;
984 }
986 > get folderConfigurations(): ResourceMap<ConfigurationModel> {
987 return this._folderConfigurations;
988 }
990 > private getConsolidatedConfigurationModel(section: string | undefined, overrides: IConfigurationOverrides, workspace: Workspace | undefined): ConfigurationModel {
991 > let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace); configurationModels.ts
992 > if (overrides.overrideIdentifier) {
993 configurationModel = configurationModel.override(overrides.overrideIdentifier);
994 }
995 > if (!this._policyConfiguration.isEmpty() && this._policyConfiguration.getValue(section) !== undefined) { configurationModels.ts
996 // clone by merging
997 configurationModel = configurationModel.merge();
1000 }
1001 }
1002 > return configurationModel; configurationModels.ts
1003 > }
1005 > private getConsolidatedConfigurationModelForResource({ resource }: IConfigurationOverrides, workspace: Workspace | undefined): ConfigurationModel {
1006 > let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration(); configurationModels.ts
1007 >
1008 > if (workspace && resource) {
1009 const root = workspace.getFolder(resource);
1010 if (root) {
1016 }
1017 }
1019 > return consolidateConfiguration;
1020 > }
1022 > private getWorkspaceConsolidatedConfiguration(): ConfigurationModel {
1023 > if (!this._workspaceConsolidatedConfiguration) { configurationModels.ts
1024 > this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.applicationConfiguration, this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
1025 > }
1026 > return this._workspaceConsolidatedConfiguration;
1027 > }
1029 > private getFolderConsolidatedConfiguration(folder: URI): ConfigurationModel {
1030 let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
1031 if (!folderConsolidatedConfiguration) {
1041 return folderConsolidatedConfiguration;
1042 }
1044 > private getFolderConfigurationModelForResource(resource: URI | null | undefined, workspace: Workspace | undefined): ConfigurationModel | undefined {
1045 > if (workspace && resource) { configurationModels.ts
1046 const root = workspace.getFolder(resource);
1047 if (root) {
1049 }
1050 }
1051 > return undefined; configurationModels.ts
1052 > }
1054 > toData(): IConfigurationData {
1055 > return { configurationModels.ts
1056 > defaults: {
1057 > contents: this._defaultConfiguration.contents,
1058 > overrides: this._defaultConfiguration.overrides,
1059 > keys: this._defaultConfiguration.keys,
1060 > },
1061 > policy: {
1062 > contents: this._policyConfiguration.contents,
1063 > overrides: this._policyConfiguration.overrides,
1064 > keys: this._policyConfiguration.keys
1065 > },
1066 > application: {
1067 > contents: this.applicationConfiguration.contents,
1068 > overrides: this.applicationConfiguration.overrides,
1069 > keys: this.applicationConfiguration.keys,
1070 > raw: Array.isArray(this.applicationConfiguration.raw) ? undefined : this.applicationConfiguration.raw
1071 > },
1072 > userLocal: {
1073 > contents: this.localUserConfiguration.contents,
1074 > overrides: this.localUserConfiguration.overrides,
1075 > keys: this.localUserConfiguration.keys,
1076 > raw: Array.isArray(this.localUserConfiguration.raw) ? undefined : this.localUserConfiguration.raw
1077 > },
1078 > userRemote: {
1079 > contents: this.remoteUserConfiguration.contents,
1080 > overrides: this.remoteUserConfiguration.overrides,
1081 > keys: this.remoteUserConfiguration.keys,
1082 > raw: Array.isArray(this.remoteUserConfiguration.raw) ? undefined : this.remoteUserConfiguration.raw
1083 > },
1084 > workspace: {
1085 > contents: this._workspaceConfiguration.contents,
1086 > overrides: this._workspaceConfiguration.overrides,
1087 > keys: this._workspaceConfiguration.keys
1088 > },
1089 > folders: [...this._folderConfigurations.keys()].reduce<[UriComponents, IConfigurationModel][]>((result, folder) => {
1090 const { contents, overrides, keys } = this._folderConfigurations.get(folder)!;
1091 result.push([folder, { contents, overrides, keys }]);
1092 return result;
1093 > }, []) configurationModels.ts
1094 > };
1095 > }
1097 > allKeys(): string[] {
1098 const keys: Set<string> = new Set<string>();
1099 this._defaultConfiguration.keys.forEach(key => keys.add(key));
1103 return [...keys.values()];
1104 }
1106 > protected allOverrideIdentifiers(): string[] {
1107 const keys: Set<string> = new Set<string>();
1108 this._defaultConfiguration.getAllOverrideIdentifiers().forEach(key => keys.add(key));
1112 return [...keys.values()];
1113 }
1115 > protected getAllKeysForOverrideIdentifier(overrideIdentifier: string): string[] {
1116 const keys: Set<string> = new Set<string>();
1117 this._defaultConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach(key => keys.add(key));
1121 return [...keys.values()];
1122 }
1124 > static parse(data: IConfigurationData, logService: ILogService): Configuration {
1125 const defaultConfiguration = this.parseConfigurationModel(data.defaults, logService);
1126 const policyConfiguration = this.parseConfigurationModel(data.policy, logService);
1146 );
1147 }
1149 > private static parseConfigurationModel(model: IConfigurationModel, logService: ILogService): ConfigurationModel {
1150 return new ConfigurationModel(model.contents, model.keys, model.overrides, model.raw, logService);
1151 }
1153 > }
1154 >
1155 > export function mergeChanges(...changes: IConfigurationChange[]): IConfigurationChange {
1156 if (changes.length === 0) {
1157 return { keys: [], overrides: [] };
1173 return { keys: [...keysSet.values()], overrides };
1174 }
1176 > export class ConfigurationChangeEvent implements IConfigurationChangeEvent {
1177 >
1178 > private readonly _marker = '\n';
1179 > private readonly _markerCode1 = this._marker.charCodeAt(0);
1180 > private readonly _markerCode2 = '.'.charCodeAt(0);
1181 > private readonly _affectsConfigStr: string;
1182 >
1183 > readonly affectedKeys = new Set<string>();
1184 > source!: ConfigurationTarget;
1185 >
1186 > constructor(
1187 > readonly change: IConfigurationChange, configurationModels.ts
1188 > private readonly previous: { workspace?: Workspace; data: IConfigurationData } | undefined,
1189 > private readonly currentConfiguraiton: Configuration,
1190 > private readonly currentWorkspace: Workspace | undefined,
1191 > private readonly logService: ILogService
1192 > ) {
1193 > for (const key of change.keys) {
1194 this.affectedKeys.add(key);
1195 }
1196 > for (const [, keys] of change.overrides) { configurationModels.ts
1197 for (const key of keys) {
1198 this.affectedKeys.add(key);
1199 }
1200 }
1202 > // Example: '\nfoo.bar\nabc.def\n'
1203 > this._affectsConfigStr = this._marker;
1204 > for (const key of this.affectedKeys) {
1205 this._affectsConfigStr += key + this._marker;
1206 }
1209 > private _previousConfiguration: Configuration | undefined = undefined;
1210 > get previousConfiguration(): Configuration | undefined {
1211 if (!this._previousConfiguration && this.previous) {
1212 this._previousConfiguration = Configuration.parse(this.previous.data, this.logService);
1214 return this._previousConfiguration;
1215 }
1217 > affectsConfiguration(section: string, overrides?: IConfigurationOverrides): boolean {
1218 > // we have one large string with all keys that have changed. we pad (marker) the section configurationModels.ts
1219 > // and check that either find it padded or before a segment character
1220 > const needle = this._marker + section;
1221 > const idx = this._affectsConfigStr.indexOf(needle);
1222 > if (idx < 0) {
1223 > // NOT: (marker + section) configurationModels.ts
1224 > return false;
1225 > }
1226 const pos = idx + needle.length;
1227 if (pos >= this._affectsConfigStr.length) {
1229 }
1230 const code = this._affectsConfigStr.charCodeAt(pos);
1231 > if (code !== this._markerCode1 && code !== this._markerCode2) { configurationModels.ts
1232 // NOT: section + (marker | segment)
1233 return false;
1239 }
1240 return true;
1243 >
1244 > function compare(from: ConfigurationModel | undefined, to: ConfigurationModel | undefined): IConfigurationCompareResult { configurationModels.ts
1245 > const { added, removed, updated } = compareConfigurationContents(to?.rawConfiguration, from?.rawConfiguration);
1246 > const overrides: [string, string[]][] = [];
1247 >
1248 > const fromOverrideIdentifiers = from?.getAllOverrideIdentifiers() || [];
1249 > const toOverrideIdentifiers = to?.getAllOverrideIdentifiers() || [];
1250 >
1251 > if (to) {
1252 > const addedOverrideIdentifiers = toOverrideIdentifiers.filter(key => !fromOverrideIdentifiers.includes(key)); configurationModels.ts
1253 > for (const identifier of addedOverrideIdentifiers) {
1254 overrides.push([identifier, to.getKeysForOverrideIdentifier(identifier)]);
1255 }
1258 > if (from) {
1259 > const removedOverrideIdentifiers = fromOverrideIdentifiers.filter(key => !toOverrideIdentifiers.includes(key));
1260 > for (const identifier of removedOverrideIdentifiers) {
1261 overrides.push([identifier, from.getKeysForOverrideIdentifier(identifier)]);
1262 }
1264 >
1265 > if (to && from) {
1266 > for (const identifier of fromOverrideIdentifiers) { configurationModels.ts
1267 if (toOverrideIdentifiers.includes(identifier)) {
1268 const result = compareConfigurationContents({ contents: from.getOverrideValue(undefined, identifier) || {}, keys: from.getKeysForOverrideIdentifier(identifier) }, { contents: to.getOverrideValue(undefined, identifier) || {}, keys: to.getKeysForOverrideIdentifier(identifier) });
1270 }
1271 }
1274 > return { added, removed, updated, overrides };
1275 > }
1277 > function compareConfigurationContents(to: { keys: string[]; contents: IStringDictionary<unknown> } | undefined, from: { keys: string[]; contents: IStringDictionary<unknown> } | undefined) { configurationModels.ts
1278 > const added = to
1279 > ? from ? to.keys.filter(key => from.keys.indexOf(key) === -1) : [...to.keys] configurationModels.ts
1280 : [];
1281 > const removed = from configurationModels.ts
1282 > ? to ? from.keys.filter(key => to.keys.indexOf(key) === -1) : [...from.keys]
1283 : [];
1284 > const updated: string[] = []; configurationModels.ts
1285 >
1286 > if (to && from) {
1287 > for (const key of from.keys) { configurationModels.ts
1288 if (to.keys.indexOf(key) !== -1) {
1289 const value1 = getConfigurationValue(from.contents, key);
src/vs/platform/extensionManagement/common/extensionManagement.ts 660 covered LOC · 10 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensionManagement.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken } from '../../../base/common/cancellation.js';
7 > import { IStringDictionary } from '../../../base/common/collections.js';
8 > import { Event } from '../../../base/common/event.js';
9 > import { IMarkdownString } from '../../../base/common/htmlContent.js';
10 > import { IPager } from '../../../base/common/paging.js';
11 > import { Platform } from '../../../base/common/platform.js';
12 > import { PolicyCategory } from '../../../base/common/policy.js';
13 > import { URI } from '../../../base/common/uri.js';
14 > import { localize, localize2 } from '../../../nls.js';
15 > import { ConfigurationScope, Extensions, IConfigurationRegistry } from '../../configuration/common/configurationRegistry.js';
16 > import { ExtensionType, IExtension, IExtensionManifest, TargetPlatform } from '../../extensions/common/extensions.js';
17 > import { FileOperationError, FileOperationResult, IFileService, IFileStat } from '../../files/common/files.js';
18 > import { createDecorator } from '../../instantiation/common/instantiation.js';
19 > import { Registry } from '../../registry/common/platform.js';
20 > import { IExtensionGalleryManifest } from './extensionGalleryManifest.js';
21 >
22 > export const EXTENSION_IDENTIFIER_PATTERN = '^([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$';
23 > export const EXTENSION_IDENTIFIER_REGEX = new RegExp(EXTENSION_IDENTIFIER_PATTERN);
24 > export const WEB_EXTENSION_TAG = '__web_extension';
25 > export const LANGUAGE_MODEL_CHAT_PROVIDER_EXTENSION_TAG = 'language-models';
26 > export const EXTENSION_INSTALL_SKIP_WALKTHROUGH_CONTEXT = 'skipWalkthrough';
27 > export const EXTENSION_INSTALL_SKIP_PUBLISHER_TRUST_CONTEXT = 'skipPublisherTrust';
28 > export const EXTENSION_INSTALL_SOURCE_CONTEXT = 'extensionInstallSource';
29 > export const EXTENSION_INSTALL_DEP_PACK_CONTEXT = 'dependecyOrPackExtensionInstall';
30 > export const EXTENSION_INSTALL_CLIENT_TARGET_PLATFORM_CONTEXT = 'clientTargetPlatform';
31 >
32 > export const enum ExtensionInstallSource {
33 > COMMAND = 'command',
34 > SETTINGS_SYNC = 'settingsSync',
35 > }
36 >
37 > export interface IProductVersion {
38 > readonly version: string;
39 > readonly date?: string;
40 > }
41 >
42 > export function TargetPlatformToString(targetPlatform: TargetPlatform) {
43 switch (targetPlatform) {
44 case TargetPlatform.WIN32_X64: return 'Windows 64 bit';
62 }
63 }
65 > export function toTargetPlatform(targetPlatform: string): TargetPlatform {
66 switch (targetPlatform) {
67 case TargetPlatform.WIN32_X64: return TargetPlatform.WIN32_X64;
84 }
85 }
87 > export function getTargetPlatform(platform: Platform | 'alpine', arch: string | undefined): TargetPlatform {
88 switch (platform) {
89 case Platform.Windows:
129 }
130 }
132 > export function isNotWebExtensionInWebTargetPlatform(allTargetPlatforms: TargetPlatform[], productTargetPlatform: TargetPlatform): boolean {
133 // Not a web extension in web target platform
134 return productTargetPlatform === TargetPlatform.WEB && !allTargetPlatforms.includes(TargetPlatform.WEB);
135 }
137 > export function isTargetPlatformCompatible(extensionTargetPlatform: TargetPlatform, allTargetPlatforms: TargetPlatform[], productTargetPlatform: TargetPlatform): boolean {
138 // Not compatible when extension is not a web extension in web target platform
139 if (isNotWebExtensionInWebTargetPlatform(allTargetPlatforms, productTargetPlatform)) {
163 return false;
164 }
166 > export interface IGalleryExtensionProperties {
167 > dependencies?: string[];
168 > extensionPack?: string[];
169 > engine?: string;
170 > enabledApiProposals?: string[];
171 > localizedLanguages?: string[];
172 > targetPlatform: TargetPlatform;
173 > isPreReleaseVersion: boolean;
174 > executesCode?: boolean;
175 > }
176 >
177 > export interface IGalleryExtensionAsset {
178 > uri: string;
179 > fallbackUri: string;
180 > }
181 >
182 > export interface IGalleryExtensionAssets {
183 > manifest: IGalleryExtensionAsset | null;
184 > readme: IGalleryExtensionAsset | null;
185 > changelog: IGalleryExtensionAsset | null;
186 > license: IGalleryExtensionAsset | null;
187 > repository: IGalleryExtensionAsset | null;
188 > download: IGalleryExtensionAsset;
189 > icon: IGalleryExtensionAsset | null;
190 > signature: IGalleryExtensionAsset | null;
191 > coreTranslations: [string, IGalleryExtensionAsset][];
192 > }
193 >
194 > export function isIExtensionIdentifier(obj: unknown): obj is IExtensionIdentifier {
195 const thing = obj as IExtensionIdentifier | undefined;
196 return !!thing
199 && (!thing.uuid || typeof thing.uuid === 'string');
200 }
202 > export interface IExtensionIdentifier {
203 > id: string;
204 > uuid?: string;
205 > }
206 >
207 > export interface IGalleryExtensionIdentifier extends IExtensionIdentifier {
208 > uuid: string;
209 > }
210 >
211 > export interface IGalleryExtensionVersion {
212 > version: string;
213 > date: string;
214 > isPreReleaseVersion: boolean;
215 > targetPlatforms: TargetPlatform[];
216 > }
217 >
218 > export interface IGalleryExtension {
219 > type: 'gallery';
220 > name: string;
221 > identifier: IGalleryExtensionIdentifier;
222 > version: string;
223 > displayName: string;
224 > publisherId: string;
225 > publisher: string;
226 > publisherDisplayName: string;
227 > publisherDomain?: { link: string; verified: boolean };
228 > publisherLink?: string;
229 > publisherSponsorLink?: string;
230 > description: string;
231 > installCount: number;
232 > rating: number;
233 > ratingCount: number;
234 > categories: readonly string[];
235 > tags: readonly string[];
236 > releaseDate: number;
237 > lastUpdated: number;
238 > preview: boolean;
239 > private: boolean;
240 > hasPreReleaseVersion: boolean;
241 > hasReleaseVersion: boolean;
242 > isSigned: boolean;
243 > allTargetPlatforms: TargetPlatform[];
244 > assets: IGalleryExtensionAssets;
245 > properties: IGalleryExtensionProperties;
246 > detailsLink?: string;
247 > ratingLink?: string;
248 > supportLink?: string;
249 > telemetryData?: IStringDictionary<unknown>;
250 > queryContext?: IStringDictionary<unknown>;
251 > }
252 >
253 > export type InstallSource = 'gallery' | 'vsix' | 'resource';
254 >
255 > export interface IGalleryMetadata {
256 > id: string;
257 > publisherId: string;
258 > private: boolean;
259 > publisherDisplayName: string;
260 > isPreReleaseVersion: boolean;
261 > targetPlatform?: TargetPlatform;
262 > }
263 >
264 > export type Metadata = Partial<IGalleryMetadata & {
265 > isApplicationScoped: boolean;
266 > isMachineScoped: boolean;
267 > isBuiltin: boolean;
268 > isSystem: boolean;
269 > updated: boolean;
270 > preRelease: boolean;
271 > hasPreReleaseVersion: boolean;
272 > installedTimestamp: number;
273 > pinned: boolean;
274 > source: InstallSource;
275 > size: number;
276 > }>;
277 >
278 > export interface ILocalExtension extends IExtension {
279 > isWorkspaceScoped: boolean;
280 > isMachineScoped: boolean;
281 > isApplicationScoped: boolean;
282 > publisherId: string | null;
283 > installedTimestamp?: number;
284 > isPreReleaseVersion: boolean;
285 > hasPreReleaseVersion: boolean;
286 > private: boolean;
287 > preRelease: boolean;
288 > updated: boolean;
289 > pinned: boolean;
290 > forceAutoUpdate: boolean;
291 > source: InstallSource;
292 > size: number;
293 > }
294 >
295 > export const enum SortBy {
296 > NoneOrRelevance = 'NoneOrRelevance',
297 > LastUpdatedDate = 'LastUpdatedDate',
298 > Title = 'Title',
299 > PublisherName = 'PublisherName',
300 > InstallCount = 'InstallCount',
301 > PublishedDate = 'PublishedDate',
302 > AverageRating = 'AverageRating',
303 > WeightedRating = 'WeightedRating'
304 > }
305 >
306 > export const enum SortOrder {
307 > Default = 0,
308 > Ascending = 1,
309 > Descending = 2
310 > }
311 >
312 > export const enum FilterType {
313 > Category = 'Category',
314 > ExtensionId = 'ExtensionId',
315 > ExtensionName = 'ExtensionName',
316 > ExcludeWithFlags = 'ExcludeWithFlags',
317 > Featured = 'Featured',
318 > SearchText = 'SearchText',
319 > Tag = 'Tag',
320 > Target = 'Target',
321 > }
322 >
323 > export interface IQueryOptions {
324 > text?: string;
325 > exclude?: string[];
326 > pageSize?: number;
327 > sortBy?: SortBy;
328 > sortOrder?: SortOrder;
329 > source?: string;
330 > includePreRelease?: boolean;
331 > productVersion?: IProductVersion;
332 > }
333 >
334 > export const enum StatisticType {
335 > Install = 'install',
336 > Uninstall = 'uninstall'
337 > }
338 >
339 > export interface IDeprecationInfo {
340 > readonly disallowInstall?: boolean;
341 > readonly extension?: {
342 > readonly id: string;
343 > readonly displayName: string;
344 > readonly autoMigrate?: {
345 > readonly storage: boolean;
346 > readonly donotDisable?: boolean;
347 > };
348 > readonly preRelease?: boolean;
349 > };
350 > readonly settings?: readonly string[];
351 > readonly additionalInfo?: string;
352 > }
353 >
354 > export interface ISearchPrefferedResults {
355 > readonly query?: string;
356 > readonly preferredResults?: string[];
357 > }
358 >
359 > export type MaliciousExtensionInfo = {
360 > readonly extensionOrPublisher: IExtensionIdentifier | string;
361 > readonly learnMoreLink?: string;
362 > };
363 >
364 > export interface IExtensionsControlManifest {
365 > readonly malicious: ReadonlyArray<MaliciousExtensionInfo>;
366 > readonly deprecated: IStringDictionary<IDeprecationInfo>;
367 > readonly search: ISearchPrefferedResults[];
368 > readonly autoUpdate?: IStringDictionary<string>;
369 > }
370 >
371 > export const enum InstallOperation {
372 > None = 1,
373 > Install,
374 > Update,
375 > Migrate,
376 > }
377 >
378 > export interface ITranslation {
379 > contents: { [key: string]: {} };
380 > }
381 >
382 > export interface IExtensionInfo extends IExtensionIdentifier {
383 > version?: string;
384 > preRelease?: boolean;
385 > hasPreRelease?: boolean;
386 > currentVersion?: string;
387 > }
388 >
389 > export interface IExtensionQueryOptions {
390 > targetPlatform?: TargetPlatform;
391 > productVersion?: IProductVersion;
392 > compatible?: boolean;
393 > queryAllVersions?: boolean;
394 > source?: string;
395 > }
396 >
397 > export interface IExtensionGalleryCapabilities {
398 > readonly query: {
399 > readonly sortBy: readonly SortBy[];
400 > readonly filters: readonly FilterType[];
401 > };
402 > readonly allRepositorySigned: boolean;
403 > }
404 >
405 > export const IExtensionGalleryService = createDecorator<IExtensionGalleryService>('extensionGalleryService');
406 >
407 > /**
408 > * Service to interact with the Visual Studio Code Marketplace to get extensions.
409 > * @throws Error if the Marketplace is not enabled or not reachable.
410 > */
411 > export interface IExtensionGalleryService {
412 > readonly _serviceBrand: undefined;
413 > isEnabled(): boolean;
414 > query(options: IQueryOptions, token: CancellationToken): Promise<IPager<IGalleryExtension>>;
415 > getExtensions(extensionInfos: ReadonlyArray<IExtensionInfo>, token: CancellationToken): Promise<IGalleryExtension[]>;
416 > getExtensions(extensionInfos: ReadonlyArray<IExtensionInfo>, options: IExtensionQueryOptions, token: CancellationToken): Promise<IGalleryExtension[]>;
417 > isExtensionCompatible(extension: IGalleryExtension, includePreRelease: boolean, targetPlatform: TargetPlatform, productVersion?: IProductVersion): Promise<boolean>;
418 > getCompatibleExtension(extension: IGalleryExtension, includePreRelease: boolean, targetPlatform: TargetPlatform, productVersion?: IProductVersion): Promise<IGalleryExtension | null>;
419 > getAllCompatibleVersions(extensionIdentifier: IExtensionIdentifier, includePreRelease: boolean, targetPlatform: TargetPlatform): Promise<IGalleryExtensionVersion[]>;
420 > getAllVersions(extensionIdentifier: IExtensionIdentifier): Promise<IGalleryExtensionVersion[]>;
421 > download(extension: IGalleryExtension, location: URI, operation: InstallOperation): Promise<void>;
422 > downloadSignatureArchive(extension: IGalleryExtension, location: URI): Promise<void>;
423 > reportStatistic(publisher: string, name: string, version: string, type: StatisticType): Promise<void>;
424 > getReadme(extension: IGalleryExtension, token: CancellationToken): Promise<string>;
425 > getManifest(extension: IGalleryExtension, token: CancellationToken): Promise<IExtensionManifest | null>;
426 > getChangelog(extension: IGalleryExtension, token: CancellationToken): Promise<string>;
427 > getCoreTranslation(extension: IGalleryExtension, languageId: string): Promise<ITranslation | null>;
428 > getExtensionsControlManifest(): Promise<IExtensionsControlManifest>;
429 > }
430 >
431 > export interface InstallExtensionEvent {
432 > readonly identifier: IExtensionIdentifier;
433 > readonly source: URI | IGalleryExtension;
434 > readonly profileLocation: URI;
435 > readonly applicationScoped?: boolean;
436 > readonly workspaceScoped?: boolean;
437 > }
438 >
439 > export interface InstallExtensionResult {
440 > readonly identifier: IExtensionIdentifier;
441 > readonly operation: InstallOperation;
442 > readonly source?: URI | IGalleryExtension;
443 > readonly local?: ILocalExtension;
444 > readonly error?: Error;
445 > readonly context?: IStringDictionary<unknown>;
446 > readonly profileLocation: URI;
447 > readonly applicationScoped?: boolean;
448 > readonly workspaceScoped?: boolean;
449 > }
450 >
451 > export interface UninstallExtensionEvent {
452 > readonly identifier: IExtensionIdentifier;
453 > readonly profileLocation: URI;
454 > readonly applicationScoped?: boolean;
455 > readonly workspaceScoped?: boolean;
456 > }
457 >
458 > export interface DidUninstallExtensionEvent {
459 > readonly identifier: IExtensionIdentifier;
460 > readonly error?: string;
461 > readonly profileLocation: URI;
462 > readonly applicationScoped?: boolean;
463 > readonly workspaceScoped?: boolean;
464 > }
465 >
466 > export interface DidUpdateExtensionMetadata {
467 > readonly profileLocation: URI;
468 > readonly local: ILocalExtension;
469 > }
470 >
471 > export const enum ExtensionGalleryErrorCode {
472 > Timeout = 'Timeout',
473 > Cancelled = 'Cancelled',
474 > ClientError = 'ClientError',
475 > ServerError = 'ServerError',
476 > Failed = 'Failed',
477 > DownloadFailedWriting = 'DownloadFailedWriting',
478 > Offline = 'Offline',
479 > }
480 >
481 > export class ExtensionGalleryError extends Error {
482 > constructor(message: string, readonly code: ExtensionGalleryErrorCode) {
483 super(message);
484 this.name = code;
485 }
487 >
488 > export const enum ExtensionManagementErrorCode {
489 > NotFound = 'NotFound',
490 > Unsupported = 'Unsupported',
491 > Deprecated = 'Deprecated',
492 > Malicious = 'Malicious',
493 > Incompatible = 'Incompatible',
494 > IncompatibleApi = 'IncompatibleApi',
495 > IncompatibleTargetPlatform = 'IncompatibleTargetPlatform',
496 > ReleaseVersionNotFound = 'ReleaseVersionNotFound',
497 > Invalid = 'Invalid',
498 > Download = 'Download',
499 > DownloadSignature = 'DownloadSignature',
500 > DownloadFailedWriting = ExtensionGalleryErrorCode.DownloadFailedWriting,
501 > UpdateMetadata = 'UpdateMetadata',
502 > Extract = 'Extract',
503 > Scanning = 'Scanning',
504 > ScanningExtension = 'ScanningExtension',
505 > ReadRemoved = 'ReadRemoved',
506 > UnsetRemoved = 'UnsetRemoved',
507 > Delete = 'Delete',
508 > Rename = 'Rename',
509 > IntializeDefaultProfile = 'IntializeDefaultProfile',
510 > AddToProfile = 'AddToProfile',
511 > InstalledExtensionNotFound = 'InstalledExtensionNotFound',
512 > PostInstall = 'PostInstall',
513 > CorruptZip = 'CorruptZip',
514 > IncompleteZip = 'IncompleteZip',
515 > PackageNotSigned = 'PackageNotSigned',
516 > SignatureVerificationInternal = 'SignatureVerificationInternal',
517 > SignatureVerificationFailed = 'SignatureVerificationFailed',
518 > NotAllowed = 'NotAllowed',
519 > Gallery = 'Gallery',
520 > Cancelled = 'Cancelled',
521 > Unknown = 'Unknown',
522 > Internal = 'Internal',
523 > }
524 >
525 > export enum ExtensionSignatureVerificationCode {
526 > 'NotSigned' = 'NotSigned',
527 > 'Success' = 'Success',
528 > 'RequiredArgumentMissing' = 'RequiredArgumentMissing', // A required argument is missing.
529 > 'InvalidArgument' = 'InvalidArgument', // An argument is invalid.
530 > 'PackageIsUnreadable' = 'PackageIsUnreadable', // The extension package is unreadable.
531 > 'UnhandledException' = 'UnhandledException', // An unhandled exception occurred.
532 > 'SignatureManifestIsMissing' = 'SignatureManifestIsMissing', // The extension is missing a signature manifest file (.signature.manifest).
533 > 'SignatureManifestIsUnreadable' = 'SignatureManifestIsUnreadable', // The signature manifest is unreadable.
534 > 'SignatureIsMissing' = 'SignatureIsMissing', // The extension is missing a signature file (.signature.p7s).
535 > 'SignatureIsUnreadable' = 'SignatureIsUnreadable', // The signature is unreadable.
536 > 'CertificateIsUnreadable' = 'CertificateIsUnreadable', // The certificate is unreadable.
537 > 'SignatureArchiveIsUnreadable' = 'SignatureArchiveIsUnreadable',
538 > 'FileAlreadyExists' = 'FileAlreadyExists', // The output file already exists.
539 > 'SignatureArchiveIsInvalidZip' = 'SignatureArchiveIsInvalidZip',
540 > 'SignatureArchiveHasSameSignatureFile' = 'SignatureArchiveHasSameSignatureFile', // The signature archive has the same signature file.
541 > 'PackageIntegrityCheckFailed' = 'PackageIntegrityCheckFailed', // The package integrity check failed.
542 > 'SignatureIsInvalid' = 'SignatureIsInvalid', // The extension has an invalid signature file (.signature.p7s).
543 > 'SignatureManifestIsInvalid' = 'SignatureManifestIsInvalid', // The extension has an invalid signature manifest file (.signature.manifest).
544 > 'SignatureIntegrityCheckFailed' = 'SignatureIntegrityCheckFailed', // The extension's signature integrity check failed. Extension integrity is suspect.
545 > 'EntryIsMissing' = 'EntryIsMissing', // An entry referenced in the signature manifest was not found in the extension.
546 > 'EntryIsTampered' = 'EntryIsTampered', // The integrity check for an entry referenced in the signature manifest failed.
547 > 'Untrusted' = 'Untrusted', // An X.509 certificate in the extension signature is untrusted.
548 > 'CertificateRevoked' = 'CertificateRevoked', // An X.509 certificate in the extension signature has been revoked.
549 > 'SignatureIsNotValid' = 'SignatureIsNotValid', // The extension signature is invalid.
550 > 'UnknownError' = 'UnknownError', // An unknown error occurred.
551 > 'PackageIsInvalidZip' = 'PackageIsInvalidZip', // The extension package is not valid ZIP format.
552 > 'SignatureArchiveHasTooManyEntries' = 'SignatureArchiveHasTooManyEntries', // The signature archive has too many entries.
553 > }
554 >
555 > export class ExtensionManagementError extends Error {
556 > constructor(message: string, readonly code: ExtensionManagementErrorCode) {
557 super(message);
558 this.name = code;
559 }
561 >
562 > export interface InstallExtensionSummary {
563 > failed: {
564 > id: string;
565 > installOptions: InstallOptions;
566 > }[];
567 > }
568 >
569 > export type InstallOptions = {
570 > isBuiltin?: boolean;
571 > isWorkspaceScoped?: boolean;
572 > isMachineScoped?: boolean;
573 > isApplicationScoped?: boolean;
574 > pinned?: boolean;
575 > donotIncludePackAndDependencies?: boolean;
576 > installGivenVersion?: boolean;
577 > preRelease?: boolean;
578 > installPreReleaseVersion?: boolean;
579 > donotVerifySignature?: boolean;
580 > operation?: InstallOperation;
581 > profileLocation?: URI;
582 > productVersion?: IProductVersion;
583 > keepExisting?: boolean;
584 > downloadExtensionsLocally?: boolean;
585 > /**
586 > * Context passed through to InstallExtensionResult
587 > */
588 > context?: IStringDictionary<unknown>;
589 > };
590 >
591 > export type UninstallOptions = {
592 > readonly profileLocation?: URI;
593 > readonly donotIncludePack?: boolean;
594 > readonly donotCheckDependents?: boolean;
595 > readonly versionOnly?: boolean;
596 > readonly remove?: boolean;
597 > };
598 >
599 > export interface IExtensionManagementParticipant {
600 > postInstall(local: ILocalExtension, source: URI | IGalleryExtension, options: InstallOptions, token: CancellationToken): Promise<void>;
601 > postUninstall(local: ILocalExtension, options: UninstallOptions, token: CancellationToken): Promise<void>;
602 > }
603 >
604 > export type InstallExtensionInfo = { readonly extension: IGalleryExtension; readonly options: InstallOptions };
605 > export type UninstallExtensionInfo = { readonly extension: ILocalExtension; readonly options?: UninstallOptions };
606 >
607 > export const IExtensionManagementService = createDecorator<IExtensionManagementService>('extensionManagementService');
608 > export interface IExtensionManagementService {
609 > readonly _serviceBrand: undefined;
610 >
611 > readonly preferPreReleases: boolean;
612 >
613 > onInstallExtension: Event<InstallExtensionEvent>;
614 > onDidInstallExtensions: Event<readonly InstallExtensionResult[]>;
615 > onUninstallExtension: Event<UninstallExtensionEvent>;
616 > onDidUninstallExtension: Event<DidUninstallExtensionEvent>;
617 > onDidUpdateExtensionMetadata: Event<DidUpdateExtensionMetadata>;
618 >
619 > zip(extension: ILocalExtension): Promise<URI>;
620 > getManifest(vsix: URI): Promise<IExtensionManifest>;
621 > install(vsix: URI, options?: InstallOptions): Promise<ILocalExtension>;
622 > canInstall(extension: IGalleryExtension): Promise<true | IMarkdownString>;
623 > installFromGallery(extension: IGalleryExtension, options?: InstallOptions): Promise<ILocalExtension>;
624 > installGalleryExtensions(extensions: InstallExtensionInfo[]): Promise<InstallExtensionResult[]>;
625 > installFromLocation(location: URI, profileLocation: URI): Promise<ILocalExtension>;
626 > installExtensionsFromProfile(extensions: IExtensionIdentifier[], fromProfileLocation: URI, toProfileLocation: URI): Promise<ILocalExtension[]>;
627 > uninstall(extension: ILocalExtension, options?: UninstallOptions): Promise<void>;
628 > uninstallExtensions(extensions: UninstallExtensionInfo[]): Promise<void>;
629 > toggleApplicationScope(extension: ILocalExtension, fromProfileLocation: URI): Promise<ILocalExtension>;
630 > getInstalled(type?: ExtensionType, profileLocation?: URI, productVersion?: IProductVersion, language?: string): Promise<ILocalExtension[]>;
631 > getExtensionsControlManifest(): Promise<IExtensionsControlManifest>;
632 > copyExtensions(fromProfileLocation: URI, toProfileLocation: URI): Promise<void>;
633 > updateMetadata(local: ILocalExtension, metadata: Partial<Metadata>, profileLocation: URI): Promise<ILocalExtension>;
634 > resetPinnedStateForAllUserExtensions(pinned: boolean): Promise<void>;
635 >
636 > download(extension: IGalleryExtension, operation: InstallOperation, donotVerifySignature: boolean): Promise<URI>;
637 >
638 > registerParticipant(pariticipant: IExtensionManagementParticipant): void;
639 > getTargetPlatform(): Promise<TargetPlatform>;
640 >
641 > cleanUp(): Promise<void>;
642 > }
643 >
644 > export const DISABLED_EXTENSIONS_STORAGE_PATH = 'extensionsIdentifiers/disabled';
645 > export const ENABLED_EXTENSIONS_STORAGE_PATH = 'extensionsIdentifiers/enabled';
646 > export const IGlobalExtensionEnablementService = createDecorator<IGlobalExtensionEnablementService>('IGlobalExtensionEnablementService');
647 >
648 > export interface IGlobalExtensionEnablementService {
649 > readonly _serviceBrand: undefined;
650 > readonly onDidChangeEnablement: Event<{ readonly extensions: IExtensionIdentifier[]; readonly source?: string }>;
651 >
652 > getDisabledExtensions(): IExtensionIdentifier[];
653 > enableExtension(extension: IExtensionIdentifier, source?: string): Promise<boolean>;
654 > disableExtension(extension: IExtensionIdentifier, source?: string): Promise<boolean>;
655 >
656 > }
657 >
658 > export type IConfigBasedExtensionTip = {
659 > readonly extensionId: string;
660 > readonly extensionName: string;
661 > readonly isExtensionPack: boolean;
662 > readonly configName: string;
663 > readonly important: boolean;
664 > readonly whenNotInstalled?: string[];
665 > };
666 >
667 > export type IExecutableBasedExtensionTip = {
668 > readonly extensionId: string;
669 > readonly extensionName: string;
670 > readonly isExtensionPack: boolean;
671 > readonly exeName: string;
672 > readonly exeFriendlyName: string;
673 > readonly windowsPath?: string;
674 > readonly whenNotInstalled?: string[];
675 > };
676 >
677 > export const IExtensionTipsService = createDecorator<IExtensionTipsService>('IExtensionTipsService');
678 > export interface IExtensionTipsService {
679 > readonly _serviceBrand: undefined;
680 >
681 > getConfigBasedTips(folder: URI): Promise<IConfigBasedExtensionTip[]>;
682 > getImportantExecutableBasedTips(): Promise<IExecutableBasedExtensionTip[]>;
683 > getOtherExecutableBasedTips(): Promise<IExecutableBasedExtensionTip[]>;
684 > }
685 >
686 > export type AllowedExtensionsConfigValueType = IStringDictionary<boolean | string | string[]>;
687 >
688 > export const IAllowedExtensionsService = createDecorator<IAllowedExtensionsService>('IAllowedExtensionsService');
689 > export interface IAllowedExtensionsService {
690 > readonly _serviceBrand: undefined;
691 >
692 > readonly allowedExtensionsConfigValue: AllowedExtensionsConfigValueType | undefined;
693 > readonly onDidChangeAllowedExtensionsConfigValue: Event<void>;
694 >
695 > isAllowed(extension: IGalleryExtension | IExtension): true | IMarkdownString;
696 > isAllowed(extension: { id: string; publisherDisplayName: string | undefined; version?: string; prerelease?: boolean; targetPlatform?: TargetPlatform }): true | IMarkdownString;
697 > }
698 >
699 export async function computeSize(location: URI, fileService: IFileService): Promise<number> {
700 let stat: IFileStat;
713 return stat.size ?? 0;
714 }
716 > export const ExtensionsLocalizedLabel = localize2('extensions', "Extensions");
717 > export const PreferencesLocalizedLabel = localize2('preferences', 'Preferences');
718 > export const AllowedExtensionsConfigKey = 'extensions.allowed';
719 > export const VerifyExtensionSignatureConfigKey = 'extensions.verifySignature';
720 > export const ExtensionRequestsTimeoutConfigKey = 'extensions.requestTimeout';
721 >
722 > Registry.as<IConfigurationRegistry>(Extensions.Configuration)
723 > .registerConfiguration({
724 > id: 'extensions',
725 > order: 30,
726 > title: localize('extensionsConfigurationTitle', "Extensions"),
727 > type: 'object',
728 > properties: {
729 > [AllowedExtensionsConfigKey]: {
730 > // Note: Type is set only to object because to support policies generation during build time, where single type is expected.
731 > type: 'object',
732 > markdownDescription: localize('extensions.allowed', "Specify a list of extensions that are allowed to use. This helps maintain a secure and consistent development environment by restricting the use of unauthorized extensions. For more information on how to configure this setting, please visit the [Configure Allowed Extensions](https://aka.ms/vscode/enterprise/extensions/allowed) section."),
733 > default: '*',
734 > defaultSnippets: [{
735 > body: {},
736 > description: localize('extensions.allowed.none', "No extensions are allowed."),
737 > }, {
738 > body: {
739 > '*': true
740 > },
741 > description: localize('extensions.allowed.all', "All extensions are allowed."),
742 > }],
743 > scope: ConfigurationScope.APPLICATION,
744 > policy: {
745 > name: 'AllowedExtensions',
746 > category: PolicyCategory.Extensions,
747 > minimumVersion: '1.96',
748 > localization: {
749 > description: {
750 > key: 'extensions.allowed.policy',
751 > value: localize('extensions.allowed.policy', "Specify a list of extensions that are allowed to use. This helps maintain a secure and consistent development environment by restricting the use of unauthorized extensions. More information: https://aka.ms/vscode/enterprise/extensions/allowed"),
752 > }
753 > }
754 > },
755 > additionalProperties: false,
756 > patternProperties: {
757 > '([a-z0-9A-Z][a-z0-9-A-Z]*)\\.([a-z0-9A-Z][a-z0-9-A-Z]*)$': {
758 > anyOf: [
759 > {
760 > type: ['boolean', 'string'],
761 > enum: [true, false, 'stable'],
762 > description: localize('extensions.allow.description', "Allow or disallow the extension."),
763 > enumDescriptions: [
764 > localize('extensions.allowed.enable.desc', "Extension is allowed."),
765 > localize('extensions.allowed.disable.desc', "Extension is not allowed."),
766 > localize('extensions.allowed.disable.stable.desc', "Allow only stable versions of the extension."),
767 > ],
768 > },
769 > {
770 > type: 'array',
771 > items: {
772 > type: 'string',
773 > },
774 > description: localize('extensions.allow.version.description', "Allow or disallow specific versions of the extension. To specifcy a platform specific version, use the format `[email protected]`, e.g. `[email protected]`. Supported platforms are `win32-x64`, `win32-arm64`, `linux-x64`, `linux-arm64`, `linux-armhf`, `alpine-x64`, `alpine-arm64`, `darwin-x64`, `darwin-arm64`"),
775 > },
776 > ]
777 > },
778 > '([a-z0-9A-Z][a-z0-9-A-Z]*)$': {
779 > type: ['boolean', 'string'],
780 > enum: [true, false, 'stable'],
781 > description: localize('extension.publisher.allow.description', "Allow or disallow all extensions from the publisher."),
782 > enumDescriptions: [
783 > localize('extensions.publisher.allowed.enable.desc', "All extensions from the publisher are allowed."),
784 > localize('extensions.publisher.allowed.disable.desc', "All extensions from the publisher are not allowed."),
785 > localize('extensions.publisher.allowed.disable.stable.desc', "Allow only stable versions of the extensions from the publisher."),
786 > ],
787 > },
788 > '\\*': {
789 > type: 'boolean',
790 > enum: [true, false],
791 > description: localize('extensions.allow.all.description', "Allow or disallow all extensions."),
792 > enumDescriptions: [
793 > localize('extensions.allow.all.enable', "Allow all extensions."),
794 > localize('extensions.allow.all.disable', "Disallow all extensions.")
795 > ],
796 > }
797 > }
798 > }
799 > }
800 > });
801 >
802 > export function shouldRequireRepositorySignatureFor(isPrivate: boolean, galleryManifest: IExtensionGalleryManifest | null): boolean {
803 if (isPrivate) {
804 return galleryManifest?.capabilities.signing?.allPrivateRepositorySigned === true;
src/vs/platform/configuration/common/configurationRegistry.ts 640 covered LOC · 99 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- configurationRegistry.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { distinct } from '../../../base/common/arrays.js';
7 > import { IStringDictionary } from '../../../base/common/collections.js';
8 > import { Emitter, Event } from '../../../base/common/event.js';
9 > import { IJSONSchema } from '../../../base/common/jsonSchema.js';
10 > import * as types from '../../../base/common/types.js';
11 > import * as nls from '../../../nls.js';
12 > import { getLanguageTagSettingPlainKey } from './configuration.js';
13 > import { Extensions as JSONExtensions, IJSONContributionRegistry } from '../../jsonschemas/common/jsonContributionRegistry.js';
14 > import { Registry } from '../../registry/common/platform.js';
15 > import { IPolicy, IPolicyReference, PolicyName } from '../../../base/common/policy.js';
16 > import { Disposable } from '../../../base/common/lifecycle.js';
17 > import product from '../../product/common/product.js';
18 >
19 > export enum EditPresentationTypes {
20 > Multiline = 'multilineText',
21 > Singleline = 'singlelineText'
22 > }
23 >
24 > export const Extensions = {
25 > Configuration: 'base.contributions.configuration'
26 > };
27 >
28 > export interface IConfigurationDelta {
29 > removedDefaults?: IConfigurationDefaults[];
30 > removedConfigurations?: IConfigurationNode[];
31 > addedDefaults?: IConfigurationDefaults[];
32 > addedConfigurations?: IConfigurationNode[];
33 > }
34 >
35 > export interface IConfigurationRegistry {
36 >
37 > /**
38 > * Register a configuration to the registry.
39 > */
40 > registerConfiguration(configuration: IConfigurationNode): IConfigurationNode;
41 >
42 > /**
43 > * Register multiple configurations to the registry.
44 > */
45 > registerConfigurations(configurations: IConfigurationNode[], validate?: boolean): void;
46 >
47 > /**
48 > * Deregister multiple configurations from the registry.
49 > */
50 > deregisterConfigurations(configurations: IConfigurationNode[]): void;
51 >
52 > /**
53 > * update the configuration registry by
54 > * - registering the configurations to add
55 > * - dereigstering the configurations to remove
56 > */
57 > updateConfigurations(configurations: { add: IConfigurationNode[]; remove: IConfigurationNode[] }): void;
58 >
59 > /**
60 > * Register multiple default configurations to the registry.
61 > */
62 > registerDefaultConfigurations(defaultConfigurations: IConfigurationDefaults[]): void;
63 >
64 > /**
65 > * Deregister multiple default configurations from the registry.
66 > */
67 > deregisterDefaultConfigurations(defaultConfigurations: IConfigurationDefaults[]): void;
68 >
69 > /**
70 > * Bulk update of the configuration registry (default and configurations, remove and add)
71 > * @param delta
72 > */
73 > deltaConfiguration(delta: IConfigurationDelta): void;
74 >
75 > /**
76 > * Return the registered default configurations
77 > */
78 > getRegisteredDefaultConfigurations(): IConfigurationDefaults[];
79 >
80 > /**
81 > * Return the registered configuration defaults overrides
82 > */
83 > getConfigurationDefaultsOverrides(): Map<string, IConfigurationDefaultOverrideValue>;
84 >
85 > /**
86 > * Signal that the schema of a configuration setting has changes. It is currently only supported to change enumeration values.
87 > * Property or default value changes are not allowed.
88 > */
89 > notifyConfigurationSchemaUpdated(...configurations: IConfigurationNode[]): void;
90 >
91 > /**
92 > * Event that fires whenever a configuration has been
93 > * registered.
94 > */
95 > readonly onDidSchemaChange: Event<void>;
96 >
97 > /**
98 > * Event that fires whenever a configuration has been
99 > * registered.
100 > */
101 > readonly onDidUpdateConfiguration: Event<{ properties: ReadonlySet<string>; defaultsOverrides?: boolean }>;
102 >
103 > /**
104 > * Returns all configuration nodes contributed to this registry.
105 > */
106 > getConfigurations(): IConfigurationNode[];
107 >
108 > /**
109 > * Returns all configurations settings of all configuration nodes contributed to this registry.
110 > */
111 > getConfigurationProperties(): IStringDictionary<IRegisteredConfigurationPropertySchema>;
112 >
113 > /**
114 > * Returns the owning setting key per policy name (at most one owner per name).
115 > */
116 > getPolicyConfigurations(): Map<PolicyName, string>;
117 >
118 > /**
119 > * Returns the referencing setting keys per policy name.
120 > */
121 > getPolicyReferenceConfigurations(): Map<PolicyName, Set<string>>;
122 >
123 > /**
124 > * Returns all excluded configurations settings of all configuration nodes contributed to this registry.
125 > */
126 > getExcludedConfigurationProperties(): IStringDictionary<IRegisteredConfigurationPropertySchema>;
127 >
128 > /**
129 > * Register the identifiers for editor configurations
130 > */
131 > registerOverrideIdentifiers(identifiers: string[]): void;
132 > }
133 >
134 > export const enum ConfigurationScope {
135 > /**
136 > * Application specific configuration, which can be configured only in default profile user settings.
137 > */
138 > APPLICATION = 1,
139 > /**
140 > * Machine specific configuration, which can be configured only in local and remote user settings.
141 > */
142 > MACHINE,
143 > /**
144 > * An application machine specific configuration, which can be configured only in default profile user settings and remote user settings.
145 > */
146 > APPLICATION_MACHINE,
147 > /**
148 > * Window specific configuration, which can be configured in the user or workspace settings.
149 > */
150 > WINDOW,
151 > /**
152 > * Resource specific configuration, which can be configured in the user, workspace or folder settings.
153 > */
154 > RESOURCE,
155 > /**
156 > * Resource specific configuration that can be configured in language specific settings
157 > */
158 > LANGUAGE_OVERRIDABLE,
159 > /**
160 > * Machine specific configuration that can also be configured in workspace or folder settings.
161 > */
162 > MACHINE_OVERRIDABLE,
163 > }
164 >
165 >
166 > export interface IConfigurationPropertySchema extends IJSONSchema {
167 >
168 > scope?: ConfigurationScope;
169 >
170 > /**
171 > * When restricted, value of this configuration will be read only from trusted sources.
172 > * For eg., If the workspace is not trusted, then the value of this configuration is not read from workspace settings file.
173 > */
174 > restricted?: boolean;
175 >
176 > /**
177 > * When `false` this property is excluded from the registry. Default is to include.
178 > */
179 > included?: boolean;
180 >
181 > /**
182 > * List of tags associated to the property.
183 > * - A tag can be used for filtering
184 > * - Use `experimental` tag for marking the setting as experimental.
185 > */
186 > tags?: string[];
187 >
188 > /**
189 > * When enabled this setting is ignored during sync and user can override this.
190 > */
191 > ignoreSync?: boolean;
192 >
193 > /**
194 > * When enabled this setting is ignored during sync and user cannot override this.
195 > */
196 > disallowSyncIgnore?: boolean;
197 >
198 > /**
199 > * Disallow extensions to contribute configuration default value for this setting.
200 > */
201 > disallowConfigurationDefault?: boolean;
202 >
203 > /**
204 > * Labels for enumeration items
205 > */
206 > enumItemLabels?: string[];
207 >
208 > /**
209 > * Optional keywords used for search purposes.
210 > */
211 > keywords?: string[];
212 >
213 > /**
214 > * When specified, controls the presentation format of string settings.
215 > * Otherwise, the presentation format defaults to `singleline`.
216 > */
217 > editPresentation?: EditPresentationTypes;
218 >
219 > /**
220 > * When specified, gives an order number for the setting
221 > * within the settings editor. Otherwise, the setting is placed at the end.
222 > */
223 > order?: number;
224 >
225 > /**
226 > * When specified, this setting's value can always be overwritten by
227 > * a system-wide policy. Exactly one setting may *own* a given policy name.
228 > */
229 > policy?: IPolicy;
230 >
231 > /**
232 > * When specified, this setting is governed by a policy owned by another setting.
233 > * A setting must not declare both `policy` and `policyReference`.
234 > * The type must match the owning setting (enforced when exporting the policy catalog).
235 > */
236 > policyReference?: IPolicyReference;
237 >
238 > /**
239 > * When specified, this setting's default value can always be overwritten by
240 > * an experiment.
241 > */
242 > experiment?: {
243 > /**
244 > * The mode of the experiment.
245 > * - `startup`: The setting value is updated to the experiment value only on startup.
246 > * - `auto`: The setting value is updated to the experiment value automatically (whenever the experiment value changes).
247 > */
248 > mode: 'startup' | 'auto';
249 >
250 > /**
251 > * The name of the experiment. By default, this is `config.${settingId}`
252 > */
253 > name?: string;
254 > };
255 >
256 > /**
257 > * When specified, provides configuration overrides for the Agents window.
258 > */
259 > agentsWindow?: {
260 > /**
261 > * Override default value for this setting in the Agents window.
262 > */
263 > default?: unknown;
264 >
265 > /**
266 > * When `true`, this setting is read-only in the Agents window
267 > * and cannot be changed by the user.
268 > */
269 > readOnly?: boolean;
270 > };
271 > }
272 >
273 > export interface IExtensionInfo {
274 > id: string;
275 > displayName?: string;
276 > }
277 >
278 > export interface IConfigurationNode {
279 > id?: string;
280 > order?: number;
281 > type?: string | string[];
282 > title?: string;
283 > description?: string;
284 > properties?: IStringDictionary<IConfigurationPropertySchema>;
285 > allOf?: IConfigurationNode[];
286 > scope?: ConfigurationScope;
287 > extensionInfo?: IExtensionInfo;
288 > restrictedProperties?: string[];
289 > }
290 >
291 > export type ConfigurationDefaultSource = IExtensionInfo | string;
292 >
293 > export function isConfigurationDefaultSourceEquals(a: ConfigurationDefaultSource | undefined, b: ConfigurationDefaultSource | undefined): boolean {
294 if (a === b) {
295 return true;
303 return a.id === b.id;
304 }
306 > export type ConfigurationDefaultValueSource = ConfigurationDefaultSource | Map<string, ConfigurationDefaultSource>;
307 >
308 > export interface IConfigurationDefaults {
309 > overrides: IStringDictionary<unknown>;
310 > source?: ConfigurationDefaultSource;
311 > donotCache?: boolean;
312 > preventExperimentOverride?: boolean;
313 > }
314 >
315 > export type IRegisteredConfigurationPropertySchema = IConfigurationPropertySchema & {
316 > section?: {
317 > id?: string;
318 > title?: string;
319 > order?: number;
320 > extensionInfo?: IExtensionInfo;
321 > };
322 > defaultDefaultValue?: unknown;
323 > source?: ConfigurationDefaultSource; // Source of the Property
324 > defaultValueSource?: ConfigurationDefaultValueSource; // Source of the Default Value
325 > };
326 >
327 > export interface IConfigurationDefaultOverride {
328 > readonly value: unknown;
329 > readonly source?: ConfigurationDefaultSource; // Source of the default override
330 > }
331 >
332 > export interface IConfigurationDefaultOverrideValue {
333 > readonly value: unknown;
334 > readonly source?: ConfigurationDefaultValueSource;
335 > }
336 >
337 > export const allSettings: { properties: IStringDictionary<IConfigurationPropertySchema>; patternProperties: IStringDictionary<IConfigurationPropertySchema> } = { properties: {}, patternProperties: {} };
338 > export const applicationSettings: { properties: IStringDictionary<IConfigurationPropertySchema>; patternProperties: IStringDictionary<IConfigurationPropertySchema> } = { properties: {}, patternProperties: {} };
339 > export const applicationMachineSettings: { properties: IStringDictionary<IConfigurationPropertySchema>; patternProperties: IStringDictionary<IConfigurationPropertySchema> } = { properties: {}, patternProperties: {} };
340 > export const machineSettings: { properties: IStringDictionary<IConfigurationPropertySchema>; patternProperties: IStringDictionary<IConfigurationPropertySchema> } = { properties: {}, patternProperties: {} };
341 > export const machineOverridableSettings: { properties: IStringDictionary<IConfigurationPropertySchema>; patternProperties: IStringDictionary<IConfigurationPropertySchema> } = { properties: {}, patternProperties: {} };
342 > export const windowSettings: { properties: IStringDictionary<IConfigurationPropertySchema>; patternProperties: IStringDictionary<IConfigurationPropertySchema> } = { properties: {}, patternProperties: {} };
343 > export const resourceSettings: { properties: IStringDictionary<IConfigurationPropertySchema>; patternProperties: IStringDictionary<IConfigurationPropertySchema> } = { properties: {}, patternProperties: {} };
344 >
345 > export const resourceLanguageSettingsSchemaId = 'vscode://schemas/settings/resourceLanguage';
346 > export const configurationDefaultsSchemaId = 'vscode://schemas/settings/configurationDefaults';
347 >
348 > const contributionRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
349 >
350 > class ConfigurationRegistry extends Disposable implements IConfigurationRegistry {
351 >
352 > private readonly registeredConfigurationDefaults: IConfigurationDefaults[] = [];
353 > private readonly configurationDefaultsOverrides: Map<string, { configurationDefaultOverrides: IConfigurationDefaultOverride[]; configurationDefaultOverrideValue?: IConfigurationDefaultOverrideValue }>;
354 > private readonly defaultLanguageConfigurationOverridesNode: IConfigurationNode;
355 > private readonly configurationContributors: IConfigurationNode[];
356 > private readonly configurationProperties: IStringDictionary<IRegisteredConfigurationPropertySchema>;
357 > private readonly policyConfigurations: Map<PolicyName, string>;
358 > private readonly policyReferenceConfigurations: Map<PolicyName, Set<string>>;
359 > private readonly excludedConfigurationProperties: IStringDictionary<IRegisteredConfigurationPropertySchema>;
360 > private readonly resourceLanguageSettingsSchema: IJSONSchema;
361 > private readonly overrideIdentifiers = new Set<string>();
362 >
363 > private readonly _onDidSchemaChange = this._register(new Emitter<void>());
364 > readonly onDidSchemaChange: Event<void> = this._onDidSchemaChange.event;
365 >
366 > private readonly _onDidUpdateConfiguration = this._register(new Emitter<{ properties: ReadonlySet<string>; defaultsOverrides?: boolean }>());
367 > readonly onDidUpdateConfiguration = this._onDidUpdateConfiguration.event;
368 >
369 > constructor() {
370 > super();
371 > this.configurationDefaultsOverrides = new Map();
372 > this.defaultLanguageConfigurationOverridesNode = {
373 > id: 'defaultOverrides',
374 > title: nls.localize('defaultLanguageConfigurationOverrides.title', "Default Language Configuration Overrides"),
375 > properties: {}
376 > };
377 > this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode];
378 > this.resourceLanguageSettingsSchema = {
379 > properties: {},
380 > patternProperties: {},
381 > additionalProperties: true,
382 > allowTrailingCommas: true,
383 > allowComments: true
384 > };
385 > this.configurationProperties = {};
386 > this.policyConfigurations = new Map<PolicyName, string>();
387 > this.policyReferenceConfigurations = new Map<PolicyName, Set<string>>();
388 > this.excludedConfigurationProperties = {};
389 >
390 > contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
391 > this.registerOverridePropertyPatternKey();
392 > }
393 >
394 > public registerConfiguration(configuration: IConfigurationNode, validate: boolean = true): IConfigurationNode {
395 > this.registerConfigurations([configuration], validate); configurationRegistry.ts
396 > return configuration;
397 > }
399 > public registerConfigurations(configurations: IConfigurationNode[], validate: boolean = true): void {
400 > const properties = new Set<string>(); configurationRegistry.ts
401 > this.doRegisterConfigurations(configurations, validate, properties);
402 >
403 > contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
404 > this._onDidSchemaChange.fire();
405 > this._onDidUpdateConfiguration.fire({ properties });
406 > }
408 > public deregisterConfigurations(configurations: IConfigurationNode[]): void {
409 const properties = new Set<string>();
410 this.doDeregisterConfigurations(configurations, properties);
414 this._onDidUpdateConfiguration.fire({ properties });
415 }
417 > public updateConfigurations({ add, remove }: { add: IConfigurationNode[]; remove: IConfigurationNode[] }): void {
418 > const properties = new Set<string>(); configurationRegistry.ts
419 > this.doDeregisterConfigurations(remove, properties);
420 > this.doRegisterConfigurations(add, false, properties);
421 >
422 > contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
423 > this._onDidSchemaChange.fire();
424 > this._onDidUpdateConfiguration.fire({ properties });
425 > }
427 > public registerDefaultConfigurations(configurationDefaults: IConfigurationDefaults[]): void {
428 const properties = new Set<string>();
429 this.doRegisterDefaultConfigurations(configurationDefaults, properties);
431 this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides: true });
432 }
434 > private doRegisterDefaultConfigurations(configurationDefaults: IConfigurationDefaults[], bucket: Set<string>) {
435
436 this.registeredConfigurationDefaults.push(...configurationDefaults);
480 this.doRegisterOverrideIdentifiers(overrideIdentifiers);
481 }
483 > public deregisterDefaultConfigurations(defaultConfigurations: IConfigurationDefaults[]): void {
484 const properties = new Set<string>();
485 this.doDeregisterDefaultConfigurations(defaultConfigurations, properties);
487 this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides: true });
488 }
490 > private doDeregisterDefaultConfigurations(defaultConfigurations: IConfigurationDefaults[], bucket: Set<string>): void {
491 for (const defaultConfiguration of defaultConfigurations) {
492 const index = this.registeredConfigurationDefaults.indexOf(defaultConfiguration);
544 this.updateOverridePropertyPatternKey();
545 }
547 > private updateDefaultOverrideProperty(key: string, newDefaultOverride: IConfigurationDefaultOverrideValue, source: ConfigurationDefaultSource | undefined): void {
548 const property: IRegisteredConfigurationPropertySchema = {
549 section: {
564 this.defaultLanguageConfigurationOverridesNode.properties![key] = property;
565 }
567 > private mergeDefaultConfigurationsForOverrideIdentifier(overrideIdentifier: string, configurationValueObject: IStringDictionary<unknown>, valueSource: ConfigurationDefaultSource | undefined, existingDefaultOverride: IConfigurationDefaultOverrideValue | undefined): IConfigurationDefaultOverrideValue | undefined {
568 const defaultValue = existingDefaultOverride?.value || {};
569 const source = existingDefaultOverride?.source ?? new Map<string, ConfigurationDefaultSource>();
605 return { value: defaultValue, source };
606 }
608 > private mergeDefaultConfigurationsForConfigurationProperty(propertyKey: string, value: unknown, valuesSource: ConfigurationDefaultSource | undefined, existingDefaultOverride: IConfigurationDefaultOverrideValue | undefined): IConfigurationDefaultOverrideValue | undefined {
609 const property = this.configurationProperties[propertyKey];
610 const existingDefaultValue = existingDefaultOverride?.value ?? property?.defaultDefaultValue;
637 return { value, source };
638 }
640 > public deltaConfiguration(delta: IConfigurationDelta): void {
641 // defaults: remove
642 let defaultsOverrides = false;
662 this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides });
663 }
665 > public notifyConfigurationSchemaUpdated(...configurations: IConfigurationNode[]) {
666 this._onDidSchemaChange.fire();
667 }
669 > public registerOverrideIdentifiers(overrideIdentifiers: string[]): void {
670 this.doRegisterOverrideIdentifiers(overrideIdentifiers);
671 this._onDidSchemaChange.fire();
672 }
674 > private doRegisterOverrideIdentifiers(overrideIdentifiers: string[]) {
675 for (const overrideIdentifier of overrideIdentifiers) {
676 this.overrideIdentifiers.add(overrideIdentifier);
678 this.updateOverridePropertyPatternKey();
679 }
681 > private doRegisterConfigurations(configurations: IConfigurationNode[], validate: boolean, bucket: Set<string>): void {
683 > configurations.forEach(configuration => {
684 >
685 > this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties, undefined, bucket);
686 >
687 > this.configurationContributors.push(configuration);
688 > this.registerJSONConfiguration(configuration);
689 > });
690 > }
692 > private doDeregisterConfigurations(configurations: IConfigurationNode[], bucket: Set<string>): void {
694 > const deregisterConfiguration = (configuration: IConfigurationNode) => {
695 if (configuration.properties) {
696 for (const key in configuration.properties) {
715 configuration.allOf?.forEach(node => deregisterConfiguration(node));
716 };
717 > for (const configuration of configurations) { configurationRegistry.ts
718 deregisterConfiguration(configuration);
719 const index = this.configurationContributors.indexOf(configuration);
722 }
723 }
726 > private validateAndRegisterProperties(configuration: IConfigurationNode, validate: boolean = true, extensionInfo: IExtensionInfo | undefined, restrictedProperties: string[] | undefined, scope: ConfigurationScope = ConfigurationScope.WINDOW, bucket: Set<string>): void {
727 > scope = types.isUndefinedOrNull(configuration.scope) ? scope : configuration.scope; configurationRegistry.ts
728 > const properties = configuration.properties;
729 > if (properties) {
730 > for (const key in properties) {
731 > const property: IRegisteredConfigurationPropertySchema = properties[key];
732 > property.section = {
733 > id: configuration.id,
734 > title: configuration.title,
735 > order: configuration.order,
736 > extensionInfo: configuration.extensionInfo
737 > };
738 > if (validate && validateProperty(key, property, extensionInfo?.id)) {
739 delete properties[key];
740 continue;
741 }
743 > property.source = extensionInfo;
744 >
745 > // update default value
746 > property.defaultDefaultValue = properties[key].default;
747 > this.updatePropertyDefaultValue(key, property);
748 >
749 > // update scope
750 > if (OVERRIDE_PROPERTY_REGEX.test(key)) {
751 property.scope = undefined; // No scope for overridable properties `[${identifier}]`
752 > } else { configurationRegistry.ts
753 > property.scope = types.isUndefinedOrNull(property.scope) ? scope : property.scope;
754 > property.restricted = types.isUndefinedOrNull(property.restricted) ? !!restrictedProperties?.includes(key) : property.restricted;
755 > }
756 >
757 > if (property.experiment) {
758 > if (!property.tags?.some(tag => tag.toLowerCase() === 'onexp')) { configurationRegistry.ts
759 > property.tags = property.tags ?? [];
760 > property.tags.push('onExP');
761 > }
762 > } else if (property.tags?.some(tag => tag.toLowerCase() === 'onexp')) { configurationRegistry.ts
763 console.error(`Invalid tag 'onExP' found for property '${key}'. Please use 'experiment' property instead.`);
764 property.experiment = { mode: 'startup' };
765 }
767 > const excluded = properties[key].hasOwnProperty('included') && !properties[key].included;
768 > const policyName = properties[key].policy?.name; configurationRegistry.ts
769 > const policyReferenceName = properties[key].policyReference?.name;
770 >
771 > if (excluded) {
772 this.excludedConfigurationProperties[key] = properties[key];
773 if (policyName) {
780 }
781 delete properties[key];
782 > } else { configurationRegistry.ts
783 > bucket.add(key);
784 > if (policyName) {
785 > this.policyConfigurations.set(policyName, key); configurationRegistry.ts
786 > }
787 > if (policyReferenceName) { configurationRegistry.ts
788 this.addPolicyReferenceConfiguration(policyReferenceName, key);
789 }
790 > this.configurationProperties[key] = properties[key]; configurationRegistry.ts
791 > if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) {
792 // If not set, default deprecationMessage to the markdown source
793 properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
794 }
797 >
798 > }
799 > }
800 > const subNodes = configuration.allOf;
801 > if (subNodes) {
802 for (const node of subNodes) {
803 this.validateAndRegisterProperties(node, validate, extensionInfo, restrictedProperties, scope, bucket);
804 }
805 }
808 > private addPolicyReferenceConfiguration(policyName: PolicyName, key: string): void {
809 let keys = this.policyReferenceConfigurations.get(policyName);
810 if (!keys) {
814 keys.add(key);
815 }
817 > // Only for tests
818 > getConfigurations(): IConfigurationNode[] {
819 return this.configurationContributors;
820 }
822 > getConfigurationProperties(): IStringDictionary<IRegisteredConfigurationPropertySchema> {
823 > return this.configurationProperties; configurationRegistry.ts
824 > }
826 > getPolicyConfigurations(): Map<PolicyName, string> {
827 > return this.policyConfigurations; configurationRegistry.ts
828 > }
830 > getPolicyReferenceConfigurations(): Map<PolicyName, Set<string>> {
831 return this.policyReferenceConfigurations;
832 }
834 > getExcludedConfigurationProperties(): IStringDictionary<IRegisteredConfigurationPropertySchema> {
835 > return this.excludedConfigurationProperties; configurationRegistry.ts
836 > }
838 > getRegisteredDefaultConfigurations(): IConfigurationDefaults[] {
839 return [...this.registeredConfigurationDefaults];
840 }
842 > getConfigurationDefaultsOverrides(): Map<string, IConfigurationDefaultOverrideValue> {
843 const configurationDefaultsOverrides = new Map<string, IConfigurationDefaultOverrideValue>();
844 for (const [key, value] of this.configurationDefaultsOverrides) {
849 return configurationDefaultsOverrides;
850 }
852 > private registerJSONConfiguration(configuration: IConfigurationNode) {
853 > const register = (configuration: IConfigurationNode) => { configurationRegistry.ts
854 > const properties = configuration.properties;
855 > if (properties) {
856 > for (const key in properties) {
857 > this.updateSchema(key, properties[key]); configurationRegistry.ts
858 > }
860 > const subNodes = configuration.allOf;
861 > subNodes?.forEach(register);
862 > };
863 > register(configuration);
864 > }
866 > private updateSchema(key: string, property: IConfigurationPropertySchema): void {
867 > allSettings.properties[key] = property; configurationRegistry.ts
868 > switch (property.scope) {
869 > case ConfigurationScope.APPLICATION:
870 > applicationSettings.properties[key] = property; configurationRegistry.ts
871 > break;
872 > case ConfigurationScope.MACHINE: configurationRegistry.ts
873 > machineSettings.properties[key] = property; configurationRegistry.ts
874 > break;
875 > case ConfigurationScope.APPLICATION_MACHINE: configurationRegistry.ts
876 applicationMachineSettings.properties[key] = property;
877 break;
878 > case ConfigurationScope.MACHINE_OVERRIDABLE: configurationRegistry.ts
879 machineOverridableSettings.properties[key] = property;
880 break;
881 > case ConfigurationScope.WINDOW: configurationRegistry.ts
882 windowSettings.properties[key] = property;
883 break;
884 > case ConfigurationScope.RESOURCE: configurationRegistry.ts
885 resourceSettings.properties[key] = property;
886 break;
887 > case ConfigurationScope.LANGUAGE_OVERRIDABLE: configurationRegistry.ts
888 resourceSettings.properties[key] = property;
889 this.resourceLanguageSettingsSchema.properties![key] = property;
890 break;
892 > }
894 > private removeFromSchema(key: string, property: IConfigurationPropertySchema): void {
895 delete allSettings.properties[key];
896 switch (property.scope) {
917 }
918 }
920 > private updateOverridePropertyPatternKey(): void {
921 for (const overrideIdentifier of this.overrideIdentifiers.values()) {
922 const overrideIdentifierProperty = `[${overrideIdentifier}]`;
937 }
938 }
940 > private registerOverridePropertyPatternKey(): void {
941 > const resourceLanguagePropertiesSchema: IJSONSchema = {
942 > type: 'object',
943 > description: nls.localize('overrideSettings.defaultDescription', "Configure editor settings to be overridden for a language."),
944 > errorMessage: nls.localize('overrideSettings.errorMessage', "This setting does not support per-language configuration."),
945 > $ref: resourceLanguageSettingsSchemaId,
946 > };
947 > allSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
948 > applicationSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
949 > applicationMachineSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
950 > machineSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
951 > machineOverridableSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
952 > windowSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
953 > resourceSettings.patternProperties[OVERRIDE_PROPERTY_PATTERN] = resourceLanguagePropertiesSchema;
954 > this._onDidSchemaChange.fire();
955 > }
956 >
957 > private updatePropertyDefaultValue(key: string, property: IRegisteredConfigurationPropertySchema): void {
958 > const configurationdefaultOverride = this.configurationDefaultsOverrides.get(key)?.configurationDefaultOverrideValue; configurationRegistry.ts
959 > let defaultValue = undefined;
960 > let defaultSource = undefined;
961 > if (configurationdefaultOverride
962 && (!property.disallowConfigurationDefault || !configurationdefaultOverride.source) // Prevent overriding the default value if the property is disallowed to be overridden by configuration defaults from extensions
964 defaultValue = configurationdefaultOverride.value;
965 defaultSource = configurationdefaultOverride.source;
966 }
967 > if (types.isUndefined(defaultValue)) { configurationRegistry.ts
968 > defaultValue = property.defaultDefaultValue; configurationRegistry.ts
969 > defaultSource = undefined;
970 > }
971 > if (types.isUndefined(defaultValue)) { configurationRegistry.ts
972 > defaultValue = getDefaultValue(property.type); configurationRegistry.ts
973 > }
974 > property.default = defaultValue; configurationRegistry.ts
975 > property.defaultValueSource = defaultSource;
976 > }
978 >
979 > const OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`;
980 > const OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, 'g');
981 > export const OVERRIDE_PROPERTY_PATTERN = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`;
982 > export const OVERRIDE_PROPERTY_REGEX = new RegExp(OVERRIDE_PROPERTY_PATTERN);
983 >
984 > export function overrideIdentifiersFromKey(key: string): string[] {
985 const identifiers: string[] = [];
986 if (OVERRIDE_PROPERTY_REGEX.test(key)) {
996 return distinct(identifiers);
997 }
999 > export function keyFromOverrideIdentifiers(overrideIdentifiers: string[]): string {
1000 return overrideIdentifiers.reduce((result, overrideIdentifier) => `${result}[${overrideIdentifier}]`, '');
1001 }
1003 > export function getDefaultValue(type: string | string[] | undefined) {
1004 > const t = Array.isArray(type) ? type[0] : <string>type; configurationRegistry.ts
1005 > switch (t) {
1006 > case 'boolean':
1007 return false;
1008 > case 'integer': configurationRegistry.ts
1009 > case 'number':
1010 return 0;
1011 > case 'string': configurationRegistry.ts
1012 > return ''; configurationRegistry.ts
1013 > case 'array': configurationRegistry.ts
1014 > return []; configurationRegistry.ts
1015 > case 'object': configurationRegistry.ts
1016 return {};
1017 > default: configurationRegistry.ts
1018 return null;
1020 > }
1022 > const configurationRegistry = new ConfigurationRegistry();
1023 > Registry.add(Extensions.Configuration, configurationRegistry);
1024 >
1025 > export function validateProperty(property: string, schema: IRegisteredConfigurationPropertySchema, extensionId?: string): string | null {
1026 > if (!property.trim()) { configurationRegistry.ts
1027 return nls.localize('config.property.empty', "Cannot register an empty property");
1028 }
1029 > if (OVERRIDE_PROPERTY_REGEX.test(property)) { configurationRegistry.ts
1030 return nls.localize('config.property.languageDefault', "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property);
1031 }
1032 > if (configurationRegistry.getConfigurationProperties()[property] !== undefined && (!extensionId || !EXTENSION_UNIFICATION_EXTENSION_IDS.has(extensionId.toLowerCase()))) { configurationRegistry.ts
1033 return nls.localize('config.property.duplicate', "Cannot register '{0}'. This property is already registered.", property);
1034 }
1035 > if (schema.policy && schema.policyReference) { configurationRegistry.ts
1036 return nls.localize('config.policy.bothPolicyAndReference', "Cannot register '{0}'. A setting must not declare both 'policy' and 'policyReference'.", property);
1037 }
1038 > if (schema.policy?.name && configurationRegistry.getPolicyConfigurations().get(schema.policy?.name) !== undefined) { configurationRegistry.ts
1039 return nls.localize('config.policy.duplicate', "Cannot register '{0}'. The associated policy {1} is already registered with {2}. To attach another setting to the same policy, use 'policyReference'.", property, schema.policy?.name, configurationRegistry.getPolicyConfigurations().get(schema.policy?.name));
1040 }
1041 > return null; configurationRegistry.ts
1042 > }
1044 > export function getScopes(): [string, ConfigurationScope | undefined][] {
1045 const scopes: [string, ConfigurationScope | undefined][] = [];
1046 const configurationProperties = configurationRegistry.getConfigurationProperties();
1052 return scopes;
1053 }
1055 > export function getAllConfigurationProperties(configurationNode: IConfigurationNode[]): IStringDictionary<IRegisteredConfigurationPropertySchema> {
1056 const result: IStringDictionary<IRegisteredConfigurationPropertySchema> = {};
1057 for (const configuration of configurationNode) {
1068 return result;
1069 }
1071 > export function parseScope(scope: string): ConfigurationScope {
1072 switch (scope) {
1073 case 'application':
1085 }
1086 }
1088 > // Used for extension unification. Should be removed when complete.
1089 > export const EXTENSION_UNIFICATION_EXTENSION_IDS: Set<string> = new Set(product.defaultChatAgent ? [product.defaultChatAgent.extensionId, product.defaultChatAgent.chatExtensionId].map(id => id.toLowerCase()) : []);
src/vs/platform/userDataSync/common/userDataSync.ts 610 covered LOC · 26 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { distinct } from '../../../base/common/arrays.js';
7 > import { VSBufferReadableStream } from '../../../base/common/buffer.js';
8 > import { IStringDictionary } from '../../../base/common/collections.js';
9 > import { Event } from '../../../base/common/event.js';
10 > import { FormattingOptions } from '../../../base/common/jsonFormatter.js';
11 > import { IJSONSchema } from '../../../base/common/jsonSchema.js';
12 > import { IDisposable } from '../../../base/common/lifecycle.js';
13 > import { IExtUri } from '../../../base/common/resources.js';
14 > import { isObject, isString } from '../../../base/common/types.js';
15 > import { URI } from '../../../base/common/uri.js';
16 > import { IHeaders } from '../../../base/parts/request/common/request.js';
17 > import { localize } from '../../../nls.js';
18 > import { allSettings, ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationRegistry, IRegisteredConfigurationPropertySchema, getAllConfigurationProperties, parseScope } from '../../configuration/common/configurationRegistry.js';
19 > import { IEnvironmentService } from '../../environment/common/environment.js';
20 > import { EXTENSION_IDENTIFIER_PATTERN, IExtensionIdentifier } from '../../extensionManagement/common/extensionManagement.js';
21 > import { IExtensionManifest } from '../../extensions/common/extensions.js';
22 > import { createDecorator } from '../../instantiation/common/instantiation.js';
23 > import { Extensions as JSONExtensions, IJSONContributionRegistry } from '../../jsonschemas/common/jsonContributionRegistry.js';
24 > import { ILogService } from '../../log/common/log.js';
25 > import { Registry } from '../../registry/common/platform.js';
26 > import { StorageScope } from '../../storage/common/storage.js';
27 > import { IUserDataProfile, UseDefaultProfileFlags } from '../../userDataProfile/common/userDataProfile.js';
28 > import { IUserDataSyncMachine } from './userDataSyncMachines.js';
29 >
30 > export function getDisallowedIgnoredSettings(): string[] {
31 > const allSettings = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties(); userDataSync.ts
32 > return Object.keys(allSettings).filter(setting => !!allSettings[setting].disallowSyncIgnore);
33 > }
35 > export function getDefaultIgnoredSettings(excludeExtensions: boolean = false): string[] {
36 > const allSettings = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties(); userDataSync.ts
37 > const ignoredSettings = getIgnoredSettings(allSettings, excludeExtensions);
38 > const disallowedSettings = getDisallowedIgnoredSettings();
39 > return distinct([...ignoredSettings, ...disallowedSettings]);
40 > }
42 > export function getIgnoredSettingsForExtension(manifest: IExtensionManifest): string[] {
43 if (!manifest.contributes?.configuration) {
44 return [];
51 return getIgnoredSettings(properties, false);
52 }
54 > function getIgnoredSettings(properties: IStringDictionary<IRegisteredConfigurationPropertySchema>, excludeExtensions: boolean): string[] { userDataSync.ts
55 > const ignoredSettings = new Set<string>();
56 > for (const key in properties) {
57 > if (excludeExtensions && !!properties[key].source) {
58 continue;
59 }
60 > const scope = isString(properties[key].scope) ? parseScope(properties[key].scope) : properties[key].scope; userDataSync.ts
61 > if (properties[key].ignoreSync
62 > || scope === ConfigurationScope.MACHINE
63 > || scope === ConfigurationScope.MACHINE_OVERRIDABLE
64 > ) {
65 > ignoredSettings.add(key);
66 > }
67 > }
68 > return [...ignoredSettings.values()];
69 > }
71 > export const USER_DATA_SYNC_CONFIGURATION_SCOPE = 'settingsSync';
72 >
73 > export interface IUserDataSyncConfiguration {
74 > keybindingsPerPlatform?: boolean;
75 > ignoredExtensions?: string[];
76 > ignoredSettings?: string[];
77 > }
78 >
79 > export const CONFIG_SYNC_KEYBINDINGS_PER_PLATFORM = 'settingsSync.keybindingsPerPlatform';
80 >
81 > export function registerConfiguration(): IDisposable {
82 > const ignoredSettingsSchemaId = 'vscode://schemas/ignoredSettings'; userDataSync.ts
83 > const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration);
84 > configurationRegistry.registerConfiguration({
85 > id: 'settingsSync',
86 > order: 30,
87 > title: localize('settings sync', "Settings Sync"),
88 > type: 'object',
89 > properties: {
90 > [CONFIG_SYNC_KEYBINDINGS_PER_PLATFORM]: {
91 > type: 'boolean',
92 > description: localize('settingsSync.keybindingsPerPlatform', "Synchronize keybindings for each platform."),
93 > default: true,
94 > scope: ConfigurationScope.APPLICATION,
95 > tags: ['sync', 'usesOnlineServices']
96 > },
97 > 'settingsSync.ignoredExtensions': {
98 > 'type': 'array',
99 > markdownDescription: localize('settingsSync.ignoredExtensions', "List of extensions to be ignored while synchronizing. The identifier of an extension is always `${publisher}.${name}`. For example: `vscode.csharp`."),
100 > items: [{
101 > type: 'string',
102 > pattern: EXTENSION_IDENTIFIER_PATTERN,
103 > errorMessage: localize('app.extension.identifier.errorMessage', "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'.")
104 > }],
105 > 'default': [],
106 > 'scope': ConfigurationScope.APPLICATION,
107 > uniqueItems: true,
108 > disallowSyncIgnore: true,
109 > tags: ['sync', 'usesOnlineServices']
110 > },
111 > 'settingsSync.ignoredSettings': {
112 > 'type': 'array',
113 > description: localize('settingsSync.ignoredSettings', "Configure settings to be ignored while synchronizing."),
114 > 'default': [],
115 > 'scope': ConfigurationScope.APPLICATION,
116 > $ref: ignoredSettingsSchemaId,
117 > additionalProperties: true,
118 > uniqueItems: true,
119 > disallowSyncIgnore: true,
120 > tags: ['sync', 'usesOnlineServices']
121 > }
122 > }
123 > });
124 > const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
125 > const registerIgnoredSettingsSchema = () => {
126 const disallowedIgnoredSettings = getDisallowedIgnoredSettings();
127 const defaultIgnoredSettings = getDefaultIgnoredSettings();
136 jsonRegistry.registerSchema(ignoredSettingsSchemaId, ignoredSettingsSchema);
137 };
138 > return configurationRegistry.onDidUpdateConfiguration(() => registerIgnoredSettingsSchema()); userDataSync.ts
139 > }
141 > // #region User Data Sync Store
142 >
143 > export const NON_EXISTING_RESOURCE_REF = '0';
144 >
145 > export interface IUserData {
146 > ref: string;
147 > content: string | null;
148 > }
149 >
150 > export type IAuthenticationProvider = { id: string; scopes: string[] };
151 >
152 > export interface IUserDataSyncStore {
153 > readonly url: URI;
154 > readonly type: UserDataSyncStoreType;
155 > readonly defaultUrl: URI;
156 > readonly stableUrl: URI;
157 > readonly insidersUrl: URI;
158 > readonly canSwitch: boolean;
159 > readonly authenticationProviders: IAuthenticationProvider[];
160 > }
161 >
162 > export function isAuthenticationProvider(thing: any): thing is IAuthenticationProvider {
163 return thing
164 && isObject(thing)
166 && Array.isArray(thing.scopes);
167 }
169 > export const enum SyncResource {
170 > Settings = 'settings',
171 > Keybindings = 'keybindings',
172 > Snippets = 'snippets',
173 > Prompts = 'prompts',
174 > Tasks = 'tasks',
175 > Mcp = 'mcp',
176 > Extensions = 'extensions',
177 > GlobalState = 'globalState',
178 > Profiles = 'profiles',
179 > WorkspaceState = 'workspaceState',
180 > }
181 > export const ALL_SYNC_RESOURCES: SyncResource[] = [SyncResource.Settings, SyncResource.Keybindings, SyncResource.Snippets, SyncResource.Prompts, SyncResource.Tasks, SyncResource.Extensions, SyncResource.GlobalState, SyncResource.Profiles, SyncResource.Mcp];
182 >
183 > export function getPathSegments(collection: string | undefined, ...paths: string[]): string[] {
184 > return collection ? [collection, ...paths] : paths; userDataSync.ts
185 > }
187 > export function getLastSyncResourceUri(collection: string | undefined, syncResource: SyncResource, environmentService: IEnvironmentService, extUri: IExtUri): URI {
188 > return extUri.joinPath(environmentService.userDataSyncHome, ...getPathSegments(collection, syncResource, `lastSync${syncResource}.json`)); userDataSync.ts
189 > }
191 > export type IUserDataResourceManifest = Record<ServerResource, string>;
192 >
193 > export interface IUserDataCollectionManifest {
194 > [collectionId: string]: {
195 > readonly latest?: IUserDataResourceManifest;
196 > };
197 > }
198 >
199 > export interface IUserDataManifest {
200 > readonly latest?: IUserDataResourceManifest;
201 > readonly session: string;
202 > readonly ref: string;
203 > readonly collections?: IUserDataCollectionManifest;
204 > }
205 >
206 > export function isUserDataManifest(thing: any): thing is IUserDataManifest {
207 > return thing userDataSync.ts
208 && isString(thing.session)
209 && isString(thing.ref)
210 && (isObject(thing.latest) || thing.latest === undefined)
211 && (isObject(thing.collections) || thing.collections === undefined);
212 > } userDataSync.ts
214 > export interface IUserDataSyncActivityData {
215 > resources?: {
216 > [resourceId: string]: { created: number; content: string }[];
217 > };
218 > collections?: {
219 > [collectionId: string]: {
220 > resources?: {
221 > [resourceId: string]: { created: number; content: string }[];
222 > } | undefined;
223 > };
224 > };
225 > }
226 >
227 > export interface IUserDataSyncLatestData {
228 > resources?: IStringDictionary<IUserData>;
229 > collections?: {
230 > [collectionId: string]: {
231 > resources?: IStringDictionary<IUserData>;
232 > };
233 > };
234 > }
235 >
236 > export interface IResourceRefHandle {
237 > ref: string;
238 > created: number;
239 > }
240 >
241 > export type ServerResource = SyncResource | 'machines' | 'editSessions' | 'workspaceState';
242 > export type UserDataSyncStoreType = 'insiders' | 'stable';
243 >
244 > export const IUserDataSyncStoreManagementService = createDecorator<IUserDataSyncStoreManagementService>('IUserDataSyncStoreManagementService');
245 > export interface IUserDataSyncStoreManagementService {
246 > readonly _serviceBrand: undefined;
247 > readonly onDidChangeUserDataSyncStore: Event<void>;
248 > readonly userDataSyncStore: IUserDataSyncStore | undefined;
249 > switch(type: UserDataSyncStoreType): Promise<void>;
250 > getPreviousUserDataSyncStore(): Promise<IUserDataSyncStore | undefined>;
251 > }
252 >
253 > export const IUserDataSyncStoreService = createDecorator<IUserDataSyncStoreService>('IUserDataSyncStoreService');
254 > export interface IUserDataSyncStoreService {
255 > readonly _serviceBrand: undefined;
256 > readonly onDidChangeDonotMakeRequestsUntil: Event<void>;
257 > readonly donotMakeRequestsUntil: Date | undefined;
258 >
259 > readonly onTokenFailed: Event<UserDataSyncErrorCode>;
260 > readonly onTokenSucceed: Event<void>;
261 > setAuthToken(token: string, type: string): void;
262 >
263 > manifest(oldValue: IUserDataManifest | null, headers?: IHeaders): Promise<IUserDataManifest | null>;
264 > readResource(resource: ServerResource, oldValue: IUserData | null, collection?: string, headers?: IHeaders): Promise<IUserData>;
265 > writeResource(resource: ServerResource, content: string, ref: string | null, collection?: string, headers?: IHeaders): Promise<string>;
266 > deleteResource(resource: ServerResource, ref: string | null, collection?: string): Promise<void>;
267 > getAllResourceRefs(resource: ServerResource, collection?: string): Promise<IResourceRefHandle[]>;
268 > resolveResourceContent(resource: ServerResource, ref: string, collection?: string, headers?: IHeaders): Promise<string | null>;
269 >
270 > getAllCollections(headers?: IHeaders): Promise<string[]>;
271 > createCollection(headers?: IHeaders): Promise<string>;
272 > deleteCollection(collection?: string, headers?: IHeaders): Promise<void>;
273 >
274 > getLatestData(headers?: IHeaders): Promise<IUserDataSyncLatestData | null>;
275 > getActivityData(): Promise<VSBufferReadableStream>;
276 >
277 > clear(): Promise<void>;
278 > }
279 >
280 > export const IUserDataSyncLocalStoreService = createDecorator<IUserDataSyncLocalStoreService>('IUserDataSyncLocalStoreService');
281 > export interface IUserDataSyncLocalStoreService {
282 > readonly _serviceBrand: undefined;
283 > writeResource(resource: ServerResource, content: string, cTime: Date, collection?: string, root?: URI): Promise<void>;
284 > getAllResourceRefs(resource: ServerResource, collection?: string, root?: URI): Promise<IResourceRefHandle[]>;
285 > resolveResourceContent(resource: ServerResource, ref: string, collection?: string, root?: URI): Promise<string | null>;
286 > }
287 >
288 > //#endregion
289 >
290 > // #region User Data Sync Headers
291 >
292 > export const HEADER_OPERATION_ID = 'x-operation-id';
293 > export const HEADER_EXECUTION_ID = 'X-Execution-Id';
294 >
295 > export function createSyncHeaders(executionId: string): IHeaders {
296 > const headers: IHeaders = {}; userDataSync.ts
297 > headers[HEADER_EXECUTION_ID] = executionId;
298 > return headers;
299 > }
301 > //#endregion
302 >
303 > // #region User Data Sync Error
304 >
305 > export const enum UserDataSyncErrorCode {
306 > // Client Errors (>= 400 )
307 > Unauthorized = 'Unauthorized', /* 401 */
308 > Forbidden = 'Forbidden', /* 403 */
309 > NotFound = 'NotFound', /* 404 */
310 > MethodNotFound = 'MethodNotFound', /* 405 */
311 > Conflict = 'Conflict', /* 409 */
312 > Gone = 'Gone', /* 410 */
313 > PreconditionFailed = 'PreconditionFailed', /* 412 */
314 > TooLarge = 'TooLarge', /* 413 */
315 > UpgradeRequired = 'UpgradeRequired', /* 426 */
316 > PreconditionRequired = 'PreconditionRequired', /* 428 */
317 > TooManyRequests = 'RemoteTooManyRequests', /* 429 */
318 > TooManyRequestsAndRetryAfter = 'TooManyRequestsAndRetryAfter', /* 429 + Retry-After */
319 >
320 > // Local Errors
321 > RequestFailed = 'RequestFailed',
322 > RequestCanceled = 'RequestCanceled',
323 > RequestTimeout = 'RequestTimeout',
324 > RequestProtocolNotSupported = 'RequestProtocolNotSupported',
325 > RequestPathNotEscaped = 'RequestPathNotEscaped',
326 > RequestHeadersNotObject = 'RequestHeadersNotObject',
327 > NoCollection = 'NoCollection',
328 > NoRef = 'NoRef',
329 > EmptyResponse = 'EmptyResponse',
330 > TurnedOff = 'TurnedOff',
331 > SessionExpired = 'SessionExpired',
332 > ServiceChanged = 'ServiceChanged',
333 > DefaultServiceChanged = 'DefaultServiceChanged',
334 > LocalTooManyProfiles = 'LocalTooManyProfiles',
335 > LocalTooManyRequests = 'LocalTooManyRequests',
336 > LocalPreconditionFailed = 'LocalPreconditionFailed',
337 > LocalInvalidContent = 'LocalInvalidContent',
338 > LocalError = 'LocalError',
339 > IncompatibleLocalContent = 'IncompatibleLocalContent',
340 > IncompatibleRemoteContent = 'IncompatibleRemoteContent',
341 >
342 > Unknown = 'Unknown',
343 > }
344 >
345 > export class UserDataSyncError extends Error {
346 >
347 > constructor(
348 message: string,
349 readonly code: UserDataSyncErrorCode,
354 this.name = `${this.code} (UserDataSyncError) syncResource:${this.resource || 'unknown'} operationId:${this.operationId || 'unknown'}`;
355 }
357 > }
358 >
359 > export class UserDataSyncStoreError extends UserDataSyncError {
360 > constructor(message: string, readonly url: string, code: UserDataSyncErrorCode, readonly serverCode: number | undefined, operationId: string | undefined) {
361 super(message, code, undefined, operationId);
362 }
363 > } userDataSync.ts
364 >
365 > export class UserDataAutoSyncError extends UserDataSyncError {
366 > constructor(message: string, code: UserDataSyncErrorCode) {
367 super(message, code);
368 }
369 > } userDataSync.ts
370 >
371 > export namespace UserDataSyncError {
372 >
373 > export function toUserDataSyncError(error: Error): UserDataSyncError {
374 if (error instanceof UserDataSyncError) {
375 return error;
383 return new UserDataSyncError(error.message, UserDataSyncErrorCode.Unknown);
384 }
386 > }
387 >
388 > //#endregion
389 >
390 > // #region User Data Synchroniser
391 >
392 > export interface ISyncUserDataProfile {
393 > readonly id: string;
394 > readonly collection: string;
395 > readonly name: string;
396 > readonly icon?: string;
397 > readonly useDefaultFlags?: UseDefaultProfileFlags;
398 > }
399 >
400 > export type ISyncExtension = ILocalSyncExtension | IRemoteSyncExtension;
401 >
402 > export interface ILocalSyncExtension {
403 > identifier: IExtensionIdentifier;
404 > pinned: boolean;
405 > version: string;
406 > preRelease: boolean;
407 > disabled?: boolean;
408 > installed?: boolean;
409 > isApplicationScoped?: boolean;
410 > state?: IStringDictionary<any>;
411 > }
412 >
413 > export interface IRemoteSyncExtension {
414 > identifier: IExtensionIdentifier;
415 > version: string;
416 > pinned?: boolean;
417 > preRelease?: boolean;
418 > disabled?: boolean;
419 > installed?: boolean;
420 > isApplicationScoped?: boolean;
421 > state?: IStringDictionary<any>;
422 > }
423 >
424 > export interface IStorageValue {
425 > version: number;
426 > value: string;
427 > scope?: StorageScope;
428 > }
429 >
430 > export interface IGlobalState {
431 > storage: IStringDictionary<IStorageValue>;
432 > }
433 >
434 > export interface IWorkspaceState {
435 > folders: IWorkspaceStateFolder[];
436 > storage: IStringDictionary<string>;
437 > version: number;
438 > }
439 >
440 > export interface IWorkspaceStateFolder {
441 > resourceUri: string;
442 > workspaceFolderIdentity: string;
443 > }
444 >
445 > export const enum SyncStatus {
446 > Uninitialized = 'uninitialized',
447 > Idle = 'idle',
448 > Syncing = 'syncing',
449 > HasConflicts = 'hasConflicts',
450 > }
451 >
452 > export interface ISyncResourceHandle {
453 > created: number;
454 > uri: URI;
455 > }
456 >
457 > export interface IRemoteUserData {
458 > ref: string;
459 > syncData: ISyncData | null;
460 > }
461 >
462 > export interface ISyncData {
463 > version: number;
464 > machineId?: string;
465 > content: string;
466 > }
467 >
468 > export const enum Change {
469 > None,
470 > Added,
471 > Modified,
472 > Deleted,
473 > }
474 >
475 > export const enum MergeState {
476 > Preview = 'preview',
477 > Conflict = 'conflict',
478 > Accepted = 'accepted',
479 > }
480 >
481 > export interface IResourcePreview {
482 > readonly baseResource: URI;
483 > readonly remoteResource: URI;
484 > readonly localResource: URI;
485 > readonly previewResource: URI;
486 > readonly acceptedResource: URI;
487 > readonly localChange: Change;
488 > readonly remoteChange: Change;
489 > readonly mergeState: MergeState;
490 > }
491 >
492 > export interface IUserDataSyncResource {
493 > readonly syncResource: SyncResource;
494 > readonly profile: IUserDataProfile;
495 > }
496 >
497 > export interface IUserDataSyncResourceConflicts extends IUserDataSyncResource {
498 > readonly conflicts: IResourcePreview[];
499 > }
500 >
501 > export interface IUserDataSyncResourcePreview extends IUserDataSyncResource {
502 > readonly isLastSyncFromCurrentMachine: boolean;
503 > readonly resourcePreviews: IResourcePreview[];
504 > }
505 >
506 > export interface IUserDataSyncResourceError extends IUserDataSyncResource {
507 > readonly error: UserDataSyncError;
508 > }
509 >
510 > export interface IUserDataSyncResourceInitializer {
511 > initialize(userData: IUserData): Promise<void>;
512 > }
513 >
514 > export interface IUserDataSynchroniser {
515 >
516 > readonly resource: SyncResource;
517 > readonly status: SyncStatus;
518 > readonly onDidChangeStatus: Event<SyncStatus>;
519 >
520 > readonly conflicts: IUserDataSyncResourceConflicts;
521 > readonly onDidChangeConflicts: Event<IUserDataSyncResourceConflicts>;
522 >
523 > readonly onDidChangeLocal: Event<void>;
524 >
525 > sync(refOrUserData: string | IUserData | null, preview: boolean, userDataSyncConfiguration: IUserDataSyncConfiguration, headers: IHeaders): Promise<IUserDataSyncResourcePreview | null>;
526 > accept(resource: URI, content?: string | null): Promise<IUserDataSyncResourcePreview | null>;
527 > apply(force: boolean, headers: IHeaders): Promise<IUserDataSyncResourcePreview | null>;
528 > stop(): Promise<void>;
529 >
530 > hasPreviouslySynced(): Promise<boolean>;
531 > hasLocalData(): Promise<boolean>;
532 > resetLocal(): Promise<void>;
533 >
534 > resolveContent(resource: URI): Promise<string | null>;
535 > replace(content: string): Promise<boolean>;
536 > }
537 >
538 > //#endregion
539 >
540 > // #region keys synced only in web
541 >
542 > export const SYNC_SERVICE_URL_TYPE = 'sync.store.url.type';
543 > export function getEnablementKey(resource: SyncResource) { return `sync.enable.${resource}`; }
544 >
545 > // #endregion
546 >
547 > // #region User Data Sync Services
548 > export const IUserDataSyncEnablementService = createDecorator<IUserDataSyncEnablementService>('IUserDataSyncEnablementService');
549 > export interface IUserDataSyncEnablementService {
550 > _serviceBrand: undefined;
551 >
552 > readonly onDidChangeEnablement: Event<boolean>;
553 > isEnabled(): boolean;
554 > canToggleEnablement(): boolean;
555 > setEnablement(enabled: boolean): void;
556 >
557 > readonly onDidChangeResourceEnablement: Event<[SyncResource, boolean]>;
558 > isResourceEnabled(resource: SyncResource, defaultValue?: boolean): boolean;
559 > setResourceEnablement(resource: SyncResource, enabled: boolean): void;
560 >
561 > getResourceSyncStateVersion(resource: SyncResource): string | undefined;
562 >
563 > /**
564 > * Checks if resource enabled was explicitly configured before,
565 > * ignoring its default enablement value used in {@link isResourceEnabled}.
566 > */
567 > isResourceEnablementConfigured(resource: SyncResource): boolean;
568 > }
569 >
570 > export interface IUserDataSyncTask {
571 > readonly manifest: IUserDataManifest | null;
572 > run(): Promise<void>;
573 > stop(): Promise<void>;
574 > }
575 >
576 > export interface IUserDataManualSyncTask {
577 > readonly id: string;
578 > merge(): Promise<void>;
579 > apply(): Promise<void>;
580 > stop(): Promise<void>;
581 > }
582 >
583 > export const IUserDataSyncService = createDecorator<IUserDataSyncService>('IUserDataSyncService');
584 > export interface IUserDataSyncService {
585 > _serviceBrand: undefined;
586 >
587 > readonly status: SyncStatus;
588 > readonly onDidChangeStatus: Event<SyncStatus>;
589 >
590 > readonly conflicts: IUserDataSyncResourceConflicts[];
591 > readonly onDidChangeConflicts: Event<IUserDataSyncResourceConflicts[]>;
592 >
593 > readonly onDidChangeLocal: Event<SyncResource>;
594 > readonly onSyncErrors: Event<IUserDataSyncResourceError[]>;
595 >
596 > readonly lastSyncTime: number | undefined;
597 > readonly onDidChangeLastSyncTime: Event<number>;
598 >
599 > readonly onDidResetRemote: Event<void>;
600 > readonly onDidResetLocal: Event<void>;
601 >
602 > createSyncTask(manifest: IUserDataManifest | null, disableCache?: boolean): Promise<IUserDataSyncTask>;
603 > createManualSyncTask(): Promise<IUserDataManualSyncTask>;
604 > resolveContent(resource: URI): Promise<string | null>;
605 > accept(syncResource: IUserDataSyncResource, resource: URI, content: string | null | undefined, apply: boolean | { force: boolean }): Promise<void>;
606 >
607 > reset(): Promise<void>;
608 > resetRemote(): Promise<void>;
609 > cleanUpRemoteData(): Promise<void>;
610 > resetLocal(): Promise<void>;
611 > hasLocalData(): Promise<boolean>;
612 > hasPreviouslySynced(): Promise<boolean>;
613 >
614 > replace(syncResourceHandle: ISyncResourceHandle): Promise<void>;
615 >
616 > saveRemoteActivityData(location: URI): Promise<void>;
617 > extractActivityData(activityDataResource: URI, location: URI): Promise<void>;
618 > }
619 >
620 > export const IUserDataSyncResourceProviderService = createDecorator<IUserDataSyncResourceProviderService>('IUserDataSyncResourceProviderService');
621 > export interface IUserDataSyncResourceProviderService {
622 > _serviceBrand: undefined;
623 > getRemoteSyncedProfiles(): Promise<ISyncUserDataProfile[]>;
624 > getLocalSyncedProfiles(location?: URI): Promise<ISyncUserDataProfile[]>;
625 > getRemoteSyncResourceHandles(syncResource: SyncResource, profile?: ISyncUserDataProfile): Promise<ISyncResourceHandle[]>;
626 > getLocalSyncResourceHandles(syncResource: SyncResource, profile?: ISyncUserDataProfile, location?: URI): Promise<ISyncResourceHandle[]>;
627 > getAssociatedResources(syncResourceHandle: ISyncResourceHandle): Promise<{ resource: URI; comparableResource: URI }[]>;
628 > getMachineId(syncResourceHandle: ISyncResourceHandle): Promise<string | undefined>;
629 > getLocalSyncedMachines(location?: URI): Promise<IUserDataSyncMachine[]>;
630 > resolveContent(resource: URI): Promise<string | null>;
631 > resolveUserDataSyncResource(syncResourceHandle: ISyncResourceHandle): IUserDataSyncResource | undefined;
632 > }
633 >
634 > export type SyncOptions = { immediately?: boolean; skipIfSyncedRecently?: boolean; disableCache?: boolean };
635 >
636 > export const IUserDataAutoSyncService = createDecorator<IUserDataAutoSyncService>('IUserDataAutoSyncService');
637 > export interface IUserDataAutoSyncService {
638 > _serviceBrand: undefined;
639 > readonly onError: Event<UserDataSyncError>;
640 > turnOn(): Promise<void>;
641 > turnOff(everywhere: boolean): Promise<void>;
642 > triggerSync(sources: string[], options?: SyncOptions): Promise<void>;
643 > }
644 >
645 > export const IUserDataSyncUtilService = createDecorator<IUserDataSyncUtilService>('IUserDataSyncUtilService');
646 > export interface IUserDataSyncUtilService {
647 > readonly _serviceBrand: undefined;
648 > resolveUserBindings(userbindings: string[]): Promise<IStringDictionary<string>>;
649 > resolveFormattingOptions(resource: URI): Promise<FormattingOptions>;
650 > resolveDefaultCoreIgnoredSettings(): Promise<string[]>;
651 > }
652 >
653 > export const IUserDataSyncLogService = createDecorator<IUserDataSyncLogService>('IUserDataSyncLogService');
654 > export interface IUserDataSyncLogService extends ILogService { }
655 >
656 > export interface IConflictSetting {
657 > key: string;
658 > localValue: any | undefined;
659 > remoteValue: any | undefined;
660 > }
661 >
662 > //#endregion
663 >
664 > export const USER_DATA_SYNC_LOG_ID = 'userDataSync';
665 > export const USER_DATA_SYNC_SCHEME = 'vscode-userdata-sync';
666 > export const PREVIEW_DIR_NAME = 'preview';
src/vs/platform/storage/common/storage.ts 609 covered LOC · 88 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- storage.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Promises, RunOnceScheduler, runWhenGlobalIdle } from '../../../base/common/async.js';
7 > import { Emitter, Event, PauseableEmitter } from '../../../base/common/event.js';
8 > import { Disposable, DisposableStore, dispose, MutableDisposable } from '../../../base/common/lifecycle.js';
9 > import { mark } from '../../../base/common/performance.js';
10 > import { isUndefinedOrNull } from '../../../base/common/types.js';
11 > import { InMemoryStorageDatabase, IStorage, IStorageChangeEvent, Storage, StorageHint, StorageValue } from '../../../base/parts/storage/common/storage.js';
12 > import { createDecorator } from '../../instantiation/common/instantiation.js';
13 > import { isUserDataProfile, IUserDataProfile } from '../../userDataProfile/common/userDataProfile.js';
14 > import { IAnyWorkspaceIdentifier } from '../../workspace/common/workspace.js';
15 >
16 > export const IS_NEW_KEY = '__$__isNewStorageMarker';
17 > export const TARGET_KEY = '__$__targetStorageMarker';
18 >
19 > export const IStorageService = createDecorator<IStorageService>('storageService');
20 >
21 > export enum WillSaveStateReason {
22 >
23 > /**
24 > * No specific reason to save state.
25 > */
26 > NONE,
27 >
28 > /**
29 > * A hint that the workbench is about to shutdown.
30 > */
31 > SHUTDOWN
32 > }
33 >
34 > export interface IWillSaveStateEvent {
35 > readonly reason: WillSaveStateReason;
36 > }
37 >
38 > export interface IStorageEntry {
39 > readonly key: string;
40 > readonly value: StorageValue;
41 > readonly scope: StorageScope;
42 > readonly target: StorageTarget;
43 > }
44 >
45 > export interface IWorkspaceStorageValueChangeEvent extends IStorageValueChangeEvent {
46 > readonly scope: StorageScope.WORKSPACE;
47 > }
48 >
49 > export interface IProfileStorageValueChangeEvent extends IStorageValueChangeEvent {
50 > readonly scope: StorageScope.PROFILE;
51 > }
52 >
53 > export interface IApplicationStorageValueChangeEvent extends IStorageValueChangeEvent {
54 > readonly scope: StorageScope.APPLICATION;
55 > }
56 >
57 > export interface IApplicationSharedStorageValueChangeEvent extends IStorageValueChangeEvent {
58 > readonly scope: StorageScope.APPLICATION_SHARED;
59 > }
60 >
61 > export interface IStorageService {
62 >
63 > readonly _serviceBrand: undefined;
64 >
65 > /**
66 > * Emitted whenever data is updated or deleted on the given
67 > * scope and optional key.
68 > *
69 > * @param scope the `StorageScope` to listen to changes
70 > * @param key the optional key to filter for or all keys of
71 > * the scope if `undefined`
72 > */
73 > onDidChangeValue(scope: StorageScope.WORKSPACE, key: string | undefined, disposable: DisposableStore): Event<IWorkspaceStorageValueChangeEvent>;
74 > onDidChangeValue(scope: StorageScope.PROFILE, key: string | undefined, disposable: DisposableStore): Event<IProfileStorageValueChangeEvent>;
75 > onDidChangeValue(scope: StorageScope.APPLICATION, key: string | undefined, disposable: DisposableStore): Event<IApplicationStorageValueChangeEvent>;
76 > onDidChangeValue(scope: StorageScope.APPLICATION_SHARED, key: string | undefined, disposable: DisposableStore): Event<IApplicationSharedStorageValueChangeEvent>;
77 > onDidChangeValue(scope: StorageScope, key: string | undefined, disposable: DisposableStore): Event<IStorageValueChangeEvent>;
78 >
79 > /**
80 > * Emitted whenever target of a storage entry changes.
81 > */
82 > readonly onDidChangeTarget: Event<IStorageTargetChangeEvent>;
83 >
84 > /**
85 > * Emitted when the storage is about to persist. This is the right time
86 > * to persist data to ensure it is stored before the application shuts
87 > * down.
88 > *
89 > * The will save state event allows to optionally ask for the reason of
90 > * saving the state, e.g. to find out if the state is saved due to a
91 > * shutdown.
92 > *
93 > * Note: this event may be fired many times, not only on shutdown to prevent
94 > * loss of state in situations where the shutdown is not sufficient to
95 > * persist the data properly.
96 > */
97 > readonly onWillSaveState: Event<IWillSaveStateEvent>;
98 >
99 > /**
100 > * Retrieve an element stored with the given key from storage. Use
101 > * the provided `defaultValue` if the element is `null` or `undefined`.
102 > *
103 > * @param scope allows to define the scope of the storage operation
104 > * to either the current workspace only, all workspaces or all profiles.
105 > */
106 > get(key: string, scope: StorageScope, fallbackValue: string): string;
107 > get(key: string, scope: StorageScope, fallbackValue?: string): string | undefined;
108 >
109 > /**
110 > * Retrieve an element stored with the given key from storage. Use
111 > * the provided `defaultValue` if the element is `null` or `undefined`.
112 > * The element will be converted to a `boolean`.
113 > *
114 > * @param scope allows to define the scope of the storage operation
115 > * to either the current workspace only, all workspaces or all profiles.
116 > */
117 > getBoolean(key: string, scope: StorageScope, fallbackValue: boolean): boolean;
118 > getBoolean(key: string, scope: StorageScope, fallbackValue?: boolean): boolean | undefined;
119 >
120 > /**
121 > * Retrieve an element stored with the given key from storage. Use
122 > * the provided `defaultValue` if the element is `null` or `undefined`.
123 > * The element will be converted to a `number` using `parseInt` with a
124 > * base of `10`.
125 > *
126 > * @param scope allows to define the scope of the storage operation
127 > * to either the current workspace only, all workspaces or all profiles.
128 > */
129 > getNumber(key: string, scope: StorageScope, fallbackValue: number): number;
130 > getNumber(key: string, scope: StorageScope, fallbackValue?: number): number | undefined;
131 >
132 > /**
133 > * Retrieve an element stored with the given key from storage. Use
134 > * the provided `defaultValue` if the element is `null` or `undefined`.
135 > * The element will be converted to a `object` using `JSON.parse`.
136 > *
137 > * @param scope allows to define the scope of the storage operation
138 > * to either the current workspace only, all workspaces or all profiles.
139 > */
140 > getObject<T extends object>(key: string, scope: StorageScope, fallbackValue: T): T;
141 > getObject<T extends object>(key: string, scope: StorageScope, fallbackValue?: T): T | undefined;
142 >
143 > /**
144 > * Store a value under the given key to storage. The value will be
145 > * converted to a `string`. Storing either `undefined` or `null` will
146 > * remove the entry under the key.
147 > *
148 > * @param scope allows to define the scope of the storage operation
149 > * to either the current workspace only, all workspaces or all profiles.
150 > *
151 > * @param target allows to define the target of the storage operation
152 > * to either the current machine or user.
153 > */
154 > store(key: string, value: StorageValue, scope: StorageScope, target: StorageTarget): void;
155 >
156 > /**
157 > * Allows to store multiple values in a bulk operation. Events will only
158 > * be emitted when all values have been stored.
159 > *
160 > * @param external a hint to indicate the source of the operation is external,
161 > * such as settings sync or profile changes.
162 > */
163 > storeAll(entries: Array<IStorageEntry>, external: boolean): void;
164 >
165 > /**
166 > * Delete an element stored under the provided key from storage.
167 > *
168 > * The scope argument allows to define the scope of the storage
169 > * operation to either the current workspace only, all workspaces
170 > * or all profiles.
171 > */
172 > remove(key: string, scope: StorageScope): void;
173 >
174 > /**
175 > * Returns all the keys used in the storage for the provided `scope`
176 > * and `target`.
177 > *
178 > * Note: this will NOT return all keys stored in the storage layer.
179 > * Some keys may not have an associated `StorageTarget` and thus
180 > * will be excluded from the results.
181 > *
182 > * @param scope allows to define the scope for the keys
183 > * to either the current workspace only, all workspaces or all profiles.
184 > *
185 > * @param target allows to define the target for the keys
186 > * to either the current machine or user.
187 > */
188 > keys(scope: StorageScope, target: StorageTarget): string[];
189 >
190 > /**
191 > * Log the contents of the storage to the console.
192 > */
193 > log(): void;
194 >
195 > /**
196 > * Returns true if the storage service handles the provided scope.
197 > */
198 > hasScope(scope: IAnyWorkspaceIdentifier | IUserDataProfile): boolean;
199 >
200 > /**
201 > * Switch storage to another workspace or profile. Optionally preserve the
202 > * current data to the new storage.
203 > */
204 > switch(to: IAnyWorkspaceIdentifier | IUserDataProfile, preserveData: boolean): Promise<void>;
205 >
206 > /**
207 > * Whether the storage for the given scope was created during this session or
208 > * existed before.
209 > */
210 > isNew(scope: StorageScope): boolean;
211 >
212 > /**
213 > * Attempts to reduce the DB size via optimization commands if supported.
214 > */
215 > optimize(scope: StorageScope): Promise<void>;
216 >
217 > /**
218 > * Allows to flush state, e.g. in cases where a shutdown is
219 > * imminent. This will send out the `onWillSaveState` to ask
220 > * everyone for latest state.
221 > *
222 > * @returns a `Promise` that can be awaited on when all updates
223 > * to the underlying storage have been flushed.
224 > */
225 > flush(reason?: WillSaveStateReason): Promise<void>;
226 > }
227 >
228 > export const enum StorageScope {
229 >
230 > /**
231 > * The stored data will be scoped to all workspaces across all profiles
232 > * and shared across VS Code and Sessions app.
233 > */
234 > APPLICATION_SHARED = -2,
235 >
236 > /**
237 > * The stored data will be scoped to all workspaces across all profiles.
238 > */
239 > APPLICATION = -1,
240 >
241 > /**
242 > * The stored data will be scoped to all workspaces of the same profile.
243 > */
244 > PROFILE = 0,
245 >
246 > /**
247 > * The stored data will be scoped to the current workspace.
248 > */
249 > WORKSPACE = 1
250 > }
251 >
252 > export const enum StorageTarget {
253 >
254 > /**
255 > * The stored data is user specific and applies across machines.
256 > */
257 > USER,
258 >
259 > /**
260 > * The stored data is machine specific.
261 > */
262 > MACHINE
263 > }
264 >
265 > export interface IStorageValueChangeEvent {
266 >
267 > /**
268 > * The scope for the storage entry that changed
269 > * or was removed.
270 > */
271 > readonly scope: StorageScope;
272 >
273 > /**
274 > * The `key` of the storage entry that was changed
275 > * or was removed.
276 > */
277 > readonly key: string;
278 >
279 > /**
280 > * The `target` can be `undefined` if a key is being
281 > * removed.
282 > */
283 > readonly target: StorageTarget | undefined;
284 >
285 > /**
286 > * A hint how the storage change event was triggered. If
287 > * `true`, the storage change was triggered by an external
288 > * source, such as:
289 > * - another process (for example another window)
290 > * - operations such as settings sync or profiles change
291 > */
292 > readonly external?: boolean;
293 > }
294 >
295 > export interface IStorageTargetChangeEvent {
296 >
297 > /**
298 > * The scope for the target that changed. Listeners
299 > * should use `keys(scope, target)` to get an updated
300 > * list of keys for the given `scope` and `target`.
301 > */
302 > readonly scope: StorageScope;
303 > }
304 >
305 > interface IKeyTargets {
306 > [key: string]: StorageTarget;
307 > }
308 >
309 > export interface IStorageServiceOptions {
310 > readonly flushInterval: number;
311 > }
312 >
313 > export function loadKeyTargets(storage: IStorage): IKeyTargets {
314 > const keysRaw = storage.get(TARGET_KEY); storage.ts
315 > if (keysRaw) {
316 > try { storage.ts
317 > return JSON.parse(keysRaw);
318 > } catch (error) {
319 // Fail gracefully
320 }
321 > } storage.ts
322 > storage.ts
323 > return Object.create(null);
324 > }
325 > storage.ts
326 > export abstract class AbstractStorageService extends Disposable implements IStorageService {
327 >
328 > declare readonly _serviceBrand: undefined;
329 >
330 > private static DEFAULT_FLUSH_INTERVAL = 60 * 1000; // every minute
331 >
332 > private readonly _onDidChangeValue = this._register(new PauseableEmitter<IStorageValueChangeEvent>());
333 >
334 > private readonly _onDidChangeTarget = this._register(new PauseableEmitter<IStorageTargetChangeEvent>());
335 > readonly onDidChangeTarget = this._onDidChangeTarget.event;
336 >
337 > private readonly _onWillSaveState = this._register(new Emitter<IWillSaveStateEvent>());
338 > readonly onWillSaveState = this._onWillSaveState.event;
339 >
340 > private initializationPromise: Promise<void> | undefined;
341 >
342 > private readonly flushWhenIdleScheduler: RunOnceScheduler;
343 > private readonly runFlushWhenIdle = this._register(new MutableDisposable());
344 >
345 > constructor(options: IStorageServiceOptions = { flushInterval: AbstractStorageService.DEFAULT_FLUSH_INTERVAL }) {
346 > super(); storage.ts
347 >
348 > this.flushWhenIdleScheduler = this._register(new RunOnceScheduler(() => this.doFlushWhenIdle(), options.flushInterval));
349 > }
350 > storage.ts
351 > onDidChangeValue(scope: StorageScope.WORKSPACE, key: string | undefined, disposable: DisposableStore): Event<IWorkspaceStorageValueChangeEvent>;
352 > onDidChangeValue(scope: StorageScope.PROFILE, key: string | undefined, disposable: DisposableStore): Event<IProfileStorageValueChangeEvent>;
353 > onDidChangeValue(scope: StorageScope.APPLICATION, key: string | undefined, disposable: DisposableStore): Event<IApplicationStorageValueChangeEvent>;
354 > onDidChangeValue(scope: StorageScope.APPLICATION_SHARED, key: string | undefined, disposable: DisposableStore): Event<IApplicationSharedStorageValueChangeEvent>;
355 > onDidChangeValue(scope: StorageScope, key: string | undefined, disposable: DisposableStore): Event<IStorageValueChangeEvent> {
356 > return Event.filter(this._onDidChangeValue.event, e => e.scope === scope && (key === undefined || e.key === key), disposable); storage.ts
357 > }
358 > storage.ts
359 > private doFlushWhenIdle(): void {
360 this.runFlushWhenIdle.value = runWhenGlobalIdle(() => {
361 if (this.shouldFlushWhenIdle()) {
367 });
368 }
369 > storage.ts
370 > protected shouldFlushWhenIdle(): boolean {
371 return true;
372 }
373 > storage.ts
374 > protected stopFlushWhenIdle(): void {
375 dispose([this.runFlushWhenIdle, this.flushWhenIdleScheduler]);
376 }
377 > storage.ts
378 > initialize(): Promise<void> {
379 if (!this.initializationPromise) {
380 this.initializationPromise = (async () => {
402 return this.initializationPromise;
403 }
404 > storage.ts
405 > protected emitDidChangeValue(scope: StorageScope, event: IStorageChangeEvent): void {
406 > const { key, external } = event; storage.ts
407 >
408 > // Specially handle `TARGET_KEY`
409 > if (key === TARGET_KEY) {
410 >
411 > // Clear our cached version which is now out of date
412 > switch (scope) {
413 > case StorageScope.APPLICATION_SHARED:
414 this._applicationSharedKeyTargets = undefined;
415 break;
416 > case StorageScope.APPLICATION: storage.ts
417 > this._applicationKeyTargets = undefined; storage.ts
418 > break;
419 > case StorageScope.PROFILE: storage.ts
420 this._profileKeyTargets = undefined;
421 break;
422 > case StorageScope.WORKSPACE: storage.ts
423 this._workspaceKeyTargets = undefined;
424 break;
425 > } storage.ts
426 >
427 > // Emit as `didChangeTarget` event
428 > this._onDidChangeTarget.fire({ scope });
429 > }
430 >
431 > // Emit any other key to outside
432 > else {
433 > this._onDidChangeValue.fire({ scope, key, target: this.getKeyTargets(scope)[key], external });
434 > }
435 > }
436 > storage.ts
437 > protected emitWillSaveState(reason: WillSaveStateReason): void {
438 this._onWillSaveState.fire({ reason });
439 }
440 > storage.ts
441 > get(key: string, scope: StorageScope, fallbackValue: string): string;
442 > get(key: string, scope: StorageScope): string | undefined;
443 > get(key: string, scope: StorageScope, fallbackValue?: string): string | undefined {
444 > return this.getStorage(scope)?.get(key, fallbackValue); storage.ts
445 > }
446 > storage.ts
447 > getBoolean(key: string, scope: StorageScope, fallbackValue: boolean): boolean;
448 > getBoolean(key: string, scope: StorageScope): boolean | undefined;
449 > getBoolean(key: string, scope: StorageScope, fallbackValue?: boolean): boolean | undefined {
450 > return this.getStorage(scope)?.getBoolean(key, fallbackValue); storage.ts
451 > }
452 > storage.ts
453 > getNumber(key: string, scope: StorageScope, fallbackValue: number): number;
454 > getNumber(key: string, scope: StorageScope): number | undefined;
455 > getNumber(key: string, scope: StorageScope, fallbackValue?: number): number | undefined {
456 > return this.getStorage(scope)?.getNumber(key, fallbackValue); storage.ts
457 > }
458 > storage.ts
459 > getObject(key: string, scope: StorageScope, fallbackValue: object): object;
460 > getObject(key: string, scope: StorageScope): object | undefined;
461 > getObject(key: string, scope: StorageScope, fallbackValue?: object): object | undefined {
462 return this.getStorage(scope)?.getObject(key, fallbackValue);
463 }
464 > storage.ts
465 > storeAll(entries: Array<IStorageEntry>, external: boolean): void {
466 this.withPausedEmitters(() => {
467 for (const entry of entries) {
470 });
471 }
472 > storage.ts
473 > store(key: string, value: StorageValue, scope: StorageScope, target: StorageTarget, external = false): void {
474 > storage.ts
475 > // We remove the key for undefined/null values
476 > if (isUndefinedOrNull(value)) {
477 this.remove(key, scope, external);
478 return;
479 }
480 > storage.ts
481 > // Update our datastructures but send events only after
482 > this.withPausedEmitters(() => {
483 >
484 > // Update key-target map
485 > this.updateKeyTarget(key, scope, target);
486 >
487 > // Store actual value
488 > this.getStorage(scope)?.set(key, value, external);
489 > });
490 > }
491 > storage.ts
492 > remove(key: string, scope: StorageScope, external = false): void {
493 > storage.ts
494 > // Update our datastructures but send events only after
495 > this.withPausedEmitters(() => {
496 >
497 > // Update key-target map
498 > this.updateKeyTarget(key, scope, undefined);
499 >
500 > // Remove actual key
501 > this.getStorage(scope)?.delete(key, external);
502 > });
503 > }
504 > storage.ts
505 > private withPausedEmitters(fn: Function): void {
506 > storage.ts
507 > // Pause emitters
508 > this._onDidChangeValue.pause();
509 > this._onDidChangeTarget.pause();
510 >
511 > try {
512 > fn();
513 > } finally {
514 >
515 > // Resume emitters
516 > this._onDidChangeValue.resume();
517 > this._onDidChangeTarget.resume();
518 > }
519 > }
520 > storage.ts
521 > keys(scope: StorageScope, target: StorageTarget): string[] {
522 > const keys: string[] = []; storage.ts
523 >
524 > const keyTargets = this.getKeyTargets(scope);
525 > for (const key of Object.keys(keyTargets)) {
526 const keyTarget = keyTargets[key];
527 if (keyTarget === target) {
529 }
530 }
531 > storage.ts
532 > return keys;
533 > }
534 > storage.ts
535 > private updateKeyTarget(key: string, scope: StorageScope, target: StorageTarget | undefined, external = false): void {
536 > storage.ts
537 > // Add
538 > const keyTargets = this.getKeyTargets(scope);
539 > if (typeof target === 'number') {
540 > if (keyTargets[key] !== target) {
541 > keyTargets[key] = target;
542 > this.getStorage(scope)?.set(TARGET_KEY, JSON.stringify(keyTargets), external);
543 > }
544 > }
545 > storage.ts
546 > // Remove
547 > else {
548 > if (typeof keyTargets[key] === 'number') {
549 > delete keyTargets[key]; storage.ts
550 > this.getStorage(scope)?.set(TARGET_KEY, JSON.stringify(keyTargets), external);
551 > }
552 > } storage.ts
553 > } storage.ts
554 > storage.ts
555 > private _workspaceKeyTargets: IKeyTargets | undefined = undefined;
556 > private get workspaceKeyTargets(): IKeyTargets {
557 if (!this._workspaceKeyTargets) {
558 this._workspaceKeyTargets = this.loadKeyTargets(StorageScope.WORKSPACE);
561 return this._workspaceKeyTargets;
562 }
563 > storage.ts
564 > private _profileKeyTargets: IKeyTargets | undefined = undefined;
565 > private get profileKeyTargets(): IKeyTargets {
566 > if (!this._profileKeyTargets) { storage.ts
567 > this._profileKeyTargets = this.loadKeyTargets(StorageScope.PROFILE);
568 > }
569 >
570 > return this._profileKeyTargets;
571 > }
572 > storage.ts
573 > private _applicationKeyTargets: IKeyTargets | undefined = undefined;
574 > private get applicationKeyTargets(): IKeyTargets {
575 > if (!this._applicationKeyTargets) { storage.ts
576 > this._applicationKeyTargets = this.loadKeyTargets(StorageScope.APPLICATION);
577 > }
578 >
579 > return this._applicationKeyTargets;
580 > }
581 > storage.ts
582 > private _applicationSharedKeyTargets: IKeyTargets | undefined = undefined;
583 > private get applicationSharedKeyTargets(): IKeyTargets {
584 > if (!this._applicationSharedKeyTargets) { storage.ts
585 > this._applicationSharedKeyTargets = this.loadKeyTargets(StorageScope.APPLICATION_SHARED);
586 > }
587 >
588 > return this._applicationSharedKeyTargets;
589 > }
590 > storage.ts
591 > private getKeyTargets(scope: StorageScope): IKeyTargets {
592 > switch (scope) { storage.ts
593 > case StorageScope.APPLICATION_SHARED:
594 > return this.applicationSharedKeyTargets; storage.ts
595 > case StorageScope.APPLICATION: storage.ts
596 > return this.applicationKeyTargets; storage.ts
597 > case StorageScope.PROFILE: storage.ts
598 > return this.profileKeyTargets; storage.ts
599 > default: storage.ts
600 return this.workspaceKeyTargets;
601 > } storage.ts
602 > }
603 > storage.ts
604 > private loadKeyTargets(scope: StorageScope): { [key: string]: StorageTarget } {
605 > const storage = this.getStorage(scope); storage.ts
606 >
607 > return storage ? loadKeyTargets(storage) : Object.create(null);
608 > }
609 > storage.ts
610 > isNew(scope: StorageScope): boolean {
611 return this.getBoolean(IS_NEW_KEY, scope) === true;
612 }
613 > storage.ts
614 > async flush(reason = WillSaveStateReason.NONE): Promise<void> {
615
616 // Signal event to collect changes
646 }
647 }
648 > storage.ts
649 > async log(): Promise<void> {
650 const applicationItems = this.getStorage(StorageScope.APPLICATION)?.items ?? new Map<string, string>();
651 const applicationSharedItems = this.getStorage(StorageScope.APPLICATION_SHARED)?.items ?? new Map<string, string>();
664 );
665 }
666 > storage.ts
667 > async optimize(scope: StorageScope): Promise<void> {
668
669 // Await pending data to be flushed to the DB
673 return this.getStorage(scope)?.optimize();
674 }
675 > storage.ts
676 > async switch(to: IAnyWorkspaceIdentifier | IUserDataProfile, preserveData: boolean): Promise<void> {
677
678 // Signal as event so that clients can store data before we switch
685 return this.switchToWorkspace(to, preserveData);
686 }
687 > storage.ts
688 > protected canSwitchProfile(from: IUserDataProfile, to: IUserDataProfile): boolean {
689 if (from.id === to.id) {
690 return false; // both profiles are same
697 return true;
698 }
699 > storage.ts
700 > protected switchData(oldStorage: Map<string, string>, newStorage: IStorage, scope: StorageScope): void {
701 this.withPausedEmitters(() => {
702 // Signal storage keys that have changed
718 });
719 }
720 > storage.ts
721 > // --- abstract
722 >
723 > abstract hasScope(scope: IAnyWorkspaceIdentifier | IUserDataProfile): boolean;
724 >
725 > protected abstract doInitialize(): Promise<void>;
726 >
727 > protected abstract getStorage(scope: StorageScope): IStorage | undefined;
728 >
729 > protected abstract getLogDetails(scope: StorageScope): string | undefined;
730 >
731 > protected abstract switchToProfile(toProfile: IUserDataProfile, preserveData: boolean): Promise<void>;
732 > protected abstract switchToWorkspace(toWorkspace: IAnyWorkspaceIdentifier | IUserDataProfile, preserveData: boolean): Promise<void>;
733 > }
734 >
735 > export function isProfileUsingDefaultStorage(profile: IUserDataProfile): boolean {
736 return profile.isDefault || !!profile.useDefaultFlags?.globalState;
737 }
738 > storage.ts
739 > export class InMemoryStorageService extends AbstractStorageService {
740 >
741 > private readonly applicationStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
742 > private readonly applicationSharedStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
743 > private readonly profileStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
744 > private readonly workspaceStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
745 >
746 > constructor() {
747 > super(); storage.ts
748 >
749 > this._register(this.workspaceStorage.onDidChangeStorage(e => this.emitDidChangeValue(StorageScope.WORKSPACE, e)));
750 > this._register(this.profileStorage.onDidChangeStorage(e => this.emitDidChangeValue(StorageScope.PROFILE, e)));
751 > this._register(this.applicationStorage.onDidChangeStorage(e => this.emitDidChangeValue(StorageScope.APPLICATION, e)));
752 > this._register(this.applicationSharedStorage.onDidChangeStorage(e => this.emitDidChangeValue(StorageScope.APPLICATION_SHARED, e)));
753 > }
754 > storage.ts
755 > protected getStorage(scope: StorageScope): IStorage {
756 > switch (scope) { storage.ts
757 > case StorageScope.APPLICATION_SHARED:
758 > return this.applicationSharedStorage; storage.ts
759 > case StorageScope.APPLICATION: storage.ts
760 > return this.applicationStorage; storage.ts
761 > case StorageScope.PROFILE: storage.ts
762 > return this.profileStorage; storage.ts
763 > default: storage.ts
764 return this.workspaceStorage;
765 > } storage.ts
766 > }
767 > storage.ts
768 > protected getLogDetails(scope: StorageScope): string | undefined {
769 switch (scope) {
770 case StorageScope.APPLICATION_SHARED:
778 }
779 }
780 > storage.ts
781 > protected async doInitialize(): Promise<void> { }
782 >
783 > protected async switchToProfile(): Promise<void> {
784 // no-op when in-memory
785 }
786 > storage.ts
787 > protected async switchToWorkspace(): Promise<void> {
788 // no-op when in-memory
789 }
790 > storage.ts
791 > protected override shouldFlushWhenIdle(): boolean {
792 return false;
793 }
794 > storage.ts
795 > hasScope(scope: IAnyWorkspaceIdentifier | IUserDataProfile): boolean {
796 return false;
797 }
798 > } storage.ts
799 >
800 export async function logStorage(application: Map<string, string>, applicationShared: Map<string, string>, profile: Map<string, string>, workspace: Map<string, string>, applicationPath: string, applicationSharedPath: string, profilePath: string, workspacePath: string): Promise<void> {
801 const safeParse = (value: string) => {
src/vs/base/common/lifecycle.ts 603 covered LOC · 144 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- lifecycle.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { compareBy, numberComparator } from './arrays.js';
7 > import { groupBy } from './collections.js';
8 > import { SetMap, ResourceMap } from './map.js';
9 > import { URI } from './uri.js';
10 > import { createSingleCallFunction } from './functional.js';
11 > import { Iterable } from './iterator.js';
12 > import { BugIndicatingError, onUnexpectedError } from './errors.js';
13 >
14 > // #region Disposable Tracking
15 >
16 > /**
17 > * Enables logging of potentially leaked disposables.
18 > *
19 > * A disposable is considered leaked if it is not disposed or not registered as the child of
20 > * another disposable. This tracking is very simple an only works for classes that either
21 > * extend Disposable or use a DisposableStore. This means there are a lot of false positives.
22 > */
23 > const TRACK_DISPOSABLES = false;
24 > let disposableTracker: IDisposableTracker | null = null;
25 >
26 > export interface IDisposableTracker {
27 > /**
28 > * Is called on construction of a disposable.
29 > */
30 > trackDisposable(disposable: IDisposable): void;
31 >
32 > /**
33 > * Is called when a disposable is registered as child of another disposable (e.g. {@link DisposableStore}).
34 > * If parent is `null`, the disposable is removed from its former parent.
35 > */
36 > setParent(child: IDisposable, parent: IDisposable | null): void;
37 >
38 > /**
39 > * Is called after a disposable is disposed.
40 > */
41 > markAsDisposed(disposable: IDisposable): void;
42 >
43 > /**
44 > * Indicates that the given object is a singleton which does not need to be disposed.
45 > */
46 > markAsSingleton(disposable: IDisposable): void;
47 > }
48 >
49 > export class GCBasedDisposableTracker implements IDisposableTracker {
50
51 private readonly _registry = new FinalizationRegistry<string>(heldValue => {
52 console.warn(`[LEAKED DISPOSABLE] ${heldValue}`);
53 });
55 > trackDisposable(disposable: IDisposable): void {
56 const stack = new Error('CREATED via:').stack!;
57 this._registry.register(disposable, stack, disposable);
58 }
60 > setParent(child: IDisposable, parent: IDisposable | null): void {
61 if (parent) {
62 this._registry.unregister(child);
65 }
66 }
68 > markAsDisposed(disposable: IDisposable): void {
69 this._registry.unregister(disposable);
70 }
72 > markAsSingleton(disposable: IDisposable): void {
73 this._registry.unregister(disposable);
74 }
75 > } lifecycle.ts
76 >
77 > export interface DisposableInfo {
78 > value: IDisposable;
79 > source: string | null;
80 > parent: IDisposable | null;
81 > isSingleton: boolean;
82 > idx: number;
83 > }
84 >
85 > export class DisposableTracker implements IDisposableTracker {
86 > private static idx = 0; lifecycle.ts
87 >
88 > private readonly livingDisposables = new Map<IDisposable, DisposableInfo>();
90 > private getDisposableData(d: IDisposable): DisposableInfo {
91 > let val = this.livingDisposables.get(d); lifecycle.ts
92 > if (!val) {
93 > val = { parent: null, source: null, isSingleton: false, value: d, idx: DisposableTracker.idx++ };
94 > this.livingDisposables.set(d, val);
95 > }
96 > return val;
97 > }
99 > trackDisposable(d: IDisposable): void {
100 > const data = this.getDisposableData(d); lifecycle.ts
101 > if (!data.source) {
102 > data.source =
103 > new Error().stack!;
104 > }
105 > }
106 > lifecycle.ts
107 > setParent(child: IDisposable, parent: IDisposable | null): void {
108 > const data = this.getDisposableData(child); lifecycle.ts
109 > data.parent = parent;
110 > }
111 > lifecycle.ts
112 > markAsDisposed(x: IDisposable): void {
113 > this.livingDisposables.delete(x); lifecycle.ts
114 > }
115 > lifecycle.ts
116 > markAsSingleton(disposable: IDisposable): void {
117 this.getDisposableData(disposable).isSingleton = true;
118 }
119 > lifecycle.ts
120 > private getRootParent(data: DisposableInfo, cache: Map<DisposableInfo, DisposableInfo>): DisposableInfo {
121 const cacheValue = cache.get(data);
122 if (cacheValue) {
128 return result;
129 }
130 > lifecycle.ts
131 > getTrackedDisposables(): IDisposable[] {
132 const rootParentCache = new Map<DisposableInfo, DisposableInfo>();
133
138 return leaking;
139 }
140 > lifecycle.ts
141 > computeLeakingDisposables(maxReported = 10, preComputedLeaks?: DisposableInfo[]): { leaks: DisposableInfo[]; details: string } | undefined {
142 > let uncoveredLeakingObjs: DisposableInfo[] | undefined; lifecycle.ts
143 > if (preComputedLeaks) {
144 uncoveredLeakingObjs = preComputedLeaks;
145 > } else { lifecycle.ts
146 > const rootParentCache = new Map<DisposableInfo, DisposableInfo>();
147 >
148 > const leakingObjects = [...this.livingDisposables.values()]
149 > .filter((info) => info.source !== null && !this.getRootParent(info, rootParentCache).isSingleton);
150 >
151 > if (leakingObjects.length === 0) {
152 > return; lifecycle.ts
153 > }
154 const leakingObjsSet = new Set(leakingObjects.map(o => o.value));
155
162 throw new Error('There are cyclic diposable chains!');
163 }
164 > } lifecycle.ts
165
166 if (!uncoveredLeakingObjs) {
224
225 return { leaks: uncoveredLeakingObjs, details: message };
226 > } lifecycle.ts
227 > } lifecycle.ts
228 >
229 > export function setDisposableTracker(tracker: IDisposableTracker | null): void {
230 > disposableTracker = tracker; lifecycle.ts
231 > }
232 > lifecycle.ts
233 > if (TRACK_DISPOSABLES) {
234 const __is_disposable_tracked__ = '__is_disposable_tracked__';
235 setDisposableTracker(new class implements IDisposableTracker {
268 });
269 }
270 > lifecycle.ts
271 > export function trackDisposable<T extends IDisposable>(x: T): T {
272 > disposableTracker?.trackDisposable(x); lifecycle.ts
273 > return x;
274 > }
275 > lifecycle.ts
276 > export function markAsDisposed(disposable: IDisposable): void {
277 > disposableTracker?.markAsDisposed(disposable); lifecycle.ts
278 > }
279 > lifecycle.ts
280 > function setParentOfDisposable(child: IDisposable, parent: IDisposable | null): void { lifecycle.ts
281 > disposableTracker?.setParent(child, parent);
282 > }
283 > lifecycle.ts
284 > function setParentOfDisposables(children: IDisposable[], parent: IDisposable | null): void { lifecycle.ts
285 > if (!disposableTracker) {
286 return;
287 }
288 > for (const child of children) { lifecycle.ts
289 > disposableTracker.setParent(child, parent);
290 > }
291 > }
292 > lifecycle.ts
293 > /**
294 > * Indicates that the given object is a singleton which does not need to be disposed.
295 > */
296 > export function markAsSingleton<T extends IDisposable>(singleton: T): T {
297 disposableTracker?.markAsSingleton(singleton);
298 return singleton;
299 }
300 > lifecycle.ts
301 > // #endregion
302 >
303 > /**
304 > * An object that performs a cleanup operation when `.dispose()` is called.
305 > *
306 > * Some examples of how disposables are used:
307 > *
308 > * - An event listener that removes itself when `.dispose()` is called.
309 > * - A resource such as a file system watcher that cleans up the resource when `.dispose()` is called.
310 > * - The return value from registering a provider. When `.dispose()` is called, the provider is unregistered.
311 > */
312 > export interface IDisposable {
313 > dispose(): void;
314 > }
315 >
316 > /**
317 > * Check if `thing` is {@link IDisposable disposable}.
318 > */
319 > export function isDisposable<E>(thing: E): thing is E & IDisposable {
320 // eslint-disable-next-line local/code-no-any-casts
321 return typeof thing === 'object' && thing !== null && typeof (<IDisposable><any>thing).dispose === 'function' && (<IDisposable><any>thing).dispose.length === 0;
322 }
323 > lifecycle.ts
324 > /**
325 > * Disposes of the value(s) passed in.
326 > */
327 > export function dispose<T extends IDisposable>(disposable: T): T;
328 > export function dispose<T extends IDisposable>(disposable: T | undefined): T | undefined;
329 > export function dispose<T extends IDisposable, A extends Iterable<T> = Iterable<T>>(disposables: A): A;
330 > export function dispose<T extends IDisposable>(disposables: Array<T>): Array<T>;
331 > export function dispose<T extends IDisposable>(disposables: ReadonlyArray<T>): ReadonlyArray<T>;
332 > export function dispose<T extends IDisposable>(arg: T | Iterable<T> | undefined): any {
333 > if (Iterable.is(arg)) { lifecycle.ts
334 > const errors: any[] = []; lifecycle.ts
335 >
336 > for (const d of arg) {
337 > if (d) { lifecycle.ts
338 > try {
339 > d.dispose();
340 > } catch (e) {
341 errors.push(e);
342 }
343 > } lifecycle.ts
344 > }
345 > lifecycle.ts
346 > if (errors.length === 1) {
347 throw errors[0];
348 > } else if (errors.length > 1) { lifecycle.ts
349 throw new AggregateError(errors, 'Encountered errors while disposing of store');
350 }
351 > lifecycle.ts
352 > return Array.isArray(arg) ? [] : arg; lifecycle.ts
353 > } else if (arg) { lifecycle.ts
354 > arg.dispose(); lifecycle.ts
355 > return arg;
356 > }
357 > } lifecycle.ts
358 > lifecycle.ts
359 > export function disposeIfDisposable<T extends IDisposable | object>(disposables: Array<T>): Array<T> {
360 for (const d of disposables) {
361 if (isDisposable(d)) {
365 return [];
366 }
367 > lifecycle.ts
368 > /**
369 > * Combine multiple disposable values into a single {@link IDisposable}.
370 > */
371 > export function combinedDisposable(...disposables: IDisposable[]): IDisposable {
372 > const parent = toDisposable(() => dispose(disposables)); lifecycle.ts
373 > setParentOfDisposables(disposables, parent);
374 > return parent;
375 > }
376 > lifecycle.ts
377 > class FunctionDisposable implements IDisposable {
378 > private _isDisposed: boolean;
379 > private readonly _fn: () => void;
380 >
381 > constructor(fn: () => void) {
382 > this._isDisposed = false; lifecycle.ts
383 > this._fn = fn;
384 > trackDisposable(this);
385 > }
386 > lifecycle.ts
387 > dispose() {
388 > if (this._isDisposed) { lifecycle.ts
389 > return; lifecycle.ts
390 > }
391 > if (!this._fn) { lifecycle.ts
392 throw new Error(`Unbound disposable context: Need to use an arrow function to preserve the value of this`);
393 }
394 > this._isDisposed = true; lifecycle.ts
395 > markAsDisposed(this);
396 > this._fn();
397 > }
398 > } lifecycle.ts
399 >
400 > /**
401 > * Turn a function that implements dispose into an {@link IDisposable}.
402 > *
403 > * @param fn Clean up function, guaranteed to be called only **once**.
404 > */
405 > export function toDisposable(fn: () => void): IDisposable {
406 > return new FunctionDisposable(fn); lifecycle.ts
407 > }
408 > lifecycle.ts
409 > /**
410 > * Manages a collection of disposable values.
411 > *
412 > * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an
413 > * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a
414 > * store that has already been disposed of.
415 > */
416 > export class DisposableStore implements IDisposable {
417 >
418 > static DISABLE_DISPOSED_WARNING = false;
419 >
420 > private readonly _toDispose = new Set<IDisposable>();
421 > private _isDisposed = false;
422 >
423 > constructor() {
424 > trackDisposable(this); lifecycle.ts
425 > }
426 > lifecycle.ts
427 > /**
428 > * Dispose of all registered disposables and mark this object as disposed.
429 > *
430 > * Any future disposables added to this object will be disposed of on `add`.
431 > */
432 > public dispose(): void {
433 > if (this._isDisposed) { lifecycle.ts
434 return;
435 }
436 > lifecycle.ts
437 > markAsDisposed(this);
438 > this._isDisposed = true;
439 > this.clear();
440 > }
441 > lifecycle.ts
442 > /**
443 > * @return `true` if this object has been disposed of.
444 > */
445 > public get isDisposed(): boolean {
446 return this._isDisposed;
447 }
448 > lifecycle.ts
449 > /**
450 > * Dispose of all registered disposables but do not mark this object as disposed.
451 > */
452 > public clear(): void {
453 > if (this._toDispose.size === 0) { lifecycle.ts
454 > return; lifecycle.ts
455 > }
456 > lifecycle.ts
457 > try {
458 > dispose(this._toDispose);
459 > } finally {
460 > this._toDispose.clear();
461 > }
462 > } lifecycle.ts
463 > lifecycle.ts
464 > /**
465 > * Add a new {@link IDisposable disposable} to the collection.
466 > */
467 > public add<T extends IDisposable>(o: T): T {
468 > if (!o || o === Disposable.None) { lifecycle.ts
469 > return o; lifecycle.ts
470 > }
471 > if ((o as unknown as DisposableStore) === this) { lifecycle.ts
472 throw new Error('Cannot register a disposable on itself!');
473 }
474 > lifecycle.ts
475 > setParentOfDisposable(o, this);
476 > if (this._isDisposed) {
477 if (!DisposableStore.DISABLE_DISPOSED_WARNING) {
478 console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack);
479 }
480 > } else { lifecycle.ts
481 > this._toDispose.add(o);
482 > }
483 >
484 > return o;
485 > } lifecycle.ts
486 > lifecycle.ts
487 > /**
488 > * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the
489 > * disposable even when the disposable is not part in the store.
490 > */
491 > public delete<T extends IDisposable>(o: T): void {
492 if (!o) {
493 return;
499 o.dispose();
500 }
501 > lifecycle.ts
502 > /**
503 > * Deletes the value from the store, but does not dispose it.
504 > */
505 > public deleteAndLeak<T extends IDisposable>(o: T): void {
506 if (!o) {
507 return;
511 }
512 }
513 > lifecycle.ts
514 > public assertNotDisposed(): void {
515 if (this._isDisposed) {
516 onUnexpectedError(new BugIndicatingError('Object disposed'));
517 }
518 }
519 > } lifecycle.ts
520 >
521 > /**
522 > * Abstract base class for a {@link IDisposable disposable} object.
523 > *
524 > * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of.
525 > */
526 > export abstract class Disposable implements IDisposable {
527 >
528 > /**
529 > * A disposable that does nothing when it is disposed of.
530 > *
531 > * TODO: This should not be a static property.
532 > */
533 > static readonly None = Object.freeze<IDisposable>({ dispose() { } });
534 >
535 > protected readonly _store = new DisposableStore();
536 >
537 > constructor() {
538 > trackDisposable(this); lifecycle.ts
539 > setParentOfDisposable(this._store, this);
540 > }
541 > lifecycle.ts
542 > public dispose(): void {
543 > markAsDisposed(this); lifecycle.ts
544 >
545 > this._store.dispose();
546 > }
547 > lifecycle.ts
548 > /**
549 > * Adds `o` to the collection of disposables managed by this object.
550 > */
551 > protected _register<T extends IDisposable>(o: T): T {
552 > if ((o as unknown as Disposable) === this) { lifecycle.ts
553 throw new Error('Cannot register a disposable on itself!');
554 }
555 > return this._store.add(o); lifecycle.ts
556 > }
557 > } lifecycle.ts
558 >
559 > /**
560 > * Manages the lifecycle of a disposable value that may be changed.
561 > *
562 > * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can
563 > * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up.
564 > */
565 > export class MutableDisposable<T extends IDisposable> implements IDisposable {
566 > private _value?: T;
567 > private _isDisposed = false;
568 >
569 > constructor() {
570 > trackDisposable(this); lifecycle.ts
571 > }
572 > lifecycle.ts
573 > /**
574 > * Get the currently held disposable value, or `undefined` if this MutableDisposable has been disposed
575 > */
576 > get value(): T | undefined {
577 return this._isDisposed ? undefined : this._value;
578 }
579 > lifecycle.ts
580 > /**
581 > * Set a new disposable value.
582 > *
583 > * Behaviour:
584 > * - If the MutableDisposable has been disposed, the setter is a no-op.
585 > * - If the new value is strictly equal to the current value, the setter is a no-op.
586 > * - Otherwise the previous value (if any) is disposed and the new value is stored.
587 > *
588 > * Related helpers:
589 > * - clear() resets the value to `undefined` (and disposes the previous value).
590 > * - clearAndLeak() returns the old value without disposing it and removes its parent.
591 > */
592 > set value(value: T | undefined) {
593 if (this._isDisposed || value === this._value) {
594 return;
601 this._value = value;
602 }
603 > lifecycle.ts
604 > /**
605 > * Resets the stored value and disposed of the previously stored value.
606 > */
607 > clear(): void {
608 this.value = undefined;
609 }
610 > lifecycle.ts
611 > dispose(): void {
612 > this._isDisposed = true; lifecycle.ts
613 > markAsDisposed(this);
614 > this._value?.dispose();
615 > this._value = undefined;
616 > }
617 > lifecycle.ts
618 > /**
619 > * Clears the value, but does not dispose it.
620 > * The old value is returned.
621 > */
622 > clearAndLeak(): T | undefined {
623 const oldValue = this._value;
624 this._value = undefined;
628 return oldValue;
629 }
630 > } lifecycle.ts
631 >
632 > /**
633 > * Manages the lifecycle of a disposable value that may be changed like {@link MutableDisposable}, but the value must
634 > * exist and cannot be undefined.
635 > */
636 > export class MandatoryMutableDisposable<T extends IDisposable> implements IDisposable {
637 > private readonly _disposable = new MutableDisposable<T>();
638 > private _isDisposed = false;
639 >
640 > constructor(initialValue: T) {
641 this._disposable.value = initialValue;
642 }
643 > lifecycle.ts
644 > get value(): T {
645 return this._disposable.value!;
646 }
647 > lifecycle.ts
648 > set value(value: T) {
649 if (this._isDisposed || value === this._disposable.value) {
650 return;
652 this._disposable.value = value;
653 }
654 > lifecycle.ts
655 > dispose() {
656 this._isDisposed = true;
657 this._disposable.dispose();
658 }
659 > } lifecycle.ts
660 >
661 > export class RefCountedDisposable {
662 >
663 > private _counter: number = 1;
664 >
665 > constructor(
666 private readonly _disposable: IDisposable,
667 ) { }
668 > lifecycle.ts
669 > acquire() {
670 this._counter++;
671 return this;
672 }
673 > lifecycle.ts
674 > release() {
675 if (--this._counter === 0) {
676 this._disposable.dispose();
678 return this;
679 }
680 > } lifecycle.ts
681 >
682 > export interface IReference<T> extends IDisposable {
683 > readonly object: T;
684 > }
685 >
686 > export abstract class ReferenceCollection<T> {
687
688 private readonly references: Map<string, { readonly object: T; counter: number }> = new Map();
689 > lifecycle.ts
690 > acquire(key: string, ...args: unknown[]): IReference<T> {
691 let reference = this.references.get(key);
692
708 return { object, dispose };
709 }
710 > lifecycle.ts
711 > protected abstract createReferencedObject(key: string, ...args: unknown[]): T;
712 > protected abstract destroyReferencedObject(key: string, object: T): void;
713 > }
714 >
715 > /**
716 > * Unwraps a reference collection of promised values. Makes sure
717 > * references are disposed whenever promises get rejected.
718 > */
719 > export class AsyncReferenceCollection<T> {
720 >
721 > constructor(private referenceCollection: ReferenceCollection<Promise<T>>) { }
722 >
723 > async acquire(key: string, ...args: unknown[]): Promise<IReference<T>> {
724 const ref = this.referenceCollection.acquire(key, ...args);
725
736 }
737 }
738 > } lifecycle.ts
739 >
740 > export class ImmortalReference<T> implements IReference<T> {
741 > constructor(public object: T) { }
742 > dispose(): void { /* noop */ }
743 > }
744 >
745 > export function disposeOnReturn(fn: (store: DisposableStore) => void): void {
746 const store = new DisposableStore();
747 try {
751 }
752 }
753 > lifecycle.ts
754 > /**
755 > * A map the manages the lifecycle of the values that it stores.
756 > */
757 > export class DisposableMap<K, V extends IDisposable = IDisposable> implements IDisposable {
758 >
759 > private readonly _store: Map<K, V>;
760 > private _isDisposed = false;
761 >
762 > constructor(store: Map<K, V> = new Map<K, V>()) {
763 > this._store = store; lifecycle.ts
764 > trackDisposable(this);
765 > }
766 > lifecycle.ts
767 > /**
768 > * Disposes of all stored values and mark this object as disposed.
769 > *
770 > * Trying to use this object after it has been disposed of is an error.
771 > */
772 > dispose(): void {
773 > markAsDisposed(this); lifecycle.ts
774 > this._isDisposed = true;
775 > this.clearAndDisposeAll();
776 > }
777 > lifecycle.ts
778 > /**
779 > * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.
780 > */
781 > clearAndDisposeAll(): void {
782 > if (!this._store.size) { lifecycle.ts
783 > return; lifecycle.ts
784 > }
785
786 try {
789 this._store.clear();
790 }
791 > } lifecycle.ts
792 > lifecycle.ts
793 > has(key: K): boolean {
794 return this._store.has(key);
795 }
796 > lifecycle.ts
797 > get size(): number {
798 > return this._store.size; lifecycle.ts
799 > }
800 > lifecycle.ts
801 > get(key: K): V | undefined {
802 return this._store.get(key);
803 }
804 > lifecycle.ts
805 > set(key: K, value: V, skipDisposeOnOverwrite = false): void {
806 > if (this._isDisposed) { lifecycle.ts
807 console.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack);
808 }
809 > lifecycle.ts
810 > if (!skipDisposeOnOverwrite) {
811 > this._store.get(key)?.dispose();
812 > }
813 >
814 > this._store.set(key, value);
815 > setParentOfDisposable(value, this);
816 > }
817 > lifecycle.ts
818 > /**
819 > * Delete the value stored for `key` from this map and also dispose of it.
820 > */
821 > deleteAndDispose(key: K): void {
822 > this._store.get(key)?.dispose(); lifecycle.ts
823 > this._store.delete(key);
824 > }
825 > lifecycle.ts
826 > /**
827 > * Delete the value stored for `key` from this map but return it. The caller is
828 > * responsible for disposing of the value.
829 > */
830 > deleteAndLeak(key: K): V | undefined {
831 const value = this._store.get(key);
832 if (value) {
836 return value;
837 }
838 > lifecycle.ts
839 > keys(): IterableIterator<K> {
840 return this._store.keys();
841 }
842 > lifecycle.ts
843 > values(): IterableIterator<V> {
844 return this._store.values();
845 }
846 > lifecycle.ts
847 > [Symbol.iterator](): IterableIterator<[K, V]> {
848 return this._store[Symbol.iterator]();
849 }
850 > } lifecycle.ts
851 >
852 > /**
853 > * A set that manages the lifecycle of the values that it stores.
854 > */
855 > export class DisposableSet<V extends IDisposable = IDisposable> implements IDisposable {
856 >
857 > private readonly _store: Set<V>;
858 > private _isDisposed = false;
859 >
860 > constructor(store: Set<V> = new Set<V>()) {
861 this._store = store;
862 trackDisposable(this);
863 }
864 > lifecycle.ts
865 > /**
866 > * Disposes of all stored values and mark this object as disposed.
867 > *
868 > * Trying to use this object after it has been disposed of is an error.
869 > */
870 > dispose(): void {
871 markAsDisposed(this);
872 this._isDisposed = true;
873 this.clearAndDisposeAll();
874 }
875 > lifecycle.ts
876 > /**
877 > * Disposes of all stored values and clear the set, but DO NOT mark this object as disposed.
878 > */
879 > clearAndDisposeAll(): void {
880 if (!this._store.size) {
881 return;
888 }
889 }
890 > lifecycle.ts
891 > has(value: V): boolean {
892 return this._store.has(value);
893 }
894 > lifecycle.ts
895 > get size(): number {
896 return this._store.size;
897 }
898 > lifecycle.ts
899 > add(value: V): void {
900 if (this._isDisposed) {
901 console.warn(new Error('Trying to add a disposable to a DisposableSet that has already been disposed of. The added object will be leaked!').stack);
905 setParentOfDisposable(value, this);
906 }
907 > lifecycle.ts
908 > /**
909 > * Delete the value from this set and also dispose of it.
910 > */
911 > deleteAndDispose(value: V): void {
912 if (this._store.delete(value)) {
913 value.dispose();
914 }
915 }
916 > lifecycle.ts
917 > /**
918 > * Delete the value from this set but return it. The caller is
919 > * responsible for disposing of the value.
920 > */
921 > deleteAndLeak(value: V): V | undefined {
922 if (this._store.delete(value)) {
923 setParentOfDisposable(value, null);
926 return undefined;
927 }
928 > lifecycle.ts
929 > values(): IterableIterator<V> {
930 return this._store.values();
931 }
932 > lifecycle.ts
933 > [Symbol.iterator](): IterableIterator<V> {
934 return this._store[Symbol.iterator]();
935 }
936 > } lifecycle.ts
937 >
938 > /**
939 > * Call `then` on a Promise, unless the returned disposable is disposed.
940 > */
941 > export function thenIfNotDisposed<T>(promise: Promise<T>, then: (result: T) => void): IDisposable {
942 let disposed = false;
943 promise.then(result => {
951 });
952 }
953 > lifecycle.ts
954 > /**
955 > * Call `then` on a promise that resolves to a {@link IDisposable}, then either register the
956 > * disposable or register it to the {@link DisposableStore}, depending on whether the store is
957 > * disposed or not.
958 > */
959 > export function thenRegisterOrDispose<T extends IDisposable>(promise: Promise<T>, store: DisposableStore): Promise<T> {
960 return promise.then(disposable => {
961 if (store.isDisposed) {
967 });
968 }
969 > lifecycle.ts
970 > export class DisposableResourceMap<V extends IDisposable = IDisposable> extends DisposableMap<URI, V> {
971 > constructor() {
972 super(new ResourceMap());
973 }
974 > } lifecycle.ts
src/vs/platform/userDataSync/common/abstractSynchronizer.ts 548 covered LOC · 136 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- abstractSynchronizer.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { equals } from '../../../base/common/arrays.js';
7 > import { CancelablePromise, createCancelablePromise, ThrottledDelayer } from '../../../base/common/async.js';
8 > import { VSBuffer } from '../../../base/common/buffer.js';
9 > import { CancellationToken } from '../../../base/common/cancellation.js';
10 > import { IStringDictionary } from '../../../base/common/collections.js';
11 > import { Emitter, Event } from '../../../base/common/event.js';
12 > import { parse, ParseError } from '../../../base/common/json.js';
13 > import { FormattingOptions } from '../../../base/common/jsonFormatter.js';
14 > import { Disposable } from '../../../base/common/lifecycle.js';
15 > import { IExtUri } from '../../../base/common/resources.js';
16 > import { uppercaseFirstLetter } from '../../../base/common/strings.js';
17 > import { isString, isUndefined } from '../../../base/common/types.js';
18 > import { URI } from '../../../base/common/uri.js';
19 > import { IHeaders } from '../../../base/parts/request/common/request.js';
20 > import { localize } from '../../../nls.js';
21 > import { IConfigurationService } from '../../configuration/common/configuration.js';
22 > import { IEnvironmentService } from '../../environment/common/environment.js';
23 > import { FileChangesEvent, FileOperationError, FileOperationResult, IFileContent, IFileService, toFileOperationResult } from '../../files/common/files.js';
24 > import { ILogService } from '../../log/common/log.js';
25 > import { getServiceMachineId } from '../../externalServices/common/serviceMachineId.js';
26 > import { IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
27 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
28 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
29 > import {
30 > Change, getLastSyncResourceUri, IRemoteUserData, IResourcePreview as IBaseResourcePreview, ISyncData,
31 > IUserDataSyncResourcePreview as IBaseSyncResourcePreview, IUserData, IUserDataSyncResourceInitializer, IUserDataSyncLocalStoreService,
32 > IUserDataSyncConfiguration, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService,
33 > IUserDataSyncUtilService, MergeState, PREVIEW_DIR_NAME, SyncResource, SyncStatus, UserDataSyncError, UserDataSyncErrorCode,
34 > USER_DATA_SYNC_CONFIGURATION_SCOPE, USER_DATA_SYNC_SCHEME, getPathSegments, IUserDataSyncResourceConflicts,
35 > IUserDataSyncResource, IUserDataSyncResourcePreview,
36 > NON_EXISTING_RESOURCE_REF,
37 > } from './userDataSync.js';
38 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
39 >
40 > export function isRemoteUserData(thing: any): thing is IRemoteUserData {
41 > if (thing abstractSynchronizer.ts
42 > && (thing.ref !== undefined && typeof thing.ref === 'string' && thing.ref !== '')
43 > && (thing.syncData !== undefined && (thing.syncData === null || isSyncData(thing.syncData)))) {
44 > return true; abstractSynchronizer.ts
45 > }
46
47 return false;
48 }
50 > export function isSyncData(thing: any): thing is ISyncData {
51 if (thing
52 && (thing.version !== undefined && typeof thing.version === 'number')
66 return false;
67 }
69 > export function getSyncResourceLogLabel(syncResource: SyncResource, profile: IUserDataProfile): string {
70 > return `${uppercaseFirstLetter(syncResource)}${profile.isDefault ? '' : ` (${profile.name})`}`; abstractSynchronizer.ts
71 > }
73 > export interface IResourcePreview {
74 >
75 > readonly baseResource: URI;
76 > readonly baseContent: string | null;
77 >
78 > readonly remoteResource: URI;
79 > readonly remoteContent: string | null;
80 > readonly remoteChange: Change;
81 >
82 > readonly localResource: URI;
83 > readonly localContent: string | null;
84 > readonly localChange: Change;
85 >
86 > readonly previewResource: URI;
87 > readonly acceptedResource: URI;
88 > }
89 >
90 > export interface IAcceptResult {
91 > readonly content: string | null;
92 > readonly localChange: Change;
93 > readonly remoteChange: Change;
94 > }
95 >
96 > export interface IMergeResult extends IAcceptResult {
97 > readonly hasConflicts: boolean;
98 > }
99 >
100 > interface IEditableResourcePreview extends IBaseResourcePreview, IResourcePreview {
101 > localChange: Change;
102 > remoteChange: Change;
103 > mergeState: MergeState;
104 > acceptResult?: IAcceptResult;
105 > }
106 >
107 > export interface ISyncResourcePreview extends IBaseSyncResourcePreview {
108 > readonly remoteUserData: IRemoteUserData;
109 > readonly lastSyncUserData: IRemoteUserData | null;
110 > readonly resourcePreviews: IEditableResourcePreview[];
111 > }
112 >
113 > interface ILastSyncUserDataState {
114 > readonly ref: string;
115 > readonly version: string | undefined;
116 > [key: string]: any;
117 > }
118 >
119 > export const enum SyncStrategy {
120 > Preview = 'preview', // Merge the local and remote data without applying.
121 > Merge = 'merge', // Merge the local and remote data and apply.
122 > PullOrPush = 'pull-push', // Pull the remote data or push the local data.
123 > }
124 >
125 > export abstract class AbstractSynchroniser extends Disposable implements IUserDataSynchroniser {
126 >
127 > private syncPreviewPromise: CancelablePromise<ISyncResourcePreview> | null = null;
128 >
129 > protected readonly syncFolder: URI;
130 > protected readonly syncPreviewFolder: URI;
131 > protected readonly extUri: IExtUri;
132 > protected readonly currentMachineIdPromise: Promise<string>;
133 >
134 > private _status: SyncStatus = SyncStatus.Idle;
135 > get status(): SyncStatus { return this._status; }
136 > private _onDidChangStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>());
137 > readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangStatus.event;
138 >
139 > private _conflicts: IBaseResourcePreview[] = [];
140 > get conflicts(): IUserDataSyncResourceConflicts { return { ...this.syncResource, conflicts: this._conflicts }; }
141 > private _onDidChangeConflicts = this._register(new Emitter<IUserDataSyncResourceConflicts>());
142 > readonly onDidChangeConflicts = this._onDidChangeConflicts.event;
143 >
144 > private readonly localChangeTriggerThrottler = this._register(new ThrottledDelayer<void>(50));
145 > private readonly _onDidChangeLocal: Emitter<void> = this._register(new Emitter<void>());
146 > readonly onDidChangeLocal: Event<void> = this._onDidChangeLocal.event;
147 >
148 > protected readonly lastSyncResource: URI;
149 > private readonly lastSyncUserDataStateKey: string;
150 > private hasSyncResourceStateVersionChanged: boolean = false;
151 > protected readonly syncResourceLogLabel: string;
152 >
153 > protected syncHeaders: IHeaders = {};
154 >
155 > readonly resource: SyncResource;
156 >
157 > constructor(
158 > readonly syncResource: IUserDataSyncResource, abstractSynchronizer.ts
159 > readonly collection: string | undefined,
160 > @IFileService protected readonly fileService: IFileService,
161 > @IEnvironmentService protected readonly environmentService: IEnvironmentService,
162 > @IStorageService protected readonly storageService: IStorageService,
163 > @IUserDataSyncStoreService protected readonly userDataSyncStoreService: IUserDataSyncStoreService,
164 > @IUserDataSyncLocalStoreService protected readonly userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
165 > @IUserDataSyncEnablementService protected readonly userDataSyncEnablementService: IUserDataSyncEnablementService,
166 > @ITelemetryService protected readonly telemetryService: ITelemetryService,
167 > @IUserDataSyncLogService protected readonly logService: IUserDataSyncLogService,
168 > @IConfigurationService protected readonly configurationService: IConfigurationService,
169 > @IUriIdentityService uriIdentityService: IUriIdentityService,
170 > ) {
171 > super();
172 > this.lastSyncUserDataStateKey = `${collection ? `${collection}.` : ''}${syncResource.syncResource}.lastSyncUserData`;
173 > this.resource = syncResource.syncResource;
174 > this.syncResourceLogLabel = getSyncResourceLogLabel(syncResource.syncResource, syncResource.profile);
175 > this.extUri = uriIdentityService.extUri;
176 > this.syncFolder = this.extUri.joinPath(environmentService.userDataSyncHome, ...getPathSegments(syncResource.profile.isDefault ? undefined : syncResource.profile.id, syncResource.syncResource));
177 > this.syncPreviewFolder = this.extUri.joinPath(this.syncFolder, PREVIEW_DIR_NAME);
178 > this.lastSyncResource = getLastSyncResourceUri(syncResource.profile.isDefault ? undefined : syncResource.profile.id, syncResource.syncResource, environmentService, this.extUri);
179 > this.currentMachineIdPromise = getServiceMachineId(environmentService, fileService, storageService);
180 > }
182 > protected triggerLocalChange(): void {
183 this.localChangeTriggerThrottler.trigger(() => this.doTriggerLocalChange());
184 }
186 > protected async doTriggerLocalChange(): Promise<void> {
187
188 // Sync again if current status is in conflicts
205 }
206 }
208 > protected setStatus(status: SyncStatus): void {
209 > if (this._status !== status) { abstractSynchronizer.ts
210 > this._status = status;
211 > this._onDidChangStatus.fire(status);
212 > }
213 > }
215 > async sync(refOrUserData: string | IUserData | null, preview: boolean = false, userDataSyncConfiguration: IUserDataSyncConfiguration = this.getUserDataSyncConfiguration(), headers: IHeaders = {}): Promise<IUserDataSyncResourcePreview | null> {
217 > this.syncHeaders = { ...headers };
218 >
219 > if (this.status === SyncStatus.HasConflicts) {
220 this.logService.info(`${this.syncResourceLogLabel}: Skipped synchronizing ${this.resource.toLowerCase()} as there are conflicts.`);
221 return this.syncPreviewPromise;
222 }
224 > if (this.status === SyncStatus.Syncing) {
225 this.logService.info(`${this.syncResourceLogLabel}: Skipped synchronizing ${this.resource.toLowerCase()} as it is running already.`);
226 return this.syncPreviewPromise;
227 }
229 > this.logService.trace(`${this.syncResourceLogLabel}: Started synchronizing ${this.resource.toLowerCase()}...`);
230 > this.setStatus(SyncStatus.Syncing);
231 >
232 > let status: SyncStatus = SyncStatus.Idle;
233 > try {
234 > const lastSyncUserData = await this.getLastSyncUserData();
235 > const remoteUserData = await this.getLatestRemoteUserData(refOrUserData, lastSyncUserData);
236 > status = await this.performSync(remoteUserData, lastSyncUserData, preview ? SyncStrategy.Preview : SyncStrategy.Merge, userDataSyncConfiguration);
237 > if (status === SyncStatus.HasConflicts) { abstractSynchronizer.ts
238 this.logService.info(`${this.syncResourceLogLabel}: Detected conflicts while synchronizing ${this.resource.toLowerCase()}.`);
239 > } else if (status === SyncStatus.Idle) { abstractSynchronizer.ts
240 > this.logService.trace(`${this.syncResourceLogLabel}: Finished synchronizing ${this.resource.toLowerCase()}.`); abstractSynchronizer.ts
241 > }
242 > return this.syncPreviewPromise || null; abstractSynchronizer.ts
243 > } finally { abstractSynchronizer.ts
244 > this.setStatus(status);
245 > }
246 > } finally {
247 > this.syncHeaders = {};
248 > }
249 > }
251 > async apply(force: boolean, headers: IHeaders = {}): Promise<ISyncResourcePreview | null> {
252 try {
253 this.syncHeaders = { ...headers };
261 }
262 }
264 > async replace(content: string): Promise<boolean> {
265 const syncData = this.parseSyncData(content);
266 if (!syncData) {
297 return true;
298 }
300 > private async isRemoteDataFromCurrentMachine(remoteUserData: IRemoteUserData): Promise<boolean> {
301 > const machineId = await this.currentMachineIdPromise; abstractSynchronizer.ts
302 > return !!remoteUserData.syncData?.machineId && remoteUserData.syncData.machineId === machineId;
303 > }
305 > protected async getLatestRemoteUserData(refOrLatestData: string | IUserData | null, lastSyncUserData: IRemoteUserData | null): Promise<IRemoteUserData> {
306 > if (refOrLatestData === null) { abstractSynchronizer.ts
307 > return { ref: NON_EXISTING_RESOURCE_REF, syncData: null };
308 > }
309
310 if (!isString(refOrLatestData)) {
313
314 // Last time synced resource and latest resource on server are same
315 > if (lastSyncUserData?.ref === refOrLatestData) { abstractSynchronizer.ts
316 return lastSyncUserData;
317 }
318
319 return this.getRemoteUserData(lastSyncUserData);
322 > private async performSync(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, strategy: SyncStrategy, userDataSyncConfiguration: IUserDataSyncConfiguration): Promise<SyncStatus> {
323 > if (remoteUserData.syncData && remoteUserData.syncData.version > this.version) { abstractSynchronizer.ts
324 throw new UserDataSyncError(localize({ key: 'incompatible', comment: ['This is an error while syncing a resource that its local version is not compatible with its remote version.'] }, "Cannot sync {0} as its local version {1} is not compatible with its remote version {2}", this.resource, this.version, remoteUserData.syncData.version), UserDataSyncErrorCode.IncompatibleLocalContent, this.resource);
325 }
327 > try {
328 > return await this.doSync(remoteUserData, lastSyncUserData, strategy, userDataSyncConfiguration);
329 > } catch (e) {
330 if (e instanceof UserDataSyncError) {
331 switch (e.code) {
353 throw e;
354 }
357 > protected async doSync(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, strategy: SyncStrategy, userDataSyncConfiguration: IUserDataSyncConfiguration): Promise<SyncStatus> {
359 >
360 > const isRemoteDataFromCurrentMachine = await this.isRemoteDataFromCurrentMachine(remoteUserData);
361 > const acceptRemote = !isRemoteDataFromCurrentMachine && lastSyncUserData === null && this.getStoredLastSyncUserDataStateContent() !== undefined;
362 > const merge = strategy === SyncStrategy.Preview || (strategy === SyncStrategy.Merge && !acceptRemote);
363 > const apply = strategy === SyncStrategy.Merge || strategy === SyncStrategy.PullOrPush;
364 >
365 > // generate or use existing preview
366 > if (!this.syncPreviewPromise) {
367 > this.syncPreviewPromise = createCancelablePromise(token => this.doGenerateSyncResourcePreview(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, merge, userDataSyncConfiguration, token));
368 > }
369 >
370 > let preview = await this.syncPreviewPromise;
372 > if (strategy === SyncStrategy.Merge && acceptRemote) { abstractSynchronizer.ts
373 this.logService.info(`${this.syncResourceLogLabel}: Accepting remote because it was synced before and the last sync data is not available.`);
374 for (const resourcePreview of preview.resourcePreviews) {
376 }
377 }
379 > else if (strategy === SyncStrategy.PullOrPush) {
380 for (const resourcePreview of preview.resourcePreviews) {
381 if (resourcePreview.mergeState === MergeState.Accepted) {
389 }
390 }
392 > this.updateConflicts(preview.resourcePreviews);
393 > if (preview.resourcePreviews.some(({ mergeState }) => mergeState === MergeState.Conflict)) {
394 return SyncStatus.HasConflicts;
395 }
397 > if (apply) {
398 > return await this.doApply(false); abstractSynchronizer.ts
399 > }
400
401 return SyncStatus.Syncing;
408 throw error;
409 }
412 > async accept(resource: URI, content?: string | null): Promise<ISyncResourcePreview | null> {
413 await this.updateSyncResourcePreview(resource, async (resourcePreview) => {
414 const acceptResult = await this.getAcceptResult(resourcePreview, resource, content, CancellationToken.None);
421 return this.syncPreviewPromise;
422 }
424 > async discard(resource: URI): Promise<ISyncResourcePreview | null> {
425 await this.updateSyncResourcePreview(resource, async (resourcePreview) => {
426 const mergeResult = await this.getMergeResult(resourcePreview, CancellationToken.None);
434 return this.syncPreviewPromise;
435 }
437 > private async updateSyncResourcePreview(resource: URI, updateResourcePreview: (resourcePreview: IEditableResourcePreview) => Promise<IEditableResourcePreview>): Promise<void> {
438 if (!this.syncPreviewPromise) {
439 return;
464 }
465 }
467 > private async doApply(force: boolean): Promise<SyncStatus> {
468 > if (!this.syncPreviewPromise) { abstractSynchronizer.ts
469 return SyncStatus.Idle;
470 }
472 > const preview = await this.syncPreviewPromise;
473 >
474 > // check for conflicts
475 > if (preview.resourcePreviews.some(({ mergeState }) => mergeState === MergeState.Conflict)) {
476 return SyncStatus.HasConflicts;
477 }
479 > // check if all are accepted
480 > if (preview.resourcePreviews.some(({ mergeState }) => mergeState !== MergeState.Accepted)) {
481 return SyncStatus.Syncing;
482 }
484 > // apply preview
485 > await this.applyResult(preview.remoteUserData, preview.lastSyncUserData, preview.resourcePreviews.map(resourcePreview => ([resourcePreview, resourcePreview.acceptResult!])), force);
487 > // reset preview
488 > this.syncPreviewPromise = null;
489 >
490 > // reset preview folder
491 > await this.clearPreviewFolder();
492 >
493 > return SyncStatus.Idle;
496 > private async clearPreviewFolder(): Promise<void> {
498 > await this.fileService.del(this.syncPreviewFolder, { recursive: true });
499 > } catch (error) { /* Ignore */ }
500 > }
502 > private updateConflicts(resourcePreviews: IEditableResourcePreview[]): void {
503 > const conflicts = resourcePreviews.filter(({ mergeState }) => mergeState === MergeState.Conflict); abstractSynchronizer.ts
504 > if (!equals(this._conflicts, conflicts, (a, b) => this.extUri.isEqual(a.previewResource, b.previewResource))) {
505 this._conflicts = conflicts;
506 this._onDidChangeConflicts.fire(this.conflicts);
507 }
510 > async hasPreviouslySynced(): Promise<boolean> {
511 const lastSyncData = await this.getLastSyncUserData();
512 return !!lastSyncData && lastSyncData.syncData !== null /* `null` sync data implies resource is not synced */;
513 }
515 > protected async resolvePreviewContent(uri: URI): Promise<string | null> {
516 const syncPreview = this.syncPreviewPromise ? await this.syncPreviewPromise : null;
517 if (syncPreview) {
533 return null;
534 }
536 > async resetLocal(): Promise<void> {
537 > this.storageService.remove(this.lastSyncUserDataStateKey, StorageScope.APPLICATION); abstractSynchronizer.ts
538 > try {
539 > await this.fileService.del(this.lastSyncResource);
540 > } catch (error) {
541 if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) {
542 this.logService.error(error);
543 }
544 }
547 > private async doGenerateSyncResourcePreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean, merge: boolean, userDataSyncConfiguration: IUserDataSyncConfiguration, token: CancellationToken): Promise<ISyncResourcePreview> {
548 > const resourcePreviewResults = await this.generateSyncPreview(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, userDataSyncConfiguration, token); abstractSynchronizer.ts
550 > const resourcePreviews: IEditableResourcePreview[] = [];
551 > for (const resourcePreviewResult of resourcePreviewResults) {
552 > const acceptedResource = resourcePreviewResult.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }); abstractSynchronizer.ts
553 >
554 > /* No change -> Accept */
555 > if (resourcePreviewResult.localChange === Change.None && resourcePreviewResult.remoteChange === Change.None) {
556 > resourcePreviews.push({ abstractSynchronizer.ts
557 > ...resourcePreviewResult,
558 > acceptedResource,
559 > acceptResult: { content: null, localChange: Change.None, remoteChange: Change.None },
560 > mergeState: MergeState.Accepted
561 > });
562 > }
564 > /* Changed -> Apply ? (Merge ? Conflict | Accept) : Preview */
565 > else {
566 > /* Merge */
567 > const mergeResult = merge ? await this.getMergeResult(resourcePreviewResult, token) : undefined;
568 > if (token.isCancellationRequested) {
569 break;
570 }
571 > await this.fileService.writeFile(resourcePreviewResult.previewResource, VSBuffer.fromString(mergeResult?.content || '')); abstractSynchronizer.ts
572 >
573 > /* Conflict | Accept */
574 > const acceptResult = mergeResult && !mergeResult.hasConflicts
575 > /* Accept if merged and there are no conflicts */ abstractSynchronizer.ts
576 > ? await this.getAcceptResult(resourcePreviewResult, resourcePreviewResult.previewResource, undefined, token)
577 : undefined;
579 > resourcePreviews.push({
580 > ...resourcePreviewResult,
581 > acceptResult,
582 > mergeState: mergeResult?.hasConflicts ? MergeState.Conflict : acceptResult ? MergeState.Accepted : MergeState.Preview,
583 > localChange: acceptResult ? acceptResult.localChange : mergeResult ? mergeResult.localChange : resourcePreviewResult.localChange,
584 > remoteChange: acceptResult ? acceptResult.remoteChange : mergeResult ? mergeResult.remoteChange : resourcePreviewResult.remoteChange
585 > });
586 > }
589 > return { syncResource: this.resource, profile: this.syncResource.profile, remoteUserData, lastSyncUserData, resourcePreviews, isLastSyncFromCurrentMachine: isRemoteDataFromCurrentMachine };
592 > async getLastSyncUserData(): Promise<IRemoteUserData | null> {
593 > const storedLastSyncUserDataStateContent = this.getStoredLastSyncUserDataStateContent(); abstractSynchronizer.ts
594 >
595 > // Last Sync Data state does not exist
596 > if (!storedLastSyncUserDataStateContent) {
597 > this.logService.info(`${this.syncResourceLogLabel}: Last sync data state does not exist.`);
598 > return null;
599 > }
601 > const lastSyncUserDataState: ILastSyncUserDataState = JSON.parse(storedLastSyncUserDataStateContent);
602 > const resourceSyncStateVersion = this.userDataSyncEnablementService.getResourceSyncStateVersion(this.resource);
603 > this.hasSyncResourceStateVersionChanged = !!lastSyncUserDataState.version && !!resourceSyncStateVersion && lastSyncUserDataState.version !== resourceSyncStateVersion; abstractSynchronizer.ts
604 > if (this.hasSyncResourceStateVersionChanged) {
605 this.logService.info(`${this.syncResourceLogLabel}: Reset last sync state because last sync state version ${lastSyncUserDataState.version} is not compatible with current sync state version ${resourceSyncStateVersion}.`);
606 await this.resetLocal();
607 return null;
608 }
610 > let syncData: ISyncData | null | undefined = undefined;
611 >
612 > // Get Last Sync Data from Local
613 > let retrial = 1;
614 > while (syncData === undefined && retrial++ < 6 /* Retry 5 times */) { abstractSynchronizer.ts
616 > const lastSyncStoredRemoteUserData = await this.readLastSyncStoredRemoteUserData();
617 > if (lastSyncStoredRemoteUserData) { abstractSynchronizer.ts
618 > if (lastSyncStoredRemoteUserData.ref === lastSyncUserDataState.ref) { abstractSynchronizer.ts
619 > syncData = lastSyncStoredRemoteUserData.syncData; abstractSynchronizer.ts
620 > } else { abstractSynchronizer.ts
621 this.logService.info(`${this.syncResourceLogLabel}: Last sync data stored locally is not same as the last sync state.`);
622 }
625 > } catch (error) { abstractSynchronizer.ts
626 if (error instanceof FileOperationError && error.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
627 this.logService.info(`${this.syncResourceLogLabel}: Last sync resource does not exist locally.`);
634 }
635 }
637 >
638 > // Get Last Sync Data from Remote
639 > if (syncData === undefined) {
640 try {
641 const content = await this.userDataSyncStoreService.resolveResourceContent(this.resource, lastSyncUserDataState.ref, this.collection, this.syncHeaders);
650 }
651 }
653 > // Last Sync Data Not Found
654 > if (syncData === undefined) {
655 return null;
656 }
658 > return {
659 > ...lastSyncUserDataState,
660 > syncData,
661 > };
664 > protected async updateLastSyncUserData(lastSyncRemoteUserData: IRemoteUserData, additionalProps: IStringDictionary<any> = {}): Promise<void> {
665 > if (additionalProps['ref'] || additionalProps['version']) { abstractSynchronizer.ts
666 throw new Error('Cannot have core properties as additional');
667 }
669 > const version = this.userDataSyncEnablementService.getResourceSyncStateVersion(this.resource);
670 > const lastSyncUserDataState: ILastSyncUserDataState = {
671 > ref: lastSyncRemoteUserData.ref,
672 > version,
673 > ...additionalProps
674 > };
675 >
676 > this.storageService.store(this.lastSyncUserDataStateKey, JSON.stringify(lastSyncUserDataState), StorageScope.APPLICATION, StorageTarget.MACHINE);
677 > await this.writeLastSyncStoredRemoteUserData(lastSyncRemoteUserData);
678 > }
680 > private getStoredLastSyncUserDataStateContent(): string | undefined {
681 > return this.storageService.get(this.lastSyncUserDataStateKey, StorageScope.APPLICATION); abstractSynchronizer.ts
682 > }
684 > private async readLastSyncStoredRemoteUserData(): Promise<IRemoteUserData | undefined> {
685 > const content = (await this.fileService.readFile(this.lastSyncResource)).value.toString(); abstractSynchronizer.ts
687 > const lastSyncStoredRemoteUserData = content ? JSON.parse(content) : undefined; abstractSynchronizer.ts
688 > if (isRemoteUserData(lastSyncStoredRemoteUserData)) {
689 > return lastSyncStoredRemoteUserData; abstractSynchronizer.ts
690 > }
691 > } catch (e) { abstractSynchronizer.ts
692 this.logService.error(e);
693 }
694 return undefined;
697 > private async writeLastSyncStoredRemoteUserData(lastSyncRemoteUserData: IRemoteUserData): Promise<void> {
698 > await this.fileService.writeFile(this.lastSyncResource, VSBuffer.fromString(JSON.stringify(lastSyncRemoteUserData))); abstractSynchronizer.ts
699 > }
701 > async getRemoteUserData(lastSyncData: IRemoteUserData | null): Promise<IRemoteUserData> {
702 const userData = await this.getUserData(lastSyncData);
703 return this.toRemoteUserData(userData);
704 }
706 > private toRemoteUserData({ ref, content }: IUserData): IRemoteUserData {
707 let syncData: ISyncData | null = null;
708 if (content !== null) {
711 return { ref, syncData };
712 }
714 > protected parseSyncData(content: string): ISyncData {
715 try {
716 const syncData: ISyncData = JSON.parse(content);
723 throw new UserDataSyncError(localize('incompatible sync data', "Cannot parse sync data as it is not compatible with the current version."), UserDataSyncErrorCode.IncompatibleRemoteContent, this.resource);
724 }
726 > private async getUserData(lastSyncData: IRemoteUserData | null): Promise<IUserData> {
727 const lastSyncUserData: IUserData | null = lastSyncData ? { ref: lastSyncData.ref, content: lastSyncData.syncData ? JSON.stringify(lastSyncData.syncData) : null } : null;
728 return this.userDataSyncStoreService.readResource(this.resource, lastSyncUserData, this.collection, this.syncHeaders);
729 }
731 > protected async updateRemoteUserData(content: string, ref: string | null): Promise<IRemoteUserData> {
732 > const machineId = await this.currentMachineIdPromise; abstractSynchronizer.ts
733 > const syncData: ISyncData = { version: this.version, machineId, content };
734 > try {
735 > ref = await this.userDataSyncStoreService.writeResource(this.resource, JSON.stringify(syncData), ref, this.collection, this.syncHeaders);
736 > return { ref, syncData };
737 > } catch (error) {
738 if (error instanceof UserDataSyncError && error.code === UserDataSyncErrorCode.TooLarge) {
739 error = new UserDataSyncError(error.message, error.code, this.resource);
741 throw error;
742 }
745 > protected async backupLocal(content: string): Promise<void> {
746 const syncData: ISyncData = { version: this.version, content };
747 return this.userDataSyncLocalStoreService.writeResource(this.resource, JSON.stringify(syncData), new Date(), this.syncResource.profile.isDefault ? undefined : this.syncResource.profile.id);
748 }
750 > async stop(): Promise<void> {
751 if (this.status === SyncStatus.Idle) {
752 return;
765 this.logService.info(`${this.syncResourceLogLabel}: Stopped synchronizing ${this.resource.toLowerCase()}.`);
766 }
768 > private getUserDataSyncConfiguration(): IUserDataSyncConfiguration {
769 return this.configurationService.getValue(USER_DATA_SYNC_CONFIGURATION_SCOPE);
770 }
772 > protected abstract readonly version: number;
773 > protected abstract generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean, userDataSyncConfiguration: IUserDataSyncConfiguration, token: CancellationToken): Promise<IResourcePreview[]>;
774 > protected abstract getMergeResult(resourcePreview: IResourcePreview, token: CancellationToken): Promise<IMergeResult>;
775 > protected abstract getAcceptResult(resourcePreview: IResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult>;
776 > protected abstract applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, result: [IResourcePreview, IAcceptResult][], force: boolean): Promise<void>;
777 > protected abstract hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean>;
778 >
779 > abstract hasLocalData(): Promise<boolean>;
780 > abstract resolveContent(uri: URI): Promise<string | null>;
781 > }
782 >
783 > export interface IFileResourcePreview extends IResourcePreview {
784 > readonly fileContent: IFileContent | null;
785 > }
786 >
787 > export abstract class AbstractFileSynchroniser extends AbstractSynchroniser {
788 >
789 > constructor(
790 > protected readonly file: URI, abstractSynchronizer.ts
791 > syncResource: IUserDataSyncResource,
792 > collection: string | undefined,
793 > @IFileService fileService: IFileService,
794 > @IEnvironmentService environmentService: IEnvironmentService,
795 > @IStorageService storageService: IStorageService,
796 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
797 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
798 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
799 > @ITelemetryService telemetryService: ITelemetryService,
800 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
801 > @IConfigurationService configurationService: IConfigurationService,
802 > @IUriIdentityService uriIdentityService: IUriIdentityService,
803 > ) {
804 > super(syncResource, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
805 > this._register(this.fileService.watch(this.extUri.dirname(file)));
806 > this._register(this.fileService.onDidFilesChange(e => this.onFileChanges(e)));
807 > }
809 > protected async getLocalFileContent(): Promise<IFileContent | null> {
811 > return await this.fileService.readFile(this.file);
812 > } catch (error) {
813 > return null; abstractSynchronizer.ts
814 > }
817 > protected async updateLocalFileContent(newContent: string, oldContent: IFileContent | null, force: boolean): Promise<void> {
818 try {
819 if (oldContent) {
833 }
834 }
836 > protected async deleteLocalFile(): Promise<void> {
837 try {
838 await this.fileService.del(this.file);
843 }
844 }
846 > private onFileChanges(e: FileChangesEvent): void {
847 if (!e.contains(this.file)) {
848 return;
850 this.triggerLocalChange();
851 }
853 > }
854 >
855 > export abstract class AbstractJsonFileSynchroniser extends AbstractFileSynchroniser {
856 >
857 > constructor(
858 > file: URI, abstractSynchronizer.ts
859 > syncResource: IUserDataSyncResource,
860 > collection: string | undefined,
861 > @IFileService fileService: IFileService,
862 > @IEnvironmentService environmentService: IEnvironmentService,
863 > @IStorageService storageService: IStorageService,
864 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
865 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
866 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
867 > @ITelemetryService telemetryService: ITelemetryService,
868 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
869 > @IUserDataSyncUtilService protected readonly userDataSyncUtilService: IUserDataSyncUtilService,
870 > @IConfigurationService configurationService: IConfigurationService,
871 > @IUriIdentityService uriIdentityService: IUriIdentityService,
872 > ) {
873 > super(file, syncResource, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
874 > }
875 >
876 > protected hasErrors(content: string, isArray: boolean): boolean {
877 > const parseErrors: ParseError[] = []; abstractSynchronizer.ts
878 > const result = parse(content, parseErrors, { allowEmptyContent: true, allowTrailingComma: true });
879 > return parseErrors.length > 0 || (!isUndefined(result) && isArray !== Array.isArray(result));
880 > }
882 > private _formattingOptions: Promise<FormattingOptions> | undefined = undefined;
883 > protected getFormattingOptions(): Promise<FormattingOptions> { abstractSynchronizer.ts
884 > if (!this._formattingOptions) { abstractSynchronizer.ts
885 > this._formattingOptions = this.userDataSyncUtilService.resolveFormattingOptions(this.file);
886 > }
887 > return this._formattingOptions;
888 > }
890 > }
891 >
892 > export abstract class AbstractInitializer implements IUserDataSyncResourceInitializer {
893 >
894 > protected readonly extUri: IExtUri;
895 > private readonly lastSyncResource: URI;
896 >
897 > constructor(
898 readonly resource: SyncResource,
899 @IUserDataProfilesService protected readonly userDataProfilesService: IUserDataProfilesService,
907 this.lastSyncResource = getLastSyncResourceUri(undefined, this.resource, environmentService, this.extUri);
908 }
910 > async initialize({ ref, content }: IUserData): Promise<void> {
911 if (!content) {
912 this.logService.info('Remote content does not exist.', this.resource);
925 }
926 }
928 > private parseSyncData(content: string): ISyncData | undefined {
929 try {
930 const syncData: ISyncData = JSON.parse(content);
938 return undefined;
939 }
941 > protected async updateLastSyncUserData(lastSyncRemoteUserData: IRemoteUserData, additionalProps: IStringDictionary<any> = {}): Promise<void> {
942 if (additionalProps['ref'] || additionalProps['version']) {
943 throw new Error('Cannot have core properties as additional');
953 await this.fileService.writeFile(this.lastSyncResource, VSBuffer.fromString(JSON.stringify(lastSyncRemoteUserData)));
954 }
956 > protected abstract doInitialize(remoteUserData: IRemoteUserData): Promise<void>;
957 >
958 > }
src/vs/base/common/stream.ts 505 covered LOC · 101 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- stream.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken } from './cancellation.js';
7 > import { onUnexpectedError } from './errors.js';
8 > import { DisposableStore, toDisposable } from './lifecycle.js';
9 >
10 > /**
11 > * The payload that flows in readable stream events.
12 > */
13 > export type ReadableStreamEventPayload<T> = T | Error | 'end';
14 >
15 > export interface ReadableStreamEvents<T> {
16 >
17 > /**
18 > * The 'data' event is emitted whenever the stream is
19 > * relinquishing ownership of a chunk of data to a consumer.
20 > *
21 > * NOTE: PLEASE UNDERSTAND THAT ADDING A DATA LISTENER CAN
22 > * TURN THE STREAM INTO FLOWING MODE. IT IS THEREFOR THE
23 > * LAST LISTENER THAT SHOULD BE ADDED AND NOT THE FIRST
24 > *
25 > * Use `listenStream` as a helper method to listen to
26 > * stream events in the right order.
27 > */
28 > on(event: 'data', callback: (data: T) => void): void;
29 >
30 > /**
31 > * Emitted when any error occurs.
32 > */
33 > on(event: 'error', callback: (err: Error) => void): void;
34 >
35 > /**
36 > * The 'end' event is emitted when there is no more data
37 > * to be consumed from the stream. The 'end' event will
38 > * not be emitted unless the data is completely consumed.
39 > */
40 > on(event: 'end', callback: () => void): void;
41 > }
42 >
43 > /**
44 > * A interface that emulates the API shape of a node.js readable
45 > * stream for use in native and web environments.
46 > */
47 > export interface ReadableStream<T> extends ReadableStreamEvents<T> {
48 >
49 > /**
50 > * Stops emitting any events until resume() is called.
51 > */
52 > pause(): void;
53 >
54 > /**
55 > * Starts emitting events again after pause() was called.
56 > */
57 > resume(): void;
58 >
59 > /**
60 > * Destroys the stream and stops emitting any event.
61 > */
62 > destroy(): void;
63 >
64 > /**
65 > * Allows to remove a listener that was previously added.
66 > */
67 > removeListener(event: string, callback: Function): void;
68 > }
69 >
70 > /**
71 > * A interface that emulates the API shape of a node.js readable
72 > * for use in native and web environments.
73 > */
74 > export interface Readable<T> {
75 >
76 > /**
77 > * Read data from the underlying source. Will return
78 > * null to indicate that no more data can be read.
79 > */
80 > read(): T | null;
81 > }
82 >
83 > export function isReadable<T>(obj: unknown): obj is Readable<T> {
84 const candidate = obj as Readable<T> | undefined;
85 if (!candidate) {
89 return typeof candidate.read === 'function';
90 }
91 > stream.ts
92 > /**
93 > * A interface that emulates the API shape of a node.js writeable
94 > * stream for use in native and web environments.
95 > */
96 > export interface WriteableStream<T> extends ReadableStream<T> {
97 >
98 > /**
99 > * Writing data to the stream will trigger the on('data')
100 > * event listener if the stream is flowing and buffer the
101 > * data otherwise until the stream is flowing.
102 > *
103 > * If a `highWaterMark` is configured and writing to the
104 > * stream reaches this mark, a promise will be returned
105 > * that should be awaited on before writing more data.
106 > * Otherwise there is a risk of buffering a large number
107 > * of data chunks without consumer.
108 > */
109 > write(data: T): void | Promise<void>;
110 >
111 > /**
112 > * Signals an error to the consumer of the stream via the
113 > * on('error') handler if the stream is flowing.
114 > *
115 > * NOTE: call `end` to signal that the stream has ended,
116 > * this DOES NOT happen automatically from `error`.
117 > */
118 > error(error: Error): void;
119 >
120 > /**
121 > * Signals the end of the stream to the consumer. If the
122 > * result is provided, will trigger the on('data') event
123 > * listener if the stream is flowing and buffer the data
124 > * otherwise until the stream is flowing.
125 > */
126 > end(result?: T): void;
127 > }
128 >
129 > /**
130 > * A stream that has a buffer already read. Returns the original stream
131 > * that was read as well as the chunks that got read.
132 > *
133 > * The `ended` flag indicates if the stream has been fully consumed.
134 > */
135 > export interface ReadableBufferedStream<T> {
136 >
137 > /**
138 > * The original stream that is being read.
139 > */
140 > stream: ReadableStream<T>;
141 >
142 > /**
143 > * An array of chunks already read from this stream.
144 > */
145 > buffer: T[];
146 >
147 > /**
148 > * Signals if the stream has ended or not. If not, consumers
149 > * should continue to read from the stream until consumed.
150 > */
151 > ended: boolean;
152 > }
153 >
154 > export function isReadableStream<T>(obj: unknown): obj is ReadableStream<T> {
155 const candidate = obj as ReadableStream<T> | undefined;
156 if (!candidate) {
160 return [candidate.on, candidate.pause, candidate.resume, candidate.destroy].every(fn => typeof fn === 'function');
161 }
162 > stream.ts
163 > export function isReadableBufferedStream<T>(obj: unknown): obj is ReadableBufferedStream<T> {
164 const candidate = obj as ReadableBufferedStream<T> | undefined;
165 if (!candidate) {
169 return isReadableStream(candidate.stream) && Array.isArray(candidate.buffer) && typeof candidate.ended === 'boolean';
170 }
171 > stream.ts
172 > export interface IReducer<T, R = T> {
173 > (data: T[]): R;
174 > }
175 >
176 > export interface IDataTransformer<Original, Transformed> {
177 > (data: Original): Transformed;
178 > }
179 >
180 > export interface IErrorTransformer {
181 > (error: Error): Error;
182 > }
183 >
184 > export interface ITransformer<Original, Transformed> {
185 > data: IDataTransformer<Original, Transformed>;
186 > error?: IErrorTransformer;
187 > }
188 >
189 > export function newWriteableStream<T>(reducer: IReducer<T> | null, options?: WriteableStreamOptions): WriteableStream<T> {
190 > return new WriteableStreamImpl<T>(reducer, options); stream.ts
191 > }
192 > stream.ts
193 > export interface WriteableStreamOptions {
194 >
195 > /**
196 > * The number of objects to buffer before WriteableStream#write()
197 > * signals back that the buffer is full. Can be used to reduce
198 > * the memory pressure when the stream is not flowing.
199 > */
200 > highWaterMark?: number;
201 > }
202 >
203 > class WriteableStreamImpl<T> implements WriteableStream<T> {
204 >
205 > private readonly state = {
206 > flowing: false,
207 > ended: false,
208 > destroyed: false
209 > };
210 >
211 > private readonly buffer = {
212 > data: [] as T[],
213 > error: [] as Error[]
214 > };
215 >
216 > private readonly listeners = {
217 > data: [] as { (data: T): void }[],
218 > error: [] as { (error: Error): void }[],
219 > end: [] as { (): void }[]
220 > };
221 >
222 > private readonly pendingWritePromises: Function[] = [];
223 >
224 > /**
225 > * @param reducer a function that reduces the buffered data into a single object;
226 > * because some objects can be complex and non-reducible, we also
227 > * allow passing the explicit `null` value to skip the reduce step
228 > * @param options stream options
229 > */
230 > constructor(private reducer: IReducer<T> | null, private options?: WriteableStreamOptions) { }
231 >
232 > pause(): void {
233 if (this.state.destroyed) {
234 return;
237 this.state.flowing = false;
238 }
239 > stream.ts
240 > resume(): void {
241 > if (this.state.destroyed) { stream.ts
242 return;
243 }
244 > stream.ts
245 > if (!this.state.flowing) {
246 > this.state.flowing = true;
247 >
248 > // emit buffered events
249 > this.flowData();
250 > this.flowErrors();
251 > this.flowEnd();
252 > }
253 > }
254 > stream.ts
255 > write(data: T): void | Promise<void> {
256 > if (this.state.destroyed) { stream.ts
257 return;
258 }
259 > stream.ts
260 > // flowing: directly send the data to listeners
261 > if (this.state.flowing) {
262 this.emitData(data);
263 }
264 > stream.ts
265 > // not yet flowing: buffer data until flowing
266 > else {
267 > this.buffer.data.push(data);
268 >
269 > // highWaterMark: if configured, signal back when buffer reached limits
270 > if (typeof this.options?.highWaterMark === 'number' && this.buffer.data.length > this.options.highWaterMark) {
271 return new Promise(resolve => this.pendingWritePromises.push(resolve));
272 }
273 > } stream.ts
274 > } stream.ts
275 > stream.ts
276 > error(error: Error): void {
277 > if (this.state.destroyed) { stream.ts
278 return;
279 }
280 > stream.ts
281 > // flowing: directly send the error to listeners
282 > if (this.state.flowing) {
283 this.emitError(error);
284 }
285 > stream.ts
286 > // not yet flowing: buffer errors until flowing
287 > else {
288 > this.buffer.error.push(error);
289 > }
290 > } stream.ts
291 > stream.ts
292 > end(result?: T): void {
293 > if (this.state.destroyed) { stream.ts
294 return;
295 }
296 > stream.ts
297 > // end with data if provided
298 > if (typeof result !== 'undefined') {
299 > this.write(result); stream.ts
300 > }
301 > stream.ts
302 > // flowing: send end event to listeners
303 > if (this.state.flowing) {
304 this.emitEnd();
305
306 this.destroy();
307 }
308 > stream.ts
309 > // not yet flowing: remember state
310 > else {
311 > this.state.ended = true;
312 > }
313 > } stream.ts
314 > stream.ts
315 > private emitData(data: T): void {
316 > this.listeners.data.slice(0).forEach(listener => listener(data)); // slice to avoid listener mutation from delivering event stream.ts
317 > }
318 > stream.ts
319 > private emitError(error: Error): void {
320 > if (this.listeners.error.length === 0) { stream.ts
321 onUnexpectedError(error); // nobody listened to this error so we log it as unexpected
322 > } else { stream.ts
323 > this.listeners.error.slice(0).forEach(listener => listener(error)); // slice to avoid listener mutation from delivering event
324 > }
325 > }
326 > stream.ts
327 > private emitEnd(): void {
328 > this.listeners.end.slice(0).forEach(listener => listener()); // slice to avoid listener mutation from delivering event stream.ts
329 > }
330 > stream.ts
331 > on(event: 'data', callback: (data: T) => void): void;
332 > on(event: 'error', callback: (err: Error) => void): void;
333 > on(event: 'end', callback: () => void): void;
334 > on(event: 'data' | 'error' | 'end', callback: ((data: T) => void) | ((err: Error) => void) | (() => void)): void {
335 > if (this.state.destroyed) { stream.ts
336 return;
337 }
338 > stream.ts
339 > switch (event) {
340 > case 'data':
341 > this.listeners.data.push(callback as (data: T) => void);
342 >
343 > // switch into flowing mode as soon as the first 'data'
344 > // listener is added and we are not yet in flowing mode
345 > this.resume();
346 >
347 > break;
348 >
349 > case 'end':
350 > this.listeners.end.push(callback as () => void); stream.ts
351 >
352 > // emit 'end' event directly if we are flowing
353 > // and the end has already been reached
354 > //
355 > // finish() when it went through
356 > if (this.state.flowing && this.flowEnd()) {
357 this.destroy();
358 }
359 > stream.ts
360 > break;
361 > stream.ts
362 > case 'error':
363 > this.listeners.error.push(callback as (err: Error) => void); stream.ts
364 >
365 > // emit buffered 'error' events unless done already
366 > // now that we know that we have at least one listener
367 > if (this.state.flowing) {
368 this.flowErrors();
369 }
370 > stream.ts
371 > break;
372 > } stream.ts
373 > }
374 > stream.ts
375 > removeListener(event: string, callback: Function): void {
376 if (this.state.destroyed) {
377 return;
401 }
402 }
403 > stream.ts
404 > private flowData(): void {
405 > // if buffer is empty, nothing to do stream.ts
406 > if (this.buffer.data.length === 0) {
407 > return; stream.ts
408 > }
409 > stream.ts
410 > // if buffer data can be reduced into a single object,
411 > // emit the reduced data
412 > if (typeof this.reducer === 'function') {
413 > const fullDataBuffer = this.reducer(this.buffer.data); stream.ts
414 >
415 > this.emitData(fullDataBuffer);
416 > } else { stream.ts
417 // otherwise emit each buffered data instance individually
418 for (const data of this.buffer.data) {
420 }
421 }
422 > stream.ts
423 > this.buffer.data.length = 0;
424 >
425 > // when the buffer is empty, resolve all pending writers
426 > const pendingWritePromises = [...this.pendingWritePromises];
427 > this.pendingWritePromises.length = 0;
428 > pendingWritePromises.forEach(pendingWritePromise => pendingWritePromise());
429 > } stream.ts
430 > stream.ts
431 > private flowErrors(): void {
432 > if (this.listeners.error.length > 0) { stream.ts
433 > for (const error of this.buffer.error) { stream.ts
434 > this.emitError(error); stream.ts
435 > }
436 > stream.ts
437 > this.buffer.error.length = 0;
438 > }
439 > } stream.ts
440 > stream.ts
441 > private flowEnd(): boolean {
442 > if (this.state.ended) { stream.ts
443 > this.emitEnd(); stream.ts
444 >
445 > return this.listeners.end.length > 0;
446 > }
447
448 return false;
449 > } stream.ts
450 > stream.ts
451 > destroy(): void {
452 if (!this.state.destroyed) {
453 this.state.destroyed = true;
464 }
465 }
466 > } stream.ts
467 >
468 > /**
469 > * Helper to fully read a T readable into a T.
470 > */
471 > export function consumeReadable<T>(readable: Readable<T>, reducer: IReducer<T>): T {
472 const chunks: T[] = [];
473
479 return reducer(chunks);
480 }
481 > stream.ts
482 > /**
483 > * Helper to read a T readable up to a maximum of chunks. If the limit is
484 > * reached, will return a readable instead to ensure all data can still
485 > * be read.
486 > */
487 > export function peekReadable<T>(readable: Readable<T>, reducer: IReducer<T>, maxChunks: number): T | Readable<T> {
488 const chunks: T[] = [];
489
527 };
528 }
529 > stream.ts
530 > /**
531 > * Helper to fully read a T stream into a T or consuming
532 > * a stream fully, awaiting all the events without caring
533 > * about the data.
534 > */
535 > export function consumeStream<T, R = T>(stream: ReadableStreamEvents<T>, reducer: IReducer<T, R>): Promise<R>;
536 > export function consumeStream(stream: ReadableStreamEvents<unknown>): Promise<undefined>;
537 > export function consumeStream<T, R = T>(stream: ReadableStreamEvents<T>, reducer?: IReducer<T, R>): Promise<R | undefined> {
538 > return new Promise((resolve, reject) => { stream.ts
539 > const chunks: T[] = [];
540 >
541 > listenStream(stream, {
542 > onData: chunk => {
543 > if (reducer) { stream.ts
544 > chunks.push(chunk); stream.ts
545 > }
546 > }, stream.ts
547 > onError: error => { stream.ts
548 > if (reducer) { stream.ts
549 reject(error);
550 > } else { stream.ts
551 > resolve(undefined); stream.ts
552 > }
553 > }, stream.ts
554 > onEnd: () => { stream.ts
555 > if (reducer) { stream.ts
556 > resolve(reducer(chunks)); stream.ts
557 > } else { stream.ts
558 > resolve(undefined); stream.ts
559 > }
560 > } stream.ts
561 > }); stream.ts
562 > });
563 > }
564 > stream.ts
565 > export interface IStreamListener<T> {
566 >
567 > /**
568 > * The 'data' event is emitted whenever the stream is
569 > * relinquishing ownership of a chunk of data to a consumer.
570 > */
571 > onData(data: T): void;
572 >
573 > /**
574 > * Emitted when any error occurs.
575 > */
576 > onError(err: Error): void;
577 >
578 > /**
579 > * The 'end' event is emitted when there is no more data
580 > * to be consumed from the stream. The 'end' event will
581 > * not be emitted unless the data is completely consumed.
582 > */
583 > onEnd(): void;
584 > }
585 >
586 > /**
587 > * Helper to listen to all events of a T stream in proper order.
588 > */
589 > export function listenStream<T>(stream: ReadableStreamEvents<T>, listener: IStreamListener<T>, token?: CancellationToken): void {
590 > stream.ts
591 > stream.on('error', error => {
592 > if (!token?.isCancellationRequested) { stream.ts
593 > listener.onError(error); stream.ts
594 > }
595 > }); stream.ts
596 >
597 > stream.on('end', () => {
598 > if (!token?.isCancellationRequested) { stream.ts
599 > listener.onEnd(); stream.ts
600 > }
601 > }); stream.ts
602 >
603 > // Adding the `data` listener will turn the stream
604 > // into flowing mode. As such it is important to
605 > // add this listener last (DO NOT CHANGE!)
606 > stream.on('data', data => {
607 > if (!token?.isCancellationRequested) { stream.ts
608 > listener.onData(data); stream.ts
609 > }
610 > }); stream.ts
611 > }
612 > stream.ts
613 > /**
614 > * Helper to peek up to `maxChunks` into a stream. The return type signals if
615 > * the stream has ended or not. If not, caller needs to add a `data` listener
616 > * to continue reading.
617 > */
618 > export function peekStream<T>(stream: ReadableStream<T>, maxChunks: number): Promise<ReadableBufferedStream<T>> {
619 return new Promise((resolve, reject) => {
620 const streamListeners = new DisposableStore();
666 });
667 }
668 > stream.ts
669 > /**
670 > * Helper to create a readable stream from an existing T.
671 > */
672 > export function toStream<T>(t: T, reducer: IReducer<T>): ReadableStream<T> {
673 > const stream = newWriteableStream<T>(reducer); stream.ts
674 >
675 > stream.end(t);
676 >
677 > return stream;
678 > }
679 > stream.ts
680 > /**
681 > * Helper to create an empty stream
682 > */
683 > export function emptyStream(): ReadableStream<never> {
684 const stream = newWriteableStream<never>(() => { throw new Error('not supported'); });
685 stream.end();
687 return stream;
688 }
689 > stream.ts
690 > /**
691 > * Helper to convert a T into a Readable<T>.
692 > */
693 > export function toReadable<T>(t: T): Readable<T> {
694 let consumed = false;
695
706 };
707 }
708 > stream.ts
709 > /**
710 > * Helper to transform a readable stream into another stream.
711 > */
712 > export function transform<Original, Transformed>(stream: ReadableStreamEvents<Original>, transformer: ITransformer<Original, Transformed>, reducer: IReducer<Transformed>): ReadableStream<Transformed> {
713 const target = newWriteableStream<Transformed>(reducer);
714
721 return target;
722 }
723 > stream.ts
724 > /**
725 > * Helper to take an existing readable that will
726 > * have a prefix injected to the beginning.
727 > */
728 > export function prefixedReadable<T>(prefix: T, readable: Readable<T>, reducer: IReducer<T>): Readable<T> {
729 let prefixHandled = false;
730
751 };
752 }
753 > stream.ts
754 > /**
755 > * Helper to take an existing stream that will
756 > * have a prefix injected to the beginning.
757 > */
758 > export function prefixedStream<T>(prefix: T, stream: ReadableStream<T>, reducer: IReducer<T>): ReadableStream<T> {
759 let prefixHandled = false;
760
src/vs/base/common/uri.ts 503 covered LOC · 118 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- uri.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CharCode } from './charCode.js';
7 > import { MarshalledId } from './marshallingIds.js';
8 > import * as paths from './path.js';
9 > import { isWindows } from './platform.js';
10 >
11 > const _schemePattern = /^\w[\w\d+.-]*$/;
12 > const _singleSlashStart = /^\//;
13 > const _doubleSlashStart = /^\/\//;
14 >
15 > function _validateUri(ret: URI, _strict?: boolean): void { uri.ts
16 >
17 > // scheme, must be set
18 > if (!ret.scheme && _strict) {
19 throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
20 }
21 > uri.ts
22 > // scheme, https://tools.ietf.org/html/rfc3986#section-3.1
23 > // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
24 > if (ret.scheme && !_schemePattern.test(ret.scheme)) { uri.ts
25 const matches = [...ret.scheme.matchAll(/[^\w\d+.-]/gu)];
26 const detail = matches.length > 0
29 throw new Error(`[UriError]: Scheme contains illegal characters.${detail} (len:${ret.scheme.length})`);
30 }
31 > uri.ts
32 > // path, http://tools.ietf.org/html/rfc3986#section-3.3
33 > // If a URI contains an authority component, then the path component
34 > // must either be empty or begin with a slash ("/") character. If a URI
35 > // does not contain an authority component, then the path cannot begin
36 > // with two slash characters ("//").
37 > if (ret.path) {
38 > if (ret.authority) { uri.ts
39 > if (!_singleSlashStart.test(ret.path)) { uri.ts
40 throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
41 }
42 > } else { uri.ts
43 > if (_doubleSlashStart.test(ret.path)) { uri.ts
44 throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
45 }
46 > } uri.ts
47 > } uri.ts
48 > } uri.ts
49 > uri.ts
50 > // for a while we allowed uris *without* schemes and this is the migration
51 > // for them, e.g. an uri without scheme and without strict-mode warns and falls
52 > // back to the file-scheme. that should cause the least carnage and still be a
53 > // clear warning
54 > function _schemeFix(scheme: string, _strict: boolean): string { uri.ts
55 > if (!scheme && !_strict) {
56 return 'file';
57 }
58 > return scheme; uri.ts
59 > }
60 > uri.ts
61 > // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
62 > function _referenceResolution(scheme: string, path: string): string { uri.ts
63 >
64 > // the slash-character is our 'default base' as we don't
65 > // support constructing URIs relative to other URIs. This
66 > // also means that we alter and potentially break paths.
67 > // see https://tools.ietf.org/html/rfc3986#section-5.1.4
68 > switch (scheme) {
69 > case 'https':
70 > case 'http':
71 > case 'file':
72 > if (!path) { uri.ts
73 > path = _slash; uri.ts
74 > } else if (path[0] !== _slash) { uri.ts
75 > path = _slash + path; uri.ts
76 > }
77 > break; uri.ts
78 > } uri.ts
79 > return path;
80 > }
81 > uri.ts
82 > const _empty = '';
83 > const _slash = '/';
84 > const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
85 >
86 > /**
87 > * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
88 > * This class is a simple parser which creates the basic component parts
89 > * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
90 > * and encoding.
91 > *
92 > * ```txt
93 > * foo://example.com:8042/over/there?name=ferret#nose
94 > * \_/ \______________/\_________/ \_________/ \__/
95 > * | | | | |
96 > * scheme authority path query fragment
97 > * | _____________________|__
98 > * / \ / \
99 > * urn:example:animal:ferret:nose
100 > * ```
101 > */
102 > export class URI implements UriComponents {
103 >
104 > static isUri(thing: unknown): thing is URI {
105 if (thing instanceof URI) {
106 return true;
118 && typeof (<URI>thing).toString === 'function';
119 }
120 > uri.ts
121 > /**
122 > * scheme is the 'http' part of 'http://www.example.com/some/path?query#fragment'.
123 > * The part before the first colon.
124 > */
125 > readonly scheme: string;
126 >
127 > /**
128 > * authority is the 'www.example.com' part of 'http://www.example.com/some/path?query#fragment'.
129 > * The part between the first double slashes and the next slash.
130 > */
131 > readonly authority: string;
132 >
133 > /**
134 > * path is the '/some/path' part of 'http://www.example.com/some/path?query#fragment'.
135 > */
136 > readonly path: string;
137 >
138 > /**
139 > * query is the 'query' part of 'http://www.example.com/some/path?query#fragment'.
140 > */
141 > readonly query: string;
142 >
143 > /**
144 > * fragment is the 'fragment' part of 'http://www.example.com/some/path?query#fragment'.
145 > */
146 > readonly fragment: string;
147 >
148 > /**
149 > * @internal
150 > */
151 > protected constructor(scheme: string, authority?: string, path?: string, query?: string, fragment?: string, _strict?: boolean);
152 >
153 > /**
154 > * @internal
155 > */
156 > protected constructor(components: UriComponents);
157 >
158 > /**
159 > * @internal
160 > */
161 > protected constructor(schemeOrData: string | UriComponents, authority?: string, path?: string, query?: string, fragment?: string, _strict: boolean = false) {
162 > uri.ts
163 > if (typeof schemeOrData === 'object') {
164 this.scheme = schemeOrData.scheme || _empty;
165 this.authority = schemeOrData.authority || _empty;
170 // that creates uri components.
171 // _validateUri(this);
172 > } else { uri.ts
173 > this.scheme = _schemeFix(schemeOrData, _strict);
174 > this.authority = authority || _empty;
175 > this.path = _referenceResolution(this.scheme, path || _empty);
176 > this.query = query || _empty;
177 > this.fragment = fragment || _empty;
178 >
179 > _validateUri(this, _strict);
180 > }
181 > }
182 > uri.ts
183 > // ---- filesystem path -----------------------
184 >
185 > /**
186 > * Returns a string representing the corresponding file system path of this URI.
187 > * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
188 > * platform specific path separator.
189 > *
190 > * * Will *not* validate the path for invalid characters and semantics.
191 > * * Will *not* look at the scheme of this URI.
192 > * * The result shall *not* be used for display purposes but for accessing a file on disk.
193 > *
194 > *
195 > * The *difference* to `URI#path` is the use of the platform specific separator and the handling
196 > * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
197 > *
198 > * ```ts
199 > const u = URI.parse('file://server/c$/folder/file.txt')
200 > u.authority === 'server'
201 > u.path === '/shares/c$/file.txt'
202 > u.fsPath === '\\server\c$\folder\file.txt'
203 > ```
204 > *
205 > * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
206 > * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
207 > * with URIs that represent files on disk (`file` scheme).
208 > */
209 > get fsPath(): string {
210 // if (this.scheme !== 'file') {
211 // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
213 return uriToFsPath(this, false);
214 }
215 > uri.ts
216 > // ---- modify to new -------------------------
217 >
218 > with(change: { scheme?: string; authority?: string | null; path?: string | null; query?: string | null; fragment?: string | null }): URI {
219 > uri.ts
220 > if (!change) {
221 return this;
222 }
223 > uri.ts
224 > let { scheme, authority, path, query, fragment } = change;
225 > if (scheme === undefined) {
226 > scheme = this.scheme; uri.ts
227 > } else if (scheme === null) { uri.ts
228 scheme = _empty;
229 }
230 > if (authority === undefined) { uri.ts
231 > authority = this.authority; uri.ts
232 > } else if (authority === null) { uri.ts
233 authority = _empty;
234 }
235 > if (path === undefined) { uri.ts
236 > path = this.path; uri.ts
237 > } else if (path === null) { uri.ts
238 path = _empty;
239 }
240 > if (query === undefined) { uri.ts
241 > query = this.query; uri.ts
242 > } else if (query === null) { uri.ts
243 query = _empty;
244 }
245 > if (fragment === undefined) { uri.ts
246 > fragment = this.fragment; uri.ts
247 > } else if (fragment === null) { uri.ts
248 fragment = _empty;
249 }
250 > uri.ts
251 > if (scheme === this.scheme
252 > && authority === this.authority uri.ts
253 > && path === this.path
254 > && query === this.query uri.ts
255 > && fragment === this.fragment) { uri.ts
256 > uri.ts
257 > return this;
258 > }
259 > uri.ts
260 > return new Uri(scheme, authority, path, query, fragment);
261 > } uri.ts
262 > uri.ts
263 > // ---- parse & validate ------------------------
264 >
265 > /**
266 > * Creates a new URI from a string, e.g. `http://www.example.com/some/path`,
267 > * `file:///usr/home`, or `scheme:with/path`.
268 > *
269 > * @param value A string which represents an URI (see `URI#toString`).
270 > */
271 > static parse(value: string, _strict: boolean = false): URI {
272 > const match = _regexp.exec(value); uri.ts
273 > if (!match) {
274 return new Uri(_empty, _empty, _empty, _empty, _empty);
275 }
276 > return new Uri( uri.ts
277 > match[2] || _empty,
278 > percentDecode(match[4] || _empty),
279 > percentDecode(match[5] || _empty),
280 > percentDecode(match[7] || _empty),
281 > percentDecode(match[9] || _empty),
282 > _strict
283 > );
284 > }
285 > uri.ts
286 > /**
287 > * Creates a new URI from a file system path, e.g. `c:\my\files`,
288 > * `/usr/home`, or `\\server\share\some\path`.
289 > *
290 > * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
291 > * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
292 > * `URI.parse('file://' + path)` because the path might contain characters that are
293 > * interpreted (# and ?). See the following sample:
294 > * ```ts
295 > const good = URI.file('/coding/c#/project1');
296 > good.scheme === 'file';
297 > good.path === '/coding/c#/project1';
298 > good.fragment === '';
299 > const bad = URI.parse('file://' + '/coding/c#/project1');
300 > bad.scheme === 'file';
301 > bad.path === '/coding/c'; // path is now broken
302 > bad.fragment === '/project1';
303 > ```
304 > *
305 > * @param path A file system path (see `URI#fsPath`)
306 > */
307 > static file(path: string): URI {
308 > uri.ts
309 > let authority = _empty;
310 >
311 > // normalize to fwd-slashes on windows,
312 > // on other systems bwd-slashes are valid
313 > // filename character, eg /f\oo/ba\r.txt
314 > if (isWindows) {
315 path = path.replace(/\\/g, _slash);
316 }
317 > uri.ts
318 > // check for authority as used in UNC shares
319 > // or use the path as given
320 > if (path[0] === _slash && path[1] === _slash) {
321 const idx = path.indexOf(_slash, 2);
322 if (idx === -1) {
328 }
329 }
330 > uri.ts
331 > return new Uri('file', authority, path, _empty, _empty);
332 > }
333 > uri.ts
334 > /**
335 > * Creates new URI from uri components.
336 > *
337 > * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs
338 > * validation and should be used for untrusted uri components retrieved from storage,
339 > * user input, command arguments etc
340 > */
341 > static from(components: UriComponents, strict?: boolean): URI {
342 const result = new Uri(
343 components.scheme,
350 return result;
351 }
352 > uri.ts
353 > /**
354 > * Join a URI path with path fragments and normalizes the resulting path.
355 > *
356 > * @param uri The input URI.
357 > * @param pathFragment The path fragment to add to the URI path.
358 > * @returns The resulting URI.
359 > */
360 > static joinPath(uri: URI, ...pathFragment: string[]): URI {
361 > if (!uri.path) { uri.ts
362 throw new Error(`[UriError]: cannot call joinPath on URI without path: ${uri.toString()}`);
363 }
364 > let newPath: string; uri.ts
365 > if (isWindows && uri.scheme === 'file') {
366 newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
367 > } else { uri.ts
368 > newPath = paths.posix.join(uri.path, ...pathFragment);
369 > }
370 > return uri.with({ path: newPath });
371 > }
372 > uri.ts
373 > // ---- printing/externalize ---------------------------
374 >
375 > /**
376 > * Creates a string representation for this URI. It's guaranteed that calling
377 > * `URI.parse` with the result of this function creates an URI which is equal
378 > * to this URI.
379 > *
380 > * * The result shall *not* be used for display purposes but for externalization or transport.
381 > * * The result will be encoded using the percentage encoding and encoding happens mostly
382 > * ignore the scheme-specific encoding rules.
383 > *
384 > * @param skipEncoding Do not encode the result, default is `false`
385 > */
386 > toString(skipEncoding: boolean = false): string {
387 return _asFormatted(this, skipEncoding);
388 }
389 > uri.ts
390 > toJSON(): UriComponents {
391 return this;
392 }
393 > uri.ts
394 > /**
395 > * A helper function to revive URIs.
396 > *
397 > * **Note** that this function should only be used when receiving URI#toJSON generated data
398 > * and that it doesn't do any validation. Use {@link URI.from} when received "untrusted"
399 > * uri components such as command arguments or data from storage.
400 > *
401 > * @param data The URI components or URI to revive.
402 > * @returns The revived URI or undefined or null.
403 > */
404 > static revive(data: UriComponents | URI): URI;
405 > static revive(data: UriComponents | URI | undefined): URI | undefined;
406 > static revive(data: UriComponents | URI | null): URI | null;
407 > static revive(data: UriComponents | URI | undefined | null): URI | undefined | null;
408 > static revive(data: UriComponents | URI | undefined | null): URI | undefined | null {
409 if (!data) {
410 return data;
418 }
419 }
420 > uri.ts
421 > [Symbol.for('debug.description')]() {
422 return `URI(${this.toString()})`;
423 }
424 > } uri.ts
425 >
426 > export interface UriComponents {
427 > scheme: string;
428 > authority?: string;
429 > path?: string;
430 > query?: string;
431 > fragment?: string;
432 > }
433 >
434 > export function isUriComponents(thing: unknown): thing is UriComponents {
435 if (!thing || typeof thing !== 'object') {
436 return false;
442 && (typeof (<UriComponents>thing).fragment === 'string' || typeof (<UriComponents>thing).fragment === 'undefined');
443 }
444 > uri.ts
445 > interface UriState extends UriComponents {
446 > $mid: MarshalledId.Uri;
447 > external?: string;
448 > fsPath?: string;
449 > _sep?: 1;
450 > }
451 >
452 > const _pathSepMarker = isWindows ? 1 : undefined;
453 >
454 > // This class exists so that URI is compatible with vscode.Uri (API).
455 > class Uri extends URI { uri.ts
456 >
457 > _formatted: string | null = null;
458 > _fsPath: string | null = null;
459 > uri.ts
460 > override get fsPath(): string {
461 if (!this._fsPath) {
462 this._fsPath = uriToFsPath(this, false);
464 return this._fsPath;
465 }
466 > uri.ts
467 > override toString(skipEncoding: boolean = false): string {
468 > if (!skipEncoding) { uri.ts
469 > if (!this._formatted) { uri.ts
470 > this._formatted = _asFormatted(this, false);
471 > }
472 > return this._formatted;
473 > } else { uri.ts
474 > // we don't cache that uri.ts
475 > return _asFormatted(this, true);
476 > }
477 > } uri.ts
478 > uri.ts
479 > override toJSON(): UriComponents {
480 // eslint-disable-next-line local/code-no-dangerous-type-assertions
481 const res = <UriState>{
512 return res;
513 }
514 > } uri.ts
515 >
516 > // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
517 > const encodeTable: { [ch: number]: string } = {
518 > [CharCode.Colon]: '%3A', // gen-delims
519 > [CharCode.Slash]: '%2F',
520 > [CharCode.QuestionMark]: '%3F',
521 > [CharCode.Hash]: '%23',
522 > [CharCode.OpenSquareBracket]: '%5B',
523 > [CharCode.CloseSquareBracket]: '%5D',
524 > [CharCode.AtSign]: '%40',
525 >
526 > [CharCode.ExclamationMark]: '%21', // sub-delims
527 > [CharCode.DollarSign]: '%24',
528 > [CharCode.Ampersand]: '%26',
529 > [CharCode.SingleQuote]: '%27',
530 > [CharCode.OpenParen]: '%28',
531 > [CharCode.CloseParen]: '%29',
532 > [CharCode.Asterisk]: '%2A',
533 > [CharCode.Plus]: '%2B',
534 > [CharCode.Comma]: '%2C',
535 > [CharCode.Semicolon]: '%3B',
536 > [CharCode.Equals]: '%3D',
537 >
538 > [CharCode.Space]: '%20',
539 > };
540 >
541 > function encodeURIComponentFast(uriComponent: string, isPath: boolean, isAuthority: boolean): string { uri.ts
542 > let res: string | undefined = undefined;
543 > let nativeEncodePos = -1;
544 >
545 > for (let pos = 0; pos < uriComponent.length; pos++) {
546 > const code = uriComponent.charCodeAt(pos);
547 >
548 > // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3
549 > if (
550 > (code >= CharCode.a && code <= CharCode.z)
551 > || (code >= CharCode.A && code <= CharCode.Z) uri.ts
552 > || (code >= CharCode.Digit0 && code <= CharCode.Digit9)
553 > || code === CharCode.Dash uri.ts
554 > || code === CharCode.Period uri.ts
555 > || code === CharCode.Underline
556 > || code === CharCode.Tilde
557 > || (isPath && code === CharCode.Slash)
558 || (isAuthority && code === CharCode.OpenSquareBracket)
559 || (isAuthority && code === CharCode.CloseSquareBracket)
560 || (isAuthority && code === CharCode.Colon)
561 > ) { uri.ts
562 > // check if we are delaying native encode
563 > if (nativeEncodePos !== -1) {
564 res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
565 nativeEncodePos = -1;
566 }
567 > // check if we write into a new string (by default we try to return the param) uri.ts
568 > if (res !== undefined) {
569 res += uriComponent.charAt(pos);
570 }
571 > uri.ts
572 > } else {
573 // encoding needed, we need to allocate a new string
574 if (res === undefined) {
594 }
595 }
596 > } uri.ts
597 >
598 > if (nativeEncodePos !== -1) {
599 res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
600 }
601 > uri.ts
602 > return res !== undefined ? res : uriComponent;
603 > }
604 > uri.ts
605 > function encodeURIComponentMinimal(path: string): string { uri.ts
606 > let res: string | undefined = undefined;
607 > for (let pos = 0; pos < path.length; pos++) {
608 > const code = path.charCodeAt(pos);
609 > if (code === CharCode.Hash || code === CharCode.QuestionMark) {
610 if (res === undefined) {
611 res = path.substr(0, pos);
612 }
613 res += encodeTable[code];
614 > } else { uri.ts
615 > if (res !== undefined) {
616 res += path[pos];
617 }
618 > } uri.ts
619 > }
620 > return res !== undefined ? res : path;
621 > }
622 > uri.ts
623 > /**
624 > * Compute `fsPath` for the given uri
625 > */
626 > export function uriToFsPath(uri: URI, keepDriveLetterCasing: boolean): string {
627
628 let value: string;
650 return value;
651 }
652 > uri.ts
653 > /**
654 > * Create the external version of a uri
655 > */
656 > function _asFormatted(uri: URI, skipEncoding: boolean): string { uri.ts
657 >
658 > const encoder = !skipEncoding
659 > ? encodeURIComponentFast uri.ts
660 > : encodeURIComponentMinimal; uri.ts
661 > uri.ts
662 > let res = '';
663 > let { scheme, authority, path, query, fragment } = uri;
664 > if (scheme) {
665 > res += scheme;
666 > res += ':';
667 > }
668 > if (authority || scheme === 'file') {
669 > res += _slash; uri.ts
670 > res += _slash;
671 > }
672 > if (authority) { uri.ts
673 > let idx = authority.indexOf('@'); uri.ts
674 > if (idx !== -1) {
675 // <user>@<auth>
676 const userinfo = authority.substr(0, idx);
687 res += '@';
688 }
689 > authority = authority.toLowerCase(); uri.ts
690 > idx = authority.lastIndexOf(':');
691 > if (idx === -1) {
692 > res += encoder(authority, false, true); uri.ts
693 > } else { uri.ts
694 > // <auth>:<port> uri.ts
695 > res += encoder(authority.substr(0, idx), false, true);
696 > res += authority.substr(idx);
697 > }
698 > } uri.ts
699 > if (path) { uri.ts
700 > // lower-case windows drive letters in /C:/fff or C:/fff uri.ts
701 > if (path.length >= 3 && path.charCodeAt(0) === CharCode.Slash && path.charCodeAt(2) === CharCode.Colon) {
702 const code = path.charCodeAt(1);
703 if (code >= CharCode.A && code <= CharCode.Z) {
704 path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3
705 }
706 > } else if (path.length >= 2 && path.charCodeAt(1) === CharCode.Colon) { uri.ts
707 const code = path.charCodeAt(0);
708 if (code >= CharCode.A && code <= CharCode.Z) {
710 }
711 }
712 > // encode the rest of the path uri.ts
713 > res += encoder(path, true, false);
714 > }
715 > if (query) { uri.ts
716 res += '?';
717 res += encoder(query, false, false);
718 }
719 > if (fragment) { uri.ts
720 res += '#';
721 res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
722 }
723 > return res; uri.ts
724 > }
725 > uri.ts
726 > // --- decode
727 >
728 function decodeURIComponentGraceful(str: string): string {
729 try {
737 }
738 }
739 > uri.ts
740 > const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
741 >
742 > function percentDecode(str: string): string { uri.ts
743 > if (!str.match(_rEncodedAsHex)) {
744 > return str;
745 > }
746 return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match));
747 }
748 > uri.ts
749 > /**
750 > * Mapped-type that replaces all occurrences of URI with UriComponents
751 > */
752 > export type UriDto<T> = { [K in keyof T]: T[K] extends URI
753 > ? UriComponents
754 > : UriDto<T[K]> };
src/vs/base/common/strings.ts 490 covered LOC · 115 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- strings.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { LRUCachedFunction } from './cache.js';
7 > import { CharCode } from './charCode.js';
8 > import { Lazy } from './lazy.js';
9 > import { Constants } from './uint.js';
10 >
11 > export function isFalsyOrWhitespace(str: string | undefined): boolean {
12 if (!str || typeof str !== 'string') {
13 return true;
15 return str.trim().length === 0;
16 }
17 > strings.ts
18 > const _formatRegexp = /{(\d+)}/g;
19 >
20 > /**
21 > * Helper to produce a string with a variable number of arguments. Insert variable segments
22 > * into the string using the {n} notation where N is the index of the argument following the string.
23 > * @param value string to which formatting is applied
24 > * @param args replacements for {n}-entries
25 > */
26 > // eslint-disable-next-line @typescript-eslint/no-explicit-any
27 > export function format(value: string, ...args: any[]): string {
28 if (args.length === 0) {
29 return value;
36 });
37 }
38 > strings.ts
39 > const _format2Regexp = /{([^}]+)}/g;
40 >
41 > /**
42 > * Helper to create a string from a template and a string record.
43 > * Similar to `format` but with objects instead of positional arguments.
44 > */
45 > export function format2(template: string, values: Record<string, unknown>): string {
46 if (Object.keys(values).length === 0) {
47 return template;
49 return template.replace(_format2Regexp, (match, group) => (values[group] ?? match) as string);
50 }
51 > strings.ts
52 > /**
53 > * Encodes the given value so that it can be used as literal value in html attributes.
54 > *
55 > * In other words, computes `$val`, such that `attr` in `<div attr="$val" />` has the runtime value `value`.
56 > * This prevents XSS injection.
57 > */
58 > export function htmlAttributeEncodeValue(value: string): string {
59 return value.replace(/[<>"'&]/g, ch => {
60 switch (ch) {
68 });
69 }
70 > strings.ts
71 > /**
72 > * Converts HTML characters inside the string to use entities instead. Makes the string safe from
73 > * being used e.g. in HTMLElement.innerHTML.
74 > */
75 > export function escape(html: string): string {
76 return html.replace(/[<>&]/g, function (match) {
77 switch (match) {
83 });
84 }
85 > strings.ts
86 > /**
87 > * Escapes regular expression characters in a given string
88 > */
89 > export function escapeRegExpCharacters(value: string): string {
90 return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&');
91 }
92 > strings.ts
93 > /**
94 > * Counts how often `substr` occurs inside `value`.
95 > */
96 > export function count(value: string, substr: string): number {
97 let result = 0;
98 let index = value.indexOf(substr);
103 return result;
104 }
105 > strings.ts
106 > export function truncate(value: string, maxLength: number, suffix = Ellipsis): string {
107 if (value.length <= maxLength) {
108 return value;
111 return `${value.substr(0, maxLength)}${suffix}`;
112 }
113 > strings.ts
114 > export function truncateMiddle(value: string, maxLength: number, suffix = Ellipsis): string {
115 if (value.length <= maxLength) {
116 return value;
122 return `${value.substr(0, prefixLength)}${suffix}${value.substr(value.length - suffixLength)}`;
123 }
124 > strings.ts
125 > /**
126 > * Removes all occurrences of needle from the beginning and end of haystack.
127 > * @param haystack string to trim
128 > * @param needle the thing to trim (default is a blank)
129 > */
130 > export function trim(haystack: string, needle: string = ' '): string {
131 const trimmed = ltrim(haystack, needle);
132 return rtrim(trimmed, needle);
133 }
134 > strings.ts
135 > /**
136 > * Removes all occurrences of needle from the beginning of haystack.
137 > * @param haystack string to trim
138 > * @param needle the thing to trim
139 > */
140 > export function ltrim(haystack: string, needle: string): string {
141 if (!haystack || !needle) {
142 return haystack;
157 return haystack.substring(offset);
158 }
159 > strings.ts
160 > /**
161 > * Removes all occurrences of needle from the end of haystack.
162 > * @param haystack string to trim
163 > * @param needle the thing to trim
164 > */
165 > export function rtrim(haystack: string, needle: string): string {
166 if (!haystack || !needle) {
167 return haystack;
187 return haystack.substring(0, offset);
188 }
189 > strings.ts
190 > export function convertSimple2RegExpPattern(pattern: string): string {
191 return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
192 }
193 > strings.ts
194 > export interface RegExpOptions {
195 > matchCase?: boolean;
196 > wholeWord?: boolean;
197 > multiline?: boolean;
198 > global?: boolean;
199 > unicode?: boolean;
200 > }
201 >
202 > export function createRegExp(searchString: string, isRegex: boolean, options: RegExpOptions = {}): RegExp {
203 if (!searchString) {
204 throw new Error('Cannot create regex from empty string');
231 return new RegExp(searchString, modifiers);
232 }
233 > strings.ts
234 > export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean {
235 // Exit early if it's one of these special cases which are meant to match
236 // against an empty string
244 return !!(match && regexp.lastIndex === 0);
245 }
246 > strings.ts
247 > export function joinStrings(items: (string | undefined | null | false)[], separator: string): string {
248 return items.filter(item => item !== undefined && item !== null && item !== false).join(separator);
249 }
250 > strings.ts
251 > export function splitLines(str: string): string[] {
252 return str.split(/\r\n|\r|\n/);
253 }
254 > strings.ts
255 > export function splitLinesIncludeSeparators(str: string): string[] {
256 const linesWithSeparators: string[] = [];
257 const splitLinesAndSeparators = str.split(/(\r\n|\r|\n)/);
261 return linesWithSeparators;
262 }
263 > strings.ts
264 > export function indexOfPattern(str: string, re: RegExp) {
265 const match = re.exec(str);
266 if (match) {
269 return -1;
270 }
271 > strings.ts
272 > /**
273 > * Returns first index of the string that is not whitespace.
274 > * If string is empty or contains only whitespaces, returns -1
275 > */
276 > export function firstNonWhitespaceIndex(str: string): number {
277 for (let i = 0, len = str.length; i < len; i++) {
278 const chCode = str.charCodeAt(i);
283 return -1;
284 }
285 > strings.ts
286 > /**
287 > * Returns the leading whitespace of the string.
288 > * If the string contains only whitespaces, returns entire string
289 > */
290 > export function getLeadingWhitespace(str: string, start: number = 0, end: number = str.length): string {
291 for (let i = start; i < end; i++) {
292 const chCode = str.charCodeAt(i);
297 return str.substring(start, end);
298 }
299 > strings.ts
300 > /**
301 > * Returns last index of the string that is not whitespace.
302 > * If string is empty or contains only whitespaces, returns -1
303 > */
304 > export function lastNonWhitespaceIndex(str: string, startIndex: number = str.length - 1): number {
305 for (let i = startIndex; i >= 0; i--) {
306 const chCode = str.charCodeAt(i);
311 return -1;
312 }
313 > strings.ts
314 > export function getIndentationLength(str: string): number {
315 const idx = firstNonWhitespaceIndex(str);
316 if (idx === -1) { return str.length; }
317 return idx;
318 }
319 > strings.ts
320 > /**
321 > * Function that works identically to String.prototype.replace, except, the
322 > * replace function is allowed to be async and return a Promise.
323 > */
324 > export function replaceAsync(str: string, search: RegExp, replacer: (match: string, ...args: unknown[]) => Promise<string>): Promise<string> {
325 const parts: (string | Promise<string>)[] = [];
326
340 return Promise.all(parts).then(p => p.join(''));
341 }
342 > strings.ts
343 > export function compare(a: string, b: string): number {
344 if (a < b) {
345 return -1;
350 }
351 }
352 > strings.ts
353 > export function compareSubstring(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number {
354 > for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { strings.ts
355 > const codeA = a.charCodeAt(aStart);
356 > const codeB = b.charCodeAt(bStart);
357 > if (codeA < codeB) {
358 return -1;
359 > } else if (codeA > codeB) { strings.ts
360 return 1;
361 }
362 > } strings.ts
363 > const aLen = aEnd - aStart; strings.ts
364 > const bLen = bEnd - bStart;
365 > if (aLen < bLen) {
366 return -1;
367 > } else if (aLen > bLen) { strings.ts
368 return 1;
369 }
370 > return 0; strings.ts
371 > }
372 > strings.ts
373 > export function compareIgnoreCase(a: string, b: string): number {
374 > return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length); strings.ts
375 > }
376 > strings.ts
377 > export function compareSubstringIgnoreCase(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number {
378 > strings.ts
379 > for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
380 >
381 > let codeA = a.charCodeAt(aStart);
382 > let codeB = b.charCodeAt(bStart);
383 >
384 > if (codeA === codeB) {
385 > // equal strings.ts
386 > continue;
387 > }
388
389 > if (codeA >= 128 || codeB >= 128) { strings.ts
390 // not ASCII letters -> fallback to lower-casing strings
391 return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
409 return diff;
410 }
411 > strings.ts
412 > const aLen = aEnd - aStart;
413 > const bLen = bEnd - bStart;
414 >
415 > if (aLen < bLen) {
416 return -1;
417 > } else if (aLen > bLen) { strings.ts
418 return 1;
419 }
420 > strings.ts
421 > return 0;
422 > }
423 > strings.ts
424 > export function isAsciiDigit(code: number): boolean {
425 return code >= CharCode.Digit0 && code <= CharCode.Digit9;
426 }
427 > strings.ts
428 > export function isLowerAsciiLetter(code: number): boolean {
429 return code >= CharCode.a && code <= CharCode.z;
430 }
431 > strings.ts
432 > export function isUpperAsciiLetter(code: number): boolean {
433 return code >= CharCode.A && code <= CharCode.Z;
434 }
435 > strings.ts
436 > export function equalsIgnoreCase(a: string, b: string): boolean {
437 return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0;
438 }
439 > strings.ts
440 > export function equals(a: string | undefined, b: string | undefined, ignoreCase?: boolean): boolean {
441 return a === b || (!!ignoreCase && a !== undefined && b !== undefined && equalsIgnoreCase(a, b));
442 }
443 > strings.ts
444 > export function startsWithIgnoreCase(str: string, candidate: string): boolean {
445 const len = candidate.length;
446 return len <= str.length && compareSubstringIgnoreCase(str, candidate, 0, len) === 0;
447 }
448 > strings.ts
449 > export function endsWithIgnoreCase(str: string, candidate: string): boolean {
450 const len = str.length;
451 const start = len - candidate.length;
452 return start >= 0 && compareSubstringIgnoreCase(str, candidate, start, len) === 0;
453 }
454 > strings.ts
455 > /**
456 > * @returns the length of the common prefix of the two strings.
457 > */
458 > export function commonPrefixLength(a: string, b: string): number {
459
460 const len = Math.min(a.length, b.length);
469 return len;
470 }
471 > strings.ts
472 > /**
473 > * @returns the length of the common suffix of the two strings.
474 > */
475 > export function commonSuffixLength(a: string, b: string): number {
476
477 const len = Math.min(a.length, b.length);
489 return len;
490 }
491 > strings.ts
492 > /**
493 > * See http://en.wikipedia.org/wiki/Surrogate_pair
494 > */
495 > export function isHighSurrogate(charCode: number): boolean {
496 return (0xD800 <= charCode && charCode <= 0xDBFF);
497 }
498 > strings.ts
499 > /**
500 > * See http://en.wikipedia.org/wiki/Surrogate_pair
501 > */
502 > export function isLowSurrogate(charCode: number): boolean {
503 return (0xDC00 <= charCode && charCode <= 0xDFFF);
504 }
505 > strings.ts
506 > /**
507 > * See http://en.wikipedia.org/wiki/Surrogate_pair
508 > */
509 > export function computeCodePoint(highSurrogate: number, lowSurrogate: number): number {
510 return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;
511 }
512 > strings.ts
513 > /**
514 > * get the code point that begins at offset `offset`
515 > */
516 > export function getNextCodePoint(str: string, len: number, offset: number): number {
517 const charCode = str.charCodeAt(offset);
518 if (isHighSurrogate(charCode) && offset + 1 < len) {
524 return charCode;
525 }
526 > strings.ts
527 > /**
528 > * get the code point that ends right before offset `offset`
529 > */
530 function getPrevCodePoint(str: string, offset: number): number {
531 const charCode = str.charCodeAt(offset - 1);
538 return charCode;
539 }
540 > strings.ts
541 > export class CodePointIterator {
542 >
543 > private readonly _str: string;
544 > private readonly _len: number;
545 > private _offset: number;
546 >
547 > public get offset(): number {
548 return this._offset;
549 }
550 > strings.ts
551 > constructor(str: string, offset: number = 0) {
552 this._str = str;
553 this._len = str.length;
554 this._offset = offset;
555 }
556 > strings.ts
557 > public setOffset(offset: number): void {
558 this._offset = offset;
559 }
560 > strings.ts
561 > public prevCodePoint(): number {
562 const codePoint = getPrevCodePoint(this._str, this._offset);
563 this._offset -= (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
564 return codePoint;
565 }
566 > strings.ts
567 > public nextCodePoint(): number {
568 const codePoint = getNextCodePoint(this._str, this._len, this._offset);
569 this._offset += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
570 return codePoint;
571 }
572 > strings.ts
573 > public eol(): boolean {
574 return (this._offset >= this._len);
575 }
576 > } strings.ts
577 >
578 > export class GraphemeIterator {
579 >
580 > private readonly _iterator: CodePointIterator;
581 >
582 > public get offset(): number {
583 return this._iterator.offset;
584 }
585 > strings.ts
586 > constructor(str: string, offset: number = 0) {
587 this._iterator = new CodePointIterator(str, offset);
588 }
589 > strings.ts
590 > public nextGraphemeLength(): number {
591 const graphemeBreakTree = GraphemeBreakTree.getInstance();
592 const iterator = this._iterator;
606 return (iterator.offset - initialOffset);
607 }
608 > strings.ts
609 > public prevGraphemeLength(): number {
610 const graphemeBreakTree = GraphemeBreakTree.getInstance();
611 const iterator = this._iterator;
625 return (initialOffset - iterator.offset);
626 }
627 > strings.ts
628 > public eol(): boolean {
629 return this._iterator.eol();
630 }
631 > } strings.ts
632 >
633 > export function nextCharLength(str: string, initialOffset: number): number {
634 const iterator = new GraphemeIterator(str, initialOffset);
635 return iterator.nextGraphemeLength();
636 }
637 > strings.ts
638 > export function prevCharLength(str: string, initialOffset: number): number {
639 const iterator = new GraphemeIterator(str, initialOffset);
640 return iterator.prevGraphemeLength();
641 }
642 > strings.ts
643 > export function getCharContainingOffset(str: string, offset: number): [number, number] {
644 if (offset > 0 && isLowSurrogate(str.charCodeAt(offset))) {
645 offset--;
649 return [startOffset, endOffset];
650 }
651 > strings.ts
652 > export function charCount(str: string): number {
653 const iterator = new GraphemeIterator(str);
654 let length = 0;
659 return length;
660 }
661 > strings.ts
662 > let CONTAINS_RTL: RegExp | undefined = undefined;
663 >
664 function makeContainsRtl() {
665 // Generated using https://github.com/alexdima/unicode-utils/blob/main/rtl-test.js
666 return /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/;
667 }
668 > strings.ts
669 > /**
670 > * Returns true if `str` contains any Unicode character that is classified as "R" or "AL".
671 > */
672 > export function containsRTL(str: string): boolean {
673 if (!CONTAINS_RTL) {
674 CONTAINS_RTL = makeContainsRtl();
677 return CONTAINS_RTL.test(str);
678 }
679 > strings.ts
680 > const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
681 > /**
682 > * Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t
683 > */
684 > export function isBasicASCII(str: string): boolean {
685 return IS_BASIC_ASCII.test(str);
686 }
687 > strings.ts
688 > export const UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/; // LINE SEPARATOR (LS) or PARAGRAPH SEPARATOR (PS)
689 > /**
690 > * Returns true if `str` contains unusual line terminators, like LS or PS
691 > */
692 > export function containsUnusualLineTerminators(str: string): boolean {
693 return UNUSUAL_LINE_TERMINATORS.test(str);
694 }
695 > strings.ts
696 > export function isFullWidthCharacter(charCode: number): boolean {
697 // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns
698 // http://jrgraphix.net/research/unicode_blocks.php
741 );
742 }
743 > strings.ts
744 > /**
745 > * A fast function (therefore imprecise) to check if code points are emojis.
746 > * Generated using https://github.com/alexdima/unicode-utils/blob/main/emoji-test.js
747 > */
748 > export function isEmojiImprecise(x: number): boolean {
749 return (
750 (x >= 0x1F1E6 && x <= 0x1F1FF) || (x === 8986) || (x === 8987) || (x === 9200)
755 );
756 }
757 > strings.ts
758 > /**
759 > * Given a string and a max length returns a shorted version. Shorting
760 > * happens at favorable positions - such as whitespace or punctuation characters.
761 > * The return value can be longer than the given value of `n`. Leading whitespace is always trimmed.
762 > */
763 > export function lcut(text: string, n: number, prefix = ''): string {
764 const trimmed = text.trimStart();
765
785 return prefix + trimmed.substring(i).trimStart();
786 }
787 > strings.ts
788 > /**
789 > * Given a string and a max length returns a shortened version keeping the beginning.
790 > * Shortening happens at favorable positions - such as whitespace or punctuation characters.
791 > * Trailing whitespace is always trimmed.
792 > */
793 > export function rcut(text: string, n: number, suffix = ''): string {
794 const trimmed = text.trimEnd();
795
832 return result + suffix;
833 }
834 > strings.ts
835 > // Defacto standard: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
836 > const CSI_SEQUENCE = /(?:\x1b\[|\x9b)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~]/;
837 > const OSC_SEQUENCE = /(?:\x1b\]|\x9d).*?(?:\x1b\\|\x07|\x9c)/;
838 > const ESC_SEQUENCE = /\x1b(?:[ #%\(\)\*\+\-\.\/]?[a-zA-Z0-9\|}~@])/;
839 > const CONTROL_SEQUENCES = new RegExp('(?:' + [
840 > CSI_SEQUENCE.source,
841 > OSC_SEQUENCE.source,
842 > ESC_SEQUENCE.source,
843 > ].join('|') + ')', 'g');
844 >
845 > /** Iterates over parts of a string with CSI sequences */
846 > export function* forAnsiStringParts(str: string) {
847 let last = 0;
848 for (const match of str.matchAll(CONTROL_SEQUENCES)) {
859 }
860 }
861 > strings.ts
862 > /**
863 > * Strips ANSI escape sequences from a string.
864 > * @param str The dastringa stringo strip the ANSI escape sequences from.
865 > *
866 > * @example
867 > * removeAnsiEscapeCodes('\u001b[31mHello, World!\u001b[0m');
868 > * // 'Hello, World!'
869 > */
870 > export function removeAnsiEscapeCodes(str: string): string {
871 if (str) {
872 str = str.replace(CONTROL_SEQUENCES, '');
875 return str;
876 }
877 > strings.ts
878 > const PROMPT_NON_PRINTABLE = /\\\[.*?\\\]/g;
879 >
880 > /**
881 > * Strips ANSI escape sequences from a UNIX-style prompt string (eg. `$PS1`).
882 > * @param str The string to strip the ANSI escape sequences from.
883 > *
884 > * @example
885 > * removeAnsiEscapeCodesFromPrompt('\n\\[\u001b[01;34m\\]\\w\\[\u001b[00m\\]\n\\[\u001b[1;32m\\]> \\[\u001b[0m\\]');
886 > * // '\n\\w\n> '
887 > */
888 > export function removeAnsiEscapeCodesFromPrompt(str: string): string {
889 return removeAnsiEscapeCodes(str).replace(PROMPT_NON_PRINTABLE, '');
890 }
891 > strings.ts
892 >
893 > // -- UTF-8 BOM
894 >
895 > export const UTF8_BOM_CHARACTER = String.fromCharCode(CharCode.UTF8_BOM);
896 >
897 > export function startsWithUTF8BOM(str: string): boolean {
898 return !!(str && str.length > 0 && str.charCodeAt(0) === CharCode.UTF8_BOM);
899 }
900 > strings.ts
901 > export function stripUTF8BOM(str: string): string {
902 return startsWithUTF8BOM(str) ? str.substr(1) : str;
903 }
904 > strings.ts
905 > /**
906 > * Checks if the characters of the provided query string are included in the
907 > * target string. The characters do not have to be contiguous within the string.
908 > */
909 > export function fuzzyContains(target: string, query: string): boolean {
910 if (!target || !query) {
911 return false; // return early if target or query are undefined
936 return true;
937 }
938 > strings.ts
939 > export function containsUppercaseCharacter(target: string, ignoreEscapedChars = false): boolean {
940 if (!target) {
941 return false;
948 return target.toLowerCase() !== target;
949 }
950 > strings.ts
951 > export function uppercaseFirstLetter(str: string): string {
952 > return str.charAt(0).toUpperCase() + str.slice(1); strings.ts
953 > }
954 > strings.ts
955 > export function getNLines(str: string, n = 1): string {
956 if (n === 0) {
957 return '';
974 return str.substr(0, idx);
975 }
976 > strings.ts
977 > /**
978 > * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.
979 > */
980 > export function singleLetterHash(n: number): string {
981 const LETTERS_CNT = (CharCode.Z - CharCode.A + 1);
982
989 return String.fromCharCode(CharCode.A + n - LETTERS_CNT);
990 }
991 > strings.ts
992 > //#region Unicode Grapheme Break
993 >
994 > export function getGraphemeBreakType(codePoint: number): GraphemeBreakType {
995 const graphemeBreakTree = GraphemeBreakTree.getInstance();
996 return graphemeBreakTree.getGraphemeBreakType(codePoint);
997 }
998 > strings.ts
999 function breakBetweenGraphemeBreakType(breakTypeA: GraphemeBreakType, breakTypeB: GraphemeBreakType): boolean {
1000 // http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules
1076 return true;
1077 }
1078 > strings.ts
1079 > export const enum GraphemeBreakType {
1080 > Other = 0,
1081 > Prepend = 1,
1082 > CR = 2,
1083 > LF = 3,
1084 > Control = 4,
1085 > Extend = 5,
1086 > Regional_Indicator = 6,
1087 > SpacingMark = 7,
1088 > L = 8,
1089 > V = 9,
1090 > T = 10,
1091 > LV = 11,
1092 > LVT = 12,
1093 > ZWJ = 13,
1094 > Extended_Pictographic = 14
1095 > }
1096 >
1097 > class GraphemeBreakTree {
1098 >
1099 > private static _INSTANCE: GraphemeBreakTree | null = null;
1100 > public static getInstance(): GraphemeBreakTree {
1101 if (!GraphemeBreakTree._INSTANCE) {
1102 GraphemeBreakTree._INSTANCE = new GraphemeBreakTree();
1104 return GraphemeBreakTree._INSTANCE;
1105 }
1106 > strings.ts
1107 > private readonly _data: number[];
1108 >
1109 > constructor() {
1110 this._data = getGraphemeBreakRawData();
1111 }
1112 > strings.ts
1113 > public getGraphemeBreakType(codePoint: number): GraphemeBreakType {
1114 // !!! Let's make 7bit ASCII a bit faster: 0..31
1115 if (codePoint < 32) {
1145 return GraphemeBreakType.Other;
1146 }
1147 > } strings.ts
1148 >
1149 function getGraphemeBreakRawData(): number[] {
1150 // generated using https://github.com/alexdima/unicode-utils/blob/main/grapheme-break.js
1151 return JSON.parse('[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]');
1152 }
1153 > strings.ts
1154 > //#endregion
1155 >
1156 > /**
1157 > * Computes the offset after performing a left delete on the given string,
1158 > * while considering unicode grapheme/emoji rules.
1159 > */
1160 > export function getLeftDeleteOffset(offset: number, str: string): number {
1161 if (offset === 0) {
1162 return 0;
1174 return iterator.offset;
1175 }
1176 > strings.ts
1177 function getOffsetBeforeLastEmojiComponent(initialOffset: number, str: string): number | undefined {
1178 // See https://www.unicode.org/reports/tr51/tr51-14.html#EBNF_and_Regex for the
1210 return resultOffset;
1211 }
1212 > strings.ts
1213 function isEmojiModifier(codePoint: number): boolean {
1214 return 0x1F3FB <= codePoint && codePoint <= 0x1F3FF;
1215 }
1216 > strings.ts
1217 > const enum CodePoint {
1218 > zwj = 0x200D,
1219 >
1220 > /**
1221 > * Variation Selector-16 (VS16)
1222 > */
1223 > emojiVariantSelector = 0xFE0F,
1224 >
1225 > /**
1226 > * Combining Enclosing Keycap
1227 > */
1228 > enclosingKeyCap = 0x20E3,
1229 >
1230 > space = 0x0020,
1231 > }
1232 >
1233 > export const noBreakWhitespace = '\xa0';
1234 >
1235 > export class AmbiguousCharacters {
1236 > private static readonly ambiguousCharacterData = new Lazy<
1237 > Record<
1238 > string | '_common' | '_default',
1239 > /* code point -> ascii code point */ number[]
1240 > >
1241 > >(() => {
1242 // Generated using https://github.com/hediet/vscode-unicode-data
1243 // Stored as key1, value1, key2, value2, ...
1245 '{\"_common\":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,1523,96,8242,96,1370,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,118002,50,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,118003,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,118004,52,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,118005,53,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,118006,54,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,118007,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,118008,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,118009,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,117974,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,117975,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71913,67,71922,67,65315,67,8557,67,8450,67,8493,67,117976,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,117977,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,117978,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,117979,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,117980,71,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,117981,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,117983,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,117984,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,118001,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,117982,108,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,117985,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,117986,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,117987,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,118000,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,117988,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,117989,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,117990,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,117991,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,117992,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,117993,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,117994,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,117995,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71910,87,71919,87,117996,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,117997,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,117998,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,71909,90,66293,90,65338,90,8484,90,8488,90,117999,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65283,35,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125,119846,109],\"_default\":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"cs\":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"de\":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"es\":[8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"fr\":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"it\":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"ja\":[8211,45,8218,44,65281,33,8216,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65292,44,65297,49,65307,59],\"ko\":[8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"pl\":[65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"pt-BR\":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"qps-ploc\":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"ru\":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"tr\":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],\"zh-hans\":[160,32,65374,126,8218,44,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65297,49],\"zh-hant\":[8211,45,65374,126,8218,44,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89]}'
1246 );
1247 > }); strings.ts
1248 >
1249 > private static readonly cache = new LRUCachedFunction<string, AmbiguousCharacters>((localesStr) => {
1250 const locales = localesStr.split(',');
1251
1304
1305 return new AmbiguousCharacters(map);
1306 > }); strings.ts
1307 >
1308 > public static getInstance(locales: Iterable<string>): AmbiguousCharacters {
1309 return AmbiguousCharacters.cache.get(Array.from(locales).join(','));
1310 }
1311 > strings.ts
1312 > private static _locales = new Lazy<string[]>(() =>
1313 Object.keys(AmbiguousCharacters.ambiguousCharacterData.value).filter(
1314 (k) => !k.startsWith('_')
1315 )
1316 > ); strings.ts
1317 > public static getLocales(): string[] {
1318 return AmbiguousCharacters._locales.value;
1319 }
1320 > strings.ts
1321 > private constructor(
1322 private readonly confusableDictionary: Map<number, number>
1323 ) { }
1324 > strings.ts
1325 > public isAmbiguous(codePoint: number): boolean {
1326 return this.confusableDictionary.has(codePoint);
1327 }
1328 > strings.ts
1329 > public containsAmbiguousCharacter(str: string): boolean {
1330 for (let i = 0; i < str.length; i++) {
1331 const codePoint = str.codePointAt(i);
1336 return false;
1337 }
1338 > strings.ts
1339 > /**
1340 > * Returns the non basic ASCII code point that the given code point can be confused,
1341 > * or undefined if such code point does note exist.
1342 > */
1343 > public getPrimaryConfusable(codePoint: number): number | undefined {
1344 return this.confusableDictionary.get(codePoint);
1345 }
1346 > strings.ts
1347 > public getConfusableCodePoints(): ReadonlySet<number> {
1348 return new Set(this.confusableDictionary.keys());
1349 }
1350 > } strings.ts
1351 >
1352 > export class InvisibleCharacters {
1353 > private static getRawData(): Record<string | '_common', number[]> {
1354 // Generated using https://github.com/hediet/vscode-unicode-data
1355 return JSON.parse('{\"_common\":[11,12,13,127,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999],\"cs\":[173,8203,12288],\"de\":[173,8203,12288],\"es\":[8203,12288],\"fr\":[173,8203,12288],\"it\":[160,173,12288],\"ja\":[173],\"ko\":[173,12288],\"pl\":[173,8203,12288],\"pt-BR\":[173,8203,12288],\"qps-ploc\":[160,173,8203,12288],\"ru\":[173,12288],\"tr\":[160,173,8203,12288],\"zh-hans\":[160,173,8203,12288],\"zh-hant\":[173,12288]}');
1356 }
1357 > strings.ts
1358 > private static _data: Set<number> | undefined = undefined;
1359 >
1360 > private static getData() {
1361 if (!this._data) {
1362 this._data = new Set([...Object.values(InvisibleCharacters.getRawData())].flat());
1364 return this._data;
1365 }
1366 > strings.ts
1367 > public static isInvisibleCharacter(codePoint: number): boolean {
1368 return InvisibleCharacters.getData().has(codePoint);
1369 }
1370 > strings.ts
1371 > public static containsInvisibleCharacter(str: string): boolean {
1372 for (let i = 0; i < str.length; i++) {
1373 const codePoint = str.codePointAt(i);
1378 return false;
1379 }
1380 > strings.ts
1381 > public static get codePoints(): ReadonlySet<number> {
1382 return InvisibleCharacters.getData();
1383 }
1384 > } strings.ts
1385 >
1386 > export const Ellipsis = '\u2026';
1387 >
1388 > /**
1389 > * Convert a Unicode string to a string in which each 16-bit unit occupies only one byte
1390 > *
1391 > * From https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa
1392 > */
1393 function toBinary(str: string): string {
1394 const codeUnits = new Uint16Array(str.length);
1403 return binary;
1404 }
1405 > strings.ts
1406 > /**
1407 > * Version of the global `btoa` function that handles multi-byte characters instead
1408 > * of throwing an exception.
1409 > */
1410 >
1411 > export function multibyteAwareBtoa(str: string): string {
1412 return btoa(toBinary(str));
1413 }
src/vs/platform/extensions/common/extensions.ts 486 covered LOC · 25 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensions.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import Severity from '../../../base/common/severity.js';
7 > import * as strings from '../../../base/common/strings.js';
8 > import { URI } from '../../../base/common/uri.js';
9 > import { ILocalizedString } from '../../action/common/action.js';
10 > import { ExtensionKind } from '../../environment/common/environment.js';
11 > import { createDecorator } from '../../instantiation/common/instantiation.js';
12 > import { getRemoteName } from '../../remote/common/remoteHosts.js';
13 >
14 > export const USER_MANIFEST_CACHE_FILE = 'extensions.user.cache';
15 > export const BUILTIN_MANIFEST_CACHE_FILE = 'extensions.builtin.cache';
16 > export const UNDEFINED_PUBLISHER = 'undefined_publisher';
17 >
18 > export interface ICommand {
19 > command: string;
20 > title: string | ILocalizedString;
21 > category?: string | ILocalizedString;
22 > }
23 >
24 > export interface IDebugger {
25 > label?: string;
26 > type: string;
27 > runtime?: string;
28 > }
29 >
30 > export interface IGrammar {
31 > language?: string;
32 > }
33 >
34 > export interface IJSONValidation {
35 > fileMatch: string | string[];
36 > url: string;
37 > }
38 >
39 > export interface IJSONValidationRegistry {
40 > url: string;
41 > }
42 >
43 > export interface IKeyBinding {
44 > command: string;
45 > key: string;
46 > when?: string;
47 > mac?: string;
48 > linux?: string;
49 > win?: string;
50 > }
51 >
52 > export interface ILanguage {
53 > id: string;
54 > extensions: string[];
55 > aliases: string[];
56 > }
57 >
58 > export interface IMenu {
59 > command: string;
60 > alt?: string;
61 > when?: string;
62 > group?: string;
63 > }
64 >
65 > export interface ISnippet {
66 > language: string;
67 > }
68 >
69 > export interface ITheme {
70 > label: string;
71 > }
72 >
73 > export interface IViewContainer {
74 > id: string;
75 > title: string;
76 > }
77 >
78 > export interface IView {
79 > id: string;
80 > name: string;
81 > }
82 >
83 > export interface IColor {
84 > id: string;
85 > description: string;
86 > defaults: { light: string; dark: string; highContrast: string };
87 > }
88 >
89 > interface IWebviewEditor {
90 > readonly viewType: string;
91 > readonly priority: string;
92 > readonly selector: readonly {
93 > readonly filenamePattern?: string;
94 > }[];
95 > }
96 >
97 > export interface ICodeActionContributionAction {
98 > readonly kind: string;
99 > readonly title: string;
100 > readonly description?: string;
101 > }
102 >
103 > export interface ICodeActionContribution {
104 > readonly languages: readonly string[];
105 > readonly actions: readonly ICodeActionContributionAction[];
106 > }
107 >
108 > export interface IAuthenticationContribution {
109 > readonly id: string;
110 > readonly label: string;
111 > readonly authorizationServerGlobs?: string[];
112 > }
113 >
114 > export interface IWalkthroughStep {
115 > readonly id: string;
116 > readonly title: string;
117 > readonly description: string | undefined;
118 > readonly media:
119 > | { image: string | { dark: string; light: string; hc: string }; altText: string; markdown?: never; svg?: never; video?: never }
120 > | { markdown: string; image?: never; svg?: never; video?: never }
121 > | { svg: string; altText: string; markdown?: never; image?: never; video?: never }
122 > | { video: string | { dark: string; light: string; hc: string }; poster: string | { dark: string; light: string; hc: string }; altText: string; markdown?: never; image?: never; svg?: never };
123 > readonly completionEvents?: string[];
124 > /** @deprecated use `completionEvents: 'onCommand:...'` */
125 > readonly doneOn?: { command: string };
126 > readonly when?: string;
127 > }
128 >
129 > export interface IWalkthrough {
130 > readonly id: string;
131 > readonly title: string;
132 > readonly icon?: string;
133 > readonly description: string;
134 > readonly steps: IWalkthroughStep[];
135 > readonly featuredFor: string[] | undefined;
136 > readonly when?: string;
137 > }
138 >
139 > export interface IStartEntry {
140 > readonly title: string;
141 > readonly description: string;
142 > readonly command: string;
143 > readonly when?: string;
144 > readonly category: 'file' | 'folder' | 'notebook';
145 > }
146 >
147 > export interface INotebookEntry {
148 > readonly type: string;
149 > readonly displayName: string;
150 > }
151 >
152 > export interface INotebookRendererContribution {
153 > readonly id: string;
154 > readonly displayName: string;
155 > readonly mimeTypes: string[];
156 > }
157 >
158 > export interface IDebugVisualizationContribution {
159 > readonly id: string;
160 > readonly when: string;
161 > }
162 >
163 > export interface ITranslation {
164 > id: string;
165 > path: string;
166 > }
167 >
168 > export interface ILocalizationContribution {
169 > languageId: string;
170 > languageName?: string;
171 > localizedLanguageName?: string;
172 > translations: ITranslation[];
173 > minimalTranslations?: { [key: string]: string };
174 > }
175 >
176 > export interface IChatParticipantContribution {
177 > id: string;
178 > name: string;
179 > fullName: string;
180 > description?: string;
181 > isDefault?: boolean;
182 > commands?: { name: string }[];
183 > }
184 >
185 > export interface IToolContribution {
186 > name: string;
187 > displayName: string;
188 > modelDescription: string;
189 > userDescription?: string;
190 > }
191 >
192 > export interface IToolSetContribution {
193 > name: string;
194 > referenceName: string;
195 > description: string;
196 > icon?: string;
197 > tools: string[];
198 > }
199 >
200 > export interface IMcpCollectionContribution {
201 > readonly id: string;
202 > readonly label: string;
203 > readonly when?: string;
204 > }
205 >
206 > export interface IChatFileContribution {
207 > readonly path: string;
208 > readonly name?: string;
209 > readonly description?: string;
210 > readonly when?: string;
211 > readonly sessionTypes?: readonly string[];
212 > }
213 >
214 > export interface IExtensionContributions {
215 > commands?: ICommand[];
216 > configuration?: any;
217 > configurationDefaults?: any;
218 > debuggers?: IDebugger[];
219 > grammars?: IGrammar[];
220 > jsonValidation?: IJSONValidation[];
221 > jsonValidationRegistry?: IJSONValidationRegistry[];
222 > keybindings?: IKeyBinding[];
223 > languages?: ILanguage[];
224 > menus?: { [context: string]: IMenu[] };
225 > snippets?: ISnippet[];
226 > themes?: ITheme[];
227 > iconThemes?: ITheme[];
228 > productIconThemes?: ITheme[];
229 > viewsContainers?: { [location: string]: IViewContainer[] };
230 > views?: { [location: string]: IView[] };
231 > colors?: IColor[];
232 > localizations?: ILocalizationContribution[];
233 > readonly customEditors?: readonly IWebviewEditor[];
234 > readonly codeActions?: readonly ICodeActionContribution[];
235 > authentication?: IAuthenticationContribution[];
236 > walkthroughs?: IWalkthrough[];
237 > startEntries?: IStartEntry[];
238 > readonly notebooks?: INotebookEntry[];
239 > readonly notebookRenderer?: INotebookRendererContribution[];
240 > readonly debugVisualizers?: IDebugVisualizationContribution[];
241 > readonly chatParticipants?: ReadonlyArray<IChatParticipantContribution>;
242 > readonly chatPromptFiles?: ReadonlyArray<IChatFileContribution>;
243 > readonly chatInstructions?: ReadonlyArray<IChatFileContribution>;
244 > readonly chatAgents?: ReadonlyArray<IChatFileContribution>;
245 > readonly chatSkills?: ReadonlyArray<IChatFileContribution>;
246 > readonly chatPlugins?: ReadonlyArray<IChatFileContribution>;
247 > readonly languageModelTools?: ReadonlyArray<IToolContribution>;
248 > readonly languageModelToolSets?: ReadonlyArray<IToolSetContribution>;
249 > readonly mcpServerDefinitionProviders?: ReadonlyArray<IMcpCollectionContribution>;
250 > }
251 >
252 > export interface IExtensionCapabilities {
253 > readonly virtualWorkspaces?: ExtensionVirtualWorkspaceSupport;
254 > readonly untrustedWorkspaces?: ExtensionUntrustedWorkspaceSupport;
255 > }
256 >
257 >
258 > export const ALL_EXTENSION_KINDS: readonly ExtensionKind[] = ['ui', 'workspace', 'web'];
259 >
260 > export type LimitedWorkspaceSupportType = 'limited';
261 > export type ExtensionUntrustedWorkspaceSupportType = boolean | LimitedWorkspaceSupportType;
262 > export type ExtensionUntrustedWorkspaceSupport = { supported: true } | { supported: false; description: string } | { supported: LimitedWorkspaceSupportType; description: string; restrictedConfigurations?: string[] };
263 >
264 > export type ExtensionVirtualWorkspaceSupportType = boolean | LimitedWorkspaceSupportType;
265 > export type ExtensionVirtualWorkspaceSupport = boolean | { supported: true } | { supported: false | LimitedWorkspaceSupportType; description: string };
266 >
267 > export function getWorkspaceSupportTypeMessage(supportType: ExtensionUntrustedWorkspaceSupport | ExtensionVirtualWorkspaceSupport | undefined): string | undefined {
268 if (typeof supportType === 'object' && supportType !== null) {
269 if (supportType.supported !== true) {
273 return undefined;
274 }
276 >
277 > export interface IExtensionIdentifier {
278 > id: string;
279 > uuid?: string;
280 > }
281 >
282 > export const EXTENSION_CATEGORIES = [
283 > 'AI',
284 > 'Azure',
285 > 'Chat',
286 > 'Data Science',
287 > 'Debuggers',
288 > 'Extension Packs',
289 > 'Education',
290 > 'Formatters',
291 > 'Keymaps',
292 > 'Language Packs',
293 > 'Linters',
294 > 'Machine Learning',
295 > 'Notebooks',
296 > 'Programming Languages',
297 > 'SCM Providers',
298 > 'Snippets',
299 > 'Testing',
300 > 'Themes',
301 > 'Visualization',
302 > 'Other',
303 > ];
304 >
305 > export interface IRelaxedExtensionManifest {
306 > name: string;
307 > displayName?: string;
308 > publisher: string;
309 > version: string;
310 > engines: { readonly vscode: string };
311 > description?: string;
312 > main?: string;
313 > type?: string;
314 > browser?: string;
315 > preview?: boolean;
316 > // For now this only supports pointing to l10n bundle files
317 > // but it will be used for package.l10n.json files in the future
318 > l10n?: string;
319 > icon?: string;
320 > categories?: string[];
321 > keywords?: string[];
322 > activationEvents?: readonly string[];
323 > extensionDependencies?: string[];
324 > extensionAffinity?: string[];
325 > extensionPack?: string[];
326 > extensionKind?: ExtensionKind | ExtensionKind[];
327 > contributes?: IExtensionContributions;
328 > repository?: { url: string };
329 > bugs?: { url: string };
330 > originalEnabledApiProposals?: readonly string[];
331 > enabledApiProposals?: readonly string[];
332 > api?: string;
333 > scripts?: { [key: string]: string };
334 > capabilities?: IExtensionCapabilities;
335 > }
336 >
337 > export type IExtensionManifest = Readonly<IRelaxedExtensionManifest>;
338 >
339 > export const enum ExtensionType {
340 > System,
341 > User
342 > }
343 >
344 > export const enum TargetPlatform {
345 > WIN32_X64 = 'win32-x64',
346 > WIN32_ARM64 = 'win32-arm64',
347 >
348 > LINUX_X64 = 'linux-x64',
349 > LINUX_ARM64 = 'linux-arm64',
350 > LINUX_ARMHF = 'linux-armhf',
351 >
352 > ALPINE_X64 = 'alpine-x64',
353 > ALPINE_ARM64 = 'alpine-arm64',
354 >
355 > DARWIN_X64 = 'darwin-x64',
356 > DARWIN_ARM64 = 'darwin-arm64',
357 >
358 > WEB = 'web',
359 >
360 > UNIVERSAL = 'universal',
361 > UNKNOWN = 'unknown',
362 > UNDEFINED = 'undefined',
363 > }
364 >
365 > export interface IExtension {
366 > readonly type: ExtensionType;
367 > readonly isBuiltin: boolean;
368 > readonly identifier: IExtensionIdentifier;
369 > readonly manifest: IExtensionManifest;
370 > readonly location: URI;
371 > readonly targetPlatform: TargetPlatform;
372 > readonly publisherDisplayName?: string;
373 > readonly readmeUrl?: URI;
374 > readonly changelogUrl?: URI;
375 > readonly isValid: boolean;
376 > readonly validations: readonly [Severity, string][];
377 > readonly preRelease: boolean;
378 > }
379 >
380 > /**
381 > * **!Do not construct directly!**
382 > *
383 > * **!Only static methods because it gets serialized!**
384 > *
385 > * This represents the "canonical" version for an extension identifier. Extension ids
386 > * have to be case-insensitive (due to the marketplace), but we must ensure case
387 > * preservation because the extension API is already public at this time.
388 > *
389 > * For example, given an extension with the publisher `"Hello"` and the name `"World"`,
390 > * its canonical extension identifier is `"Hello.World"`. This extension could be
391 > * referenced in some other extension's dependencies using the string `"hello.world"`.
392 > *
393 > * To make matters more complicated, an extension can optionally have an UUID. When two
394 > * extensions have the same UUID, they are considered equal even if their identifier is different.
395 > */
396 > export class ExtensionIdentifier {
397 > public readonly value: string;
398 >
399 > /**
400 > * Do not use directly. This is public to avoid mangling and thus
401 > * allow compatibility between running from source and a built version.
402 > */
403 > readonly _lower: string;
404 >
405 > constructor(value: string) {
406 > this.value = value; extensions.ts
407 > this._lower = value.toLowerCase();
408 > }
410 > public static equals(a: ExtensionIdentifier | string | null | undefined, b: ExtensionIdentifier | string | null | undefined) {
411 if (typeof a === 'undefined' || a === null) {
412 return (typeof b === 'undefined' || b === null);
426 return (a._lower === b._lower);
427 }
429 > /**
430 > * Gives the value by which to index (for equality).
431 > */
432 > public static toKey(id: ExtensionIdentifier | string): string {
433 if (typeof id === 'string') {
434 return id.toLowerCase();
436 return id._lower;
437 }
438 > } extensions.ts
439 >
440 > export class ExtensionIdentifierSet {
441 >
442 > private readonly _set = new Set<string>();
443 >
444 > public get size(): number {
445 > return this._set.size;
446 > }
447 >
448 > constructor(iterable?: Iterable<ExtensionIdentifier | string>) {
449 if (iterable) {
450 for (const value of iterable) {
453 }
454 }
456 > public add(id: ExtensionIdentifier | string): void {
457 this._set.add(ExtensionIdentifier.toKey(id));
458 }
460 > public delete(extensionId: ExtensionIdentifier): boolean {
461 return this._set.delete(ExtensionIdentifier.toKey(extensionId));
462 }
464 > public has(id: ExtensionIdentifier | string): boolean {
465 return this._set.has(ExtensionIdentifier.toKey(id));
466 }
467 > } extensions.ts
468 >
469 > export class ExtensionIdentifierMap<T> {
470
471 private readonly _map = new Map<string, T>();
473 > public clear(): void {
474 this._map.clear();
475 }
477 > public delete(id: ExtensionIdentifier | string): void {
478 this._map.delete(ExtensionIdentifier.toKey(id));
479 }
481 > public get(id: ExtensionIdentifier | string): T | undefined {
482 return this._map.get(ExtensionIdentifier.toKey(id));
483 }
485 > public has(id: ExtensionIdentifier | string): boolean {
486 return this._map.has(ExtensionIdentifier.toKey(id));
487 }
489 > public set(id: ExtensionIdentifier | string, value: T): void {
490 this._map.set(ExtensionIdentifier.toKey(id), value);
491 }
493 > public values(): IterableIterator<T> {
494 return this._map.values();
495 }
497 > forEach(callbackfn: (value: T, key: string, map: Map<string, T>) => void): void {
498 this._map.forEach(callbackfn);
499 }
501 > [Symbol.iterator](): IterableIterator<[string, T]> {
502 return this._map[Symbol.iterator]();
503 }
504 > } extensions.ts
505 >
506 > /**
507 > * An error that is clearly from an extension, identified by the `ExtensionIdentifier`
508 > */
509 > export class ExtensionError extends Error {
510 >
511 > readonly extension: ExtensionIdentifier;
512 >
513 > constructor(extensionIdentifier: ExtensionIdentifier, cause: Error, message?: string) {
514 const detail = message && cause?.message ? `${message}: ${cause.message}` : (message ?? cause?.message);
515 super(`Error in extension ${ExtensionIdentifier.toKey(extensionIdentifier)}: ${detail}`, { cause });
523 }
524 }
525 > } extensions.ts
526 >
527 > export interface IRelaxedExtensionDescription extends IRelaxedExtensionManifest {
528 > id?: string;
529 > identifier: ExtensionIdentifier;
530 > uuid?: string;
531 > publisherDisplayName?: string;
532 > targetPlatform: TargetPlatform;
533 > isBuiltin: boolean;
534 > isUserBuiltin: boolean;
535 > isUnderDevelopment: boolean;
536 > extensionLocation: URI;
537 > preRelease: boolean;
538 > }
539 >
540 > export type IExtensionDescription = Readonly<IRelaxedExtensionDescription>;
541 >
542 > export function isApplicationScopedExtension(manifest: IExtensionManifest): boolean {
543 return isLanguagePackExtension(manifest);
544 }
546 > export function isLanguagePackExtension(manifest: IExtensionManifest): boolean {
547 return manifest.contributes && manifest.contributes.localizations ? manifest.contributes.localizations.length > 0 : false;
548 }
550 > export function isAuthenticationProviderExtension(manifest: IExtensionManifest): boolean {
551 return manifest.contributes && manifest.contributes.authentication ? manifest.contributes.authentication.length > 0 : false;
552 }
554 > export function isResolverExtension(manifest: IExtensionManifest, remoteAuthority: string | undefined): boolean {
555 if (remoteAuthority) {
556 const activationEvent = `onResolveRemoteAuthority:${getRemoteName(remoteAuthority)}`;
559 return false;
560 }
562 > export function parseEnabledApiProposalNames(enabledApiProposals: string[]): string[] {
563 return enabledApiProposals.map(proposal => proposal.split('@')[0]);
564 }
566 > export const IBuiltinExtensionsScannerService = createDecorator<IBuiltinExtensionsScannerService>('IBuiltinExtensionsScannerService');
567 > export interface IBuiltinExtensionsScannerService {
568 > readonly _serviceBrand: undefined;
569 > scanBuiltinExtensions(): Promise<IExtension[]>;
570 > }
src/vs/platform/userDataSync/common/userDataSyncService.ts 461 covered LOC · 109 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSyncService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { equals } from '../../../base/common/arrays.js';
7 > import { CancelablePromise, createCancelablePromise, RunOnceScheduler } from '../../../base/common/async.js';
8 > import { CancellationToken, CancellationTokenSource } from '../../../base/common/cancellation.js';
9 > import { toErrorMessage } from '../../../base/common/errorMessage.js';
10 > import { Emitter, Event } from '../../../base/common/event.js';
11 > import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../base/common/lifecycle.js';
12 > import { isEqual } from '../../../base/common/resources.js';
13 > import { isBoolean, isUndefined } from '../../../base/common/types.js';
14 > import { URI } from '../../../base/common/uri.js';
15 > import { generateUuid } from '../../../base/common/uuid.js';
16 > import { IConfigurationService } from '../../configuration/common/configuration.js';
17 > import { IExtensionGalleryService } from '../../extensionManagement/common/extensionManagement.js';
18 > import { IFileService } from '../../files/common/files.js';
19 > import { IInstantiationService } from '../../instantiation/common/instantiation.js';
20 > import { IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
21 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
22 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
23 > import { ExtensionsSynchroniser } from './extensionsSync.js';
24 > import { GlobalStateSynchroniser } from './globalStateSync.js';
25 > import { KeybindingsSynchroniser } from './keybindingsSync.js';
26 > import { PromptsSynchronizer } from './promptsSync/promptsSync.js';
27 > import { SettingsSynchroniser } from './settingsSync.js';
28 > import { SnippetsSynchroniser } from './snippetsSync.js';
29 > import { TasksSynchroniser } from './tasksSync.js';
30 > import { McpSynchroniser } from './mcpSync.js';
31 > import { UserDataProfilesManifestSynchroniser } from './userDataProfilesManifestSync.js';
32 > import {
33 > ALL_SYNC_RESOURCES, createSyncHeaders, IUserDataManualSyncTask, IUserDataSyncResourceConflicts, IUserDataSyncResourceError,
34 > IUserDataSyncResource, ISyncResourceHandle, IUserDataSyncTask, ISyncUserDataProfile, IUserDataManifest, IUserDataSyncConfiguration,
35 > IUserDataSyncEnablementService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncService, IUserDataSyncStoreManagementService, IUserDataSyncStoreService,
36 > SyncResource, SyncStatus, UserDataSyncError, UserDataSyncErrorCode, UserDataSyncStoreError, USER_DATA_SYNC_CONFIGURATION_SCOPE, IUserDataSyncResourceProviderService, IUserDataSyncActivityData, IUserDataSyncLocalStoreService,
37 > IUserDataSyncLatestData,
38 > IUserData,
39 > isUserDataManifest,
40 > } from './userDataSync.js';
41 >
42 > type SyncErrorClassification = {
43 > owner: 'sandy081';
44 > comment: 'Information about the error that occurred while syncing';
45 > code: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'error code' };
46 > service: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Settings Sync service for which this error has occurred' };
47 > serverCode?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Settings Sync service error code' };
48 > url?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Settings Sync resource URL for which this error has occurred' };
49 > resource?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Settings Sync resource for which this error has occurred' };
50 > executionId?: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Settings Sync execution id for which this error has occurred' };
51 > };
52 >
53 > type SyncErrorEvent = {
54 > code: string;
55 > service: string;
56 > serverCode?: string;
57 > url?: string;
58 > resource?: string;
59 > executionId?: string;
60 > };
61 >
62 > const LAST_SYNC_TIME_KEY = 'sync.lastSyncTime';
63 >
64 > export class UserDataSyncService extends Disposable implements IUserDataSyncService {
65 >
66 > _serviceBrand: undefined;
67 >
68 > private _status: SyncStatus = SyncStatus.Uninitialized;
69 > get status(): SyncStatus { return this._status; }
70 > private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>());
71 > readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event;
72 >
73 > private _onDidChangeLocal = this._register(new Emitter<SyncResource>());
74 > readonly onDidChangeLocal = this._onDidChangeLocal.event;
75 >
76 > private _conflicts: IUserDataSyncResourceConflicts[] = [];
77 > get conflicts(): IUserDataSyncResourceConflicts[] { return this._conflicts; }
78 > private _onDidChangeConflicts = this._register(new Emitter<IUserDataSyncResourceConflicts[]>());
79 > readonly onDidChangeConflicts = this._onDidChangeConflicts.event;
80 >
81 > private _syncErrors: IUserDataSyncResourceError[] = [];
82 > private _onSyncErrors = this._register(new Emitter<IUserDataSyncResourceError[]>());
83 > readonly onSyncErrors = this._onSyncErrors.event;
84 >
85 > private _lastSyncTime: number | undefined = undefined;
86 > get lastSyncTime(): number | undefined { return this._lastSyncTime; }
87 > private _onDidChangeLastSyncTime: Emitter<number> = this._register(new Emitter<number>());
88 > readonly onDidChangeLastSyncTime: Event<number> = this._onDidChangeLastSyncTime.event;
89 >
90 > private _onDidResetLocal = this._register(new Emitter<void>());
91 > readonly onDidResetLocal = this._onDidResetLocal.event;
92 >
93 > private _onDidResetRemote = this._register(new Emitter<void>());
94 > readonly onDidResetRemote = this._onDidResetRemote.event;
95 >
96 > private activeProfileSynchronizers = new Map<string, [ProfileSynchronizer, IDisposable]>();
97 >
98 > constructor(
99 > @IFileService private readonly fileService: IFileService, userDataSyncService.ts
100 > @IUserDataSyncStoreService private readonly userDataSyncStoreService: IUserDataSyncStoreService,
101 > @IUserDataSyncStoreManagementService private readonly userDataSyncStoreManagementService: IUserDataSyncStoreManagementService,
102 > @IInstantiationService private readonly instantiationService: IInstantiationService,
103 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
104 > @ITelemetryService private readonly telemetryService: ITelemetryService,
105 > @IStorageService private readonly storageService: IStorageService,
106 > @IUserDataSyncEnablementService private readonly userDataSyncEnablementService: IUserDataSyncEnablementService,
107 > @IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService,
108 > @IUserDataSyncResourceProviderService private readonly userDataSyncResourceProviderService: IUserDataSyncResourceProviderService,
109 > @IUserDataSyncLocalStoreService private readonly userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
110 > ) {
111 > super();
112 > this._status = userDataSyncStoreManagementService.userDataSyncStore ? SyncStatus.Idle : SyncStatus.Uninitialized;
113 > this._lastSyncTime = this.storageService.getNumber(LAST_SYNC_TIME_KEY, StorageScope.APPLICATION, undefined);
114 > this._register(toDisposable(() => this.clearActiveProfileSynchronizers()));
115 >
116 > this._register(new RunOnceScheduler(() => this.cleanUpStaleStorageData(), 5 * 1000 /* after 5s */)).schedule();
117 > }
119 > async createSyncTask(manifest: IUserDataManifest | null, disableCache?: boolean): Promise<IUserDataSyncTask> {
120 > this.checkEnablement(); userDataSyncService.ts
121 >
122 > this.logService.info('Sync started.');
123 > const startTime = new Date().getTime();
124 > const executionId = generateUuid();
125 > try {
126 > const syncHeaders = createSyncHeaders(executionId);
127 > if (disableCache) {
128 syncHeaders['Cache-Control'] = 'no-cache';
129 }
130 > manifest = await this.userDataSyncStoreService.manifest(manifest, syncHeaders); userDataSyncService.ts
131 > } catch (error) {
132 const userDataSyncError = UserDataSyncError.toUserDataSyncError(error);
133 reportUserDataSyncError(userDataSyncError, executionId, this.userDataSyncStoreManagementService, this.telemetryService);
134 throw userDataSyncError;
135 }
137 > const executed = false;
138 > const that = this;
139 > let cancellablePromise: CancelablePromise<void> | undefined;
140 > return {
141 > manifest,
142 > async run(): Promise<void> {
143 > if (executed) {
144 throw new Error('Can run a task only once');
145 }
146 > cancellablePromise = createCancelablePromise(token => that.sync(manifest, false, executionId, token)); userDataSyncService.ts
147 > await cancellablePromise.finally(() => cancellablePromise = undefined);
148 > that.logService.info(`Sync done. Took ${new Date().getTime() - startTime}ms`); userDataSyncService.ts
149 > that.updateLastSyncTime();
151 > stop(): Promise<void> {
152 cancellablePromise?.cancel();
153 return that.stop();
154 }
156 > }
158 > async createManualSyncTask(): Promise<IUserDataManualSyncTask> {
159 this.checkEnablement();
160
230 };
231 }
233 > private async sync(manifestOrLatestData: IUserDataManifest | IUserDataSyncLatestData | null, preview: boolean, executionId: string, token: CancellationToken): Promise<void> {
234 > this._syncErrors = []; userDataSyncService.ts
235 > try {
236 > if (this.status !== SyncStatus.HasConflicts) {
237 > this.setStatus(SyncStatus.Syncing);
238 > }
239 >
240 > // Sync Default Profile First
241 > const defaultProfileSynchronizer = this.getOrCreateActiveProfileSynchronizer(this.userDataProfilesService.defaultProfile, undefined);
242 > this._syncErrors.push(...await this.syncProfile(defaultProfileSynchronizer, manifestOrLatestData, preview, executionId, token));
244 > // Sync other profiles
245 > const userDataProfileManifestSynchronizer = defaultProfileSynchronizer.enabled.find(s => s.resource === SyncResource.Profiles);
246 > if (userDataProfileManifestSynchronizer) {
247 > const syncProfiles = (await (userDataProfileManifestSynchronizer as UserDataProfilesManifestSynchroniser).getLastSyncedProfiles()) || [];
248 > if (token.isCancellationRequested) {
249 return;
250 }
251 > await this.syncRemoteProfiles(syncProfiles, manifestOrLatestData, preview, executionId, token); userDataSyncService.ts
252 > }
253 > } finally { userDataSyncService.ts
254 > if (this.status !== SyncStatus.HasConflicts) {
255 > this.setStatus(SyncStatus.Idle);
256 > }
257 > this._onSyncErrors.fire(this._syncErrors);
258 > }
259 > }
261 > private async syncRemoteProfiles(remoteProfiles: ISyncUserDataProfile[], manifest: IUserDataManifest | IUserDataSyncLatestData | null, preview: boolean, executionId: string, token: CancellationToken): Promise<void> {
262 > for (const syncProfile of remoteProfiles) { userDataSyncService.ts
263 if (token.isCancellationRequested) {
264 return;
273 this._syncErrors.push(...await this.syncProfile(profileSynchronizer, manifest, preview, executionId, token));
274 }
275 > // Dispose & Delete profile synchronizers which do not exist anymore userDataSyncService.ts
276 > for (const [key, profileSynchronizerItem] of this.activeProfileSynchronizers.entries()) {
277 > if (this.userDataProfilesService.profiles.some(p => p.id === profileSynchronizerItem[0].profile.id)) {
278 > continue;
279 > }
280 await profileSynchronizerItem[0].resetLocal();
281 profileSynchronizerItem[1].dispose();
282 this.activeProfileSynchronizers.delete(key);
283 }
286 > private async applyManualSync(manifestOrLatestData: IUserDataManifest | IUserDataSyncLatestData | null, executionId: string, token: CancellationToken): Promise<void> {
287 try {
288 this.setStatus(SyncStatus.Syncing);
315 }
316 }
318 > private async syncProfile(profileSynchronizer: ProfileSynchronizer, manifestOrLatestData: IUserDataManifest | IUserDataSyncLatestData | null, preview: boolean, executionId: string, token: CancellationToken): Promise<IUserDataSyncResourceError[]> {
319 > const errors = await profileSynchronizer.sync(manifestOrLatestData, preview, executionId, token); userDataSyncService.ts
320 > return errors.map(([syncResource, error]) => ({ profile: profileSynchronizer.profile, syncResource, error })); userDataSyncService.ts
323 > private async stop(): Promise<void> {
324 if (this.status !== SyncStatus.Idle) {
325 await Promise.allSettled(this.getActiveProfileSynchronizers().map(profileSynchronizer => profileSynchronizer.stop()));
326 }
327 }
329 > async resolveContent(resource: URI): Promise<string | null> {
330 const content = await this.userDataSyncResourceProviderService.resolveContent(resource);
331 if (content) {
342 return null;
343 }
345 > async replace(syncResourceHandle: ISyncResourceHandle): Promise<void> {
346 this.checkEnablement();
347
366 return;
367 }
369 > async accept(syncResource: IUserDataSyncResource, resource: URI, content: string | null | undefined, apply: boolean | { force: boolean }): Promise<void> {
370 this.checkEnablement();
371
381 });
382 }
384 > async hasLocalData(): Promise<boolean> {
385 const result = await this.performAction(this.userDataProfilesService.defaultProfile, async synchronizer => {
386 // skip global state synchronizer
392 return !!result;
393 }
395 > async hasPreviouslySynced(): Promise<boolean> {
396 const result = await this.performAction(this.userDataProfilesService.defaultProfile, async synchronizer => {
397 if (await synchronizer.hasPreviouslySynced()) {
402 return !!result;
403 }
405 > async reset(): Promise<void> {
406 > this.checkEnablement(); userDataSyncService.ts
407 > await this.resetRemote();
408 > await this.resetLocal();
409 > }
411 > async resetRemote(): Promise<void> {
412 > this.checkEnablement(); userDataSyncService.ts
413 > try {
414 > await this.userDataSyncStoreService.clear();
415 > this.logService.info('Cleared data on server');
416 > } catch (e) {
417 this.logService.error(e);
418 }
419 > this._onDidResetRemote.fire(); userDataSyncService.ts
420 > }
422 > async resetLocal(): Promise<void> {
423 > this.checkEnablement(); userDataSyncService.ts
424 > this._lastSyncTime = undefined;
425 > this.storageService.remove(LAST_SYNC_TIME_KEY, StorageScope.APPLICATION);
426 > for (const [synchronizer] of this.activeProfileSynchronizers.values()) {
427 > try {
428 > await synchronizer.resetLocal();
429 > } catch (e) {
430 this.logService.error(e);
431 }
433 > this.clearActiveProfileSynchronizers();
434 > this._onDidResetLocal.fire();
435 > this.logService.info('Did reset the local sync state.');
436 > }
438 > private async cleanUpStaleStorageData(): Promise<void> {
439 const allKeys = this.storageService.keys(StorageScope.APPLICATION, StorageTarget.MACHINE);
440 const lastSyncProfileKeys: [string, string][] = [];
475 }
476 }
478 > async cleanUpRemoteData(): Promise<void> {
479 const remoteProfiles = await this.userDataSyncResourceProviderService.getRemoteSyncedProfiles();
480 const remoteProfileCollections = remoteProfiles.map(profile => profile.collection);
501 }
502 }
504 > async saveRemoteActivityData(location: URI): Promise<void> {
505 this.checkEnablement();
506 const data = await this.userDataSyncStoreService.getActivityData();
507 await this.fileService.writeFile(location, data);
508 }
510 > async extractActivityData(activityDataResource: URI, location: URI): Promise<void> {
511 const content = (await this.fileService.readFile(activityDataResource)).value.toString();
512 const activityData: IUserDataSyncActivityData = JSON.parse(content);
530 }
531 }
533 > private async performAction<T>(profile: IUserDataProfile, action: (synchroniser: IUserDataSynchroniser) => Promise<T | undefined>): Promise<T | null> {
534 const disposables = new DisposableStore();
535 try {
561 }
562 }
564 > private async performActionWithProfileSynchronizer<T>(profileSynchronizer: ProfileSynchronizer, action: (synchroniser: IUserDataSynchroniser) => Promise<T | undefined>, disposables: DisposableStore): Promise<T | undefined> {
565 const allSynchronizers = [...profileSynchronizer.enabled, ...profileSynchronizer.disabled.reduce<(IUserDataSynchroniser & IDisposable)[]>((synchronizers, syncResource) => {
566 if (syncResource !== SyncResource.WorkspaceState) {
577 return undefined;
578 }
580 > private setStatus(status: SyncStatus): void {
581 > const oldStatus = this._status; userDataSyncService.ts
582 > if (this._status !== status) {
583 > this._status = status;
584 > this._onDidChangeStatus.fire(status);
585 > if (oldStatus === SyncStatus.HasConflicts) {
586 this.updateLastSyncTime();
587 }
589 > }
591 > private updateConflicts(): void {
592 const conflicts = this.getActiveProfileSynchronizers().map(synchronizer => synchronizer.conflicts).flat();
593 if (!equals(this._conflicts, conflicts, (a, b) => a.profile.id === b.profile.id && a.syncResource === b.syncResource && equals(a.conflicts, b.conflicts, (a, b) => isEqual(a.previewResource, b.previewResource)))) {
596 }
597 }
599 > private updateLastSyncTime(): void {
600 > if (this.status === SyncStatus.Idle) { userDataSyncService.ts
601 > this._lastSyncTime = new Date().getTime();
602 > this.storageService.store(LAST_SYNC_TIME_KEY, this._lastSyncTime, StorageScope.APPLICATION, StorageTarget.MACHINE);
603 > this._onDidChangeLastSyncTime.fire(this._lastSyncTime);
604 > }
605 > }
607 > getOrCreateActiveProfileSynchronizer(profile: IUserDataProfile, syncProfile: ISyncUserDataProfile | undefined): ProfileSynchronizer {
608 > let activeProfileSynchronizer = this.activeProfileSynchronizers.get(profile.id); userDataSyncService.ts
609 > if (activeProfileSynchronizer && activeProfileSynchronizer[0].collection !== syncProfile?.collection) {
610 this.logService.error('Profile synchronizer collection does not match with the remote sync profile collection');
611 activeProfileSynchronizer[1].dispose();
613 this.activeProfileSynchronizers.delete(profile.id);
614 }
615 > if (!activeProfileSynchronizer) { userDataSyncService.ts
616 > const disposables = new DisposableStore();
617 > const profileSynchronizer = disposables.add(this.instantiationService.createInstance(ProfileSynchronizer, profile, syncProfile?.collection));
618 > disposables.add(profileSynchronizer.onDidChangeStatus(e => this.setStatus(e)));
619 > disposables.add(profileSynchronizer.onDidChangeConflicts(conflicts => this.updateConflicts()));
620 > disposables.add(profileSynchronizer.onDidChangeLocal(e => this._onDidChangeLocal.fire(e)));
621 > this.activeProfileSynchronizers.set(profile.id, activeProfileSynchronizer = [profileSynchronizer, disposables]);
622 > }
623 > return activeProfileSynchronizer[0];
624 > }
626 > private getActiveProfileSynchronizers(): ProfileSynchronizer[] {
627 const profileSynchronizers: ProfileSynchronizer[] = [];
628 for (const [profileSynchronizer] of this.activeProfileSynchronizers.values()) {
631 return profileSynchronizers;
632 }
634 > private clearActiveProfileSynchronizers(): void {
635 > this.activeProfileSynchronizers.forEach(([, disposable]) => disposable.dispose()); userDataSyncService.ts
636 > this.activeProfileSynchronizers.clear();
637 > }
639 > private checkEnablement(): void {
640 > if (!this.userDataSyncStoreManagementService.userDataSyncStore) { userDataSyncService.ts
641 throw new Error('Not enabled');
642 }
645 > }
646 >
647 >
648 > class ProfileSynchronizer extends Disposable {
649 >
650 > private _enabled: [IUserDataSynchroniser, number, IDisposable][] = [];
651 > get enabled(): IUserDataSynchroniser[] { return this._enabled.sort((a, b) => a[1] - b[1]).map(([synchronizer]) => synchronizer); }
652 >
653 > get disabled(): SyncResource[] { return ALL_SYNC_RESOURCES.filter(syncResource => !this.userDataSyncEnablementService.isResourceEnabled(syncResource)); }
654 >
655 > private _status: SyncStatus = SyncStatus.Idle;
656 > get status(): SyncStatus { return this._status; }
657 > private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>());
658 > readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event;
659 >
660 > private _onDidChangeLocal = this._register(new Emitter<SyncResource>());
661 > readonly onDidChangeLocal = this._onDidChangeLocal.event;
662 >
663 > private _conflicts: IUserDataSyncResourceConflicts[] = [];
664 > get conflicts(): IUserDataSyncResourceConflicts[] { return this._conflicts; }
665 > private _onDidChangeConflicts = this._register(new Emitter<IUserDataSyncResourceConflicts[]>());
666 > readonly onDidChangeConflicts = this._onDidChangeConflicts.event;
667 >
668 > constructor(
669 > readonly profile: IUserDataProfile, userDataSyncService.ts
670 > readonly collection: string | undefined,
671 > @IUserDataSyncEnablementService private readonly userDataSyncEnablementService: IUserDataSyncEnablementService,
672 > @IInstantiationService private readonly instantiationService: IInstantiationService,
673 > @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService,
674 > @IUserDataSyncStoreManagementService private readonly userDataSyncStoreManagementService: IUserDataSyncStoreManagementService,
675 > @ITelemetryService private readonly telemetryService: ITelemetryService,
676 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
677 > @IConfigurationService private readonly configurationService: IConfigurationService,
678 > ) {
679 > super();
680 > this._register(userDataSyncEnablementService.onDidChangeResourceEnablement(([syncResource, enablement]) => this.onDidChangeResourceEnablement(syncResource, enablement)));
681 > this._register(toDisposable(() => this._enabled.splice(0, this._enabled.length).forEach(([, , disposable]) => disposable.dispose())));
682 > for (const syncResource of ALL_SYNC_RESOURCES) {
683 > if (userDataSyncEnablementService.isResourceEnabled(syncResource)) {
684 > this.registerSynchronizer(syncResource);
685 > }
686 > }
687 > }
689 > private onDidChangeResourceEnablement(syncResource: SyncResource, enabled: boolean): void {
690 if (enabled) {
691 this.registerSynchronizer(syncResource);
694 }
695 }
697 > protected registerSynchronizer(syncResource: SyncResource): void {
698 > if (this._enabled.some(([synchronizer]) => synchronizer.resource === syncResource)) { userDataSyncService.ts
699 return;
700 }
701 > if (syncResource === SyncResource.Extensions && !this.extensionGalleryService.isEnabled()) { userDataSyncService.ts
702 this.logService.info('Skipping extensions sync because gallery is not configured');
703 return;
704 }
705 > if (syncResource === SyncResource.Profiles) { userDataSyncService.ts
706 > if (!this.profile.isDefault) {
707 return;
708 }
710 > if (syncResource === SyncResource.WorkspaceState) {
711 return;
712 }
713 > if (syncResource !== SyncResource.Profiles && this.profile.useDefaultFlags?.[syncResource]) { userDataSyncService.ts
714 this.logService.debug(`Skipping syncing ${syncResource} in ${this.profile.name} because it is already synced by default profile`);
715 return;
716 }
717 > const disposables = new DisposableStore(); userDataSyncService.ts
718 > const synchronizer = disposables.add(this.createSynchronizer(syncResource));
719 > disposables.add(synchronizer.onDidChangeStatus(() => this.updateStatus()));
720 > disposables.add(synchronizer.onDidChangeConflicts(() => this.updateConflicts()));
721 > disposables.add(synchronizer.onDidChangeLocal(() => this._onDidChangeLocal.fire(syncResource)));
722 > const order = this.getOrder(syncResource);
723 > this._enabled.push([synchronizer, order, disposables]);
724 > }
726 > private deRegisterSynchronizer(syncResource: SyncResource): void {
727 const index = this._enabled.findIndex(([synchronizer]) => synchronizer.resource === syncResource);
728 if (index !== -1) {
733 }
734 }
736 > createSynchronizer(syncResource: Exclude<SyncResource, SyncResource.WorkspaceState>): IUserDataSynchroniser & IDisposable {
737 > switch (syncResource) { userDataSyncService.ts
738 > case SyncResource.Settings: return this.instantiationService.createInstance(SettingsSynchroniser, this.profile, this.collection);
739 > case SyncResource.Keybindings: return this.instantiationService.createInstance(KeybindingsSynchroniser, this.profile, this.collection);
740 > case SyncResource.Snippets: return this.instantiationService.createInstance(SnippetsSynchroniser, this.profile, this.collection);
741 > case SyncResource.Prompts: return this.instantiationService.createInstance(PromptsSynchronizer, this.profile, this.collection);
742 > case SyncResource.Tasks: return this.instantiationService.createInstance(TasksSynchroniser, this.profile, this.collection);
743 > case SyncResource.Mcp: return this.instantiationService.createInstance(McpSynchroniser, this.profile, this.collection);
744 > case SyncResource.GlobalState: return this.instantiationService.createInstance(GlobalStateSynchroniser, this.profile, this.collection);
745 > case SyncResource.Extensions: return this.instantiationService.createInstance(ExtensionsSynchroniser, this.profile, this.collection);
746 > case SyncResource.Profiles: return this.instantiationService.createInstance(UserDataProfilesManifestSynchroniser, this.profile, this.collection);
747 > }
748 > }
750 > async sync(manifestOrLatestData: IUserDataManifest | IUserDataSyncLatestData | null, preview: boolean, executionId: string, token: CancellationToken): Promise<[SyncResource, UserDataSyncError][]> {
752 > // Return if cancellation is requested
753 > if (token.isCancellationRequested) {
754 return [];
755 }
757 > const synchronizers = this.enabled;
758 > if (!synchronizers.length) {
759 return [];
760 }
762 > try {
763 > const syncErrors: [SyncResource, UserDataSyncError][] = [];
764 > const syncHeaders = createSyncHeaders(executionId);
765 > const userDataSyncConfiguration = preview ? await this.getUserDataSyncConfiguration(manifestOrLatestData) : this.getLocalUserDataSyncConfiguration();
766 > for (const synchroniser of synchronizers) {
767 > // Return if cancellation is requested
768 > if (token.isCancellationRequested) {
769 return [];
770 }
772 > // Return if resource is not enabled
773 > if (!this.userDataSyncEnablementService.isResourceEnabled(synchroniser.resource)) {
774 return [];
775 }
777 > try {
778 > const refOrUserData = getRefOrUserData(manifestOrLatestData, this.collection, synchroniser.resource) ?? null;
779 > await synchroniser.sync(refOrUserData, preview, userDataSyncConfiguration, syncHeaders);
780 > } catch (e) {
781 const userDataSyncError = UserDataSyncError.toUserDataSyncError(e);
782 reportUserDataSyncError(userDataSyncError, executionId, this.userDataSyncStoreManagementService, this.telemetryService);
790 syncErrors.push([synchroniser.resource, userDataSyncError]);
791 }
794 > return syncErrors;
795 > } finally { userDataSyncService.ts
796 > this.updateStatus();
797 > }
798 > }
800 > async apply(executionId: string, token: CancellationToken): Promise<void> {
801 const syncHeaders = createSyncHeaders(executionId);
802 for (const synchroniser of this.enabled) {
819 }
820 }
822 > async stop(): Promise<void> {
823 for (const synchroniser of this.enabled) {
824 try {
831 }
832 }
834 > async resetLocal(): Promise<void> {
835 > for (const synchroniser of this.enabled) { userDataSyncService.ts
836 > try {
837 > await synchroniser.resetLocal();
838 > } catch (e) {
839 this.logService.error(`${synchroniser.resource}: ${toErrorMessage(e)}`);
840 this.logService.error(e);
841 }
843 > }
845 > private async getUserDataSyncConfiguration(manifestOrLatestData: IUserDataManifest | IUserDataSyncLatestData | null): Promise<IUserDataSyncConfiguration> {
846 if (!this.profile.isDefault) {
847 return {};
855 return local;
856 }
858 > private getLocalUserDataSyncConfiguration(): IUserDataSyncConfiguration {
859 > return this.configurationService.getValue(USER_DATA_SYNC_CONFIGURATION_SCOPE); userDataSyncService.ts
860 > }
862 > private setStatus(status: SyncStatus): void {
863 > if (this._status !== status) { userDataSyncService.ts
864 > this._status = status;
865 > this._onDidChangeStatus.fire(status);
866 > }
867 > }
869 > private updateStatus(): void {
870 > this.updateConflicts(); userDataSyncService.ts
871 > if (this.enabled.some(s => s.status === SyncStatus.HasConflicts)) {
872 return this.setStatus(SyncStatus.HasConflicts);
873 }
874 > if (this.enabled.some(s => s.status === SyncStatus.Syncing)) { userDataSyncService.ts
875 > return this.setStatus(SyncStatus.Syncing);
876 > }
877 > return this.setStatus(SyncStatus.Idle); userDataSyncService.ts
880 > private updateConflicts(): void {
881 > const conflicts = this.enabled.filter(s => s.status === SyncStatus.HasConflicts) userDataSyncService.ts
882 > .filter(s => s.conflicts.conflicts.length > 0)
883 > .map(s => s.conflicts);
884 > if (!equals(this._conflicts, conflicts, (a, b) => a.syncResource === b.syncResource && equals(a.conflicts, b.conflicts, (a, b) => isEqual(a.previewResource, b.previewResource)))) {
885 this._conflicts = conflicts;
886 this._onDidChangeConflicts.fire(conflicts);
887 }
890 > private getOrder(syncResource: SyncResource): number {
891 > switch (syncResource) { userDataSyncService.ts
892 > case SyncResource.Settings: return 0;
893 > case SyncResource.Keybindings: return 1;
894 > case SyncResource.Snippets: return 2;
895 > case SyncResource.Tasks: return 3;
896 > case SyncResource.Mcp: return 4;
897 > case SyncResource.GlobalState: return 5;
898 > case SyncResource.Extensions: return 6;
899 > case SyncResource.Prompts: return 7;
900 > case SyncResource.Profiles: return 8;
901 > case SyncResource.WorkspaceState: return 9;
902 > }
903 > }
905 >
906 function canBailout(e: unknown): boolean {
907 if (e instanceof UserDataSyncError) {
922 return false;
923 }
925 function reportUserDataSyncError(userDataSyncError: UserDataSyncError, executionId: string, userDataSyncStoreManagementService: IUserDataSyncStoreManagementService, telemetryService: ITelemetryService): void {
926 telemetryService.publicLog2<SyncErrorEvent, SyncErrorClassification>('sync/error',
934 });
935 }
937 > function getRefOrUserData(manifestOrLatestData: IUserDataManifest | IUserDataSyncLatestData | null, collection: string | undefined, resource: SyncResource): string | IUserData | undefined { userDataSyncService.ts
938 > if (isUserDataManifest(manifestOrLatestData)) {
939 if (collection) {
940 return manifestOrLatestData?.collections?.[collection]?.latest?.[resource];
src/vs/base/common/charCode.ts 450 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- charCode.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/
7 >
8 > /**
9 > * An inlined enum containing useful character codes (to be used with String.charCodeAt).
10 > * Please leave the const keyword such that it gets inlined when compiled to JavaScript!
11 > */
12 > export const enum CharCode {
13 > Null = 0,
14 > /**
15 > * The `\b` character.
16 > */
17 > Backspace = 8,
18 > /**
19 > * The `\t` character.
20 > */
21 > Tab = 9,
22 > /**
23 > * The `\n` character.
24 > */
25 > LineFeed = 10,
26 > /**
27 > * The `\r` character.
28 > */
29 > CarriageReturn = 13,
30 > Space = 32,
31 > /**
32 > * The `!` character.
33 > */
34 > ExclamationMark = 33,
35 > /**
36 > * The `"` character.
37 > */
38 > DoubleQuote = 34,
39 > /**
40 > * The `#` character.
41 > */
42 > Hash = 35,
43 > /**
44 > * The `$` character.
45 > */
46 > DollarSign = 36,
47 > /**
48 > * The `%` character.
49 > */
50 > PercentSign = 37,
51 > /**
52 > * The `&` character.
53 > */
54 > Ampersand = 38,
55 > /**
56 > * The `'` character.
57 > */
58 > SingleQuote = 39,
59 > /**
60 > * The `(` character.
61 > */
62 > OpenParen = 40,
63 > /**
64 > * The `)` character.
65 > */
66 > CloseParen = 41,
67 > /**
68 > * The `*` character.
69 > */
70 > Asterisk = 42,
71 > /**
72 > * The `+` character.
73 > */
74 > Plus = 43,
75 > /**
76 > * The `,` character.
77 > */
78 > Comma = 44,
79 > /**
80 > * The `-` character.
81 > */
82 > Dash = 45,
83 > /**
84 > * The `.` character.
85 > */
86 > Period = 46,
87 > /**
88 > * The `/` character.
89 > */
90 > Slash = 47,
91 >
92 > Digit0 = 48,
93 > Digit1 = 49,
94 > Digit2 = 50,
95 > Digit3 = 51,
96 > Digit4 = 52,
97 > Digit5 = 53,
98 > Digit6 = 54,
99 > Digit7 = 55,
100 > Digit8 = 56,
101 > Digit9 = 57,
102 >
103 > /**
104 > * The `:` character.
105 > */
106 > Colon = 58,
107 > /**
108 > * The `;` character.
109 > */
110 > Semicolon = 59,
111 > /**
112 > * The `<` character.
113 > */
114 > LessThan = 60,
115 > /**
116 > * The `=` character.
117 > */
118 > Equals = 61,
119 > /**
120 > * The `>` character.
121 > */
122 > GreaterThan = 62,
123 > /**
124 > * The `?` character.
125 > */
126 > QuestionMark = 63,
127 > /**
128 > * The `@` character.
129 > */
130 > AtSign = 64,
131 >
132 > A = 65,
133 > B = 66,
134 > C = 67,
135 > D = 68,
136 > E = 69,
137 > F = 70,
138 > G = 71,
139 > H = 72,
140 > I = 73,
141 > J = 74,
142 > K = 75,
143 > L = 76,
144 > M = 77,
145 > N = 78,
146 > O = 79,
147 > P = 80,
148 > Q = 81,
149 > R = 82,
150 > S = 83,
151 > T = 84,
152 > U = 85,
153 > V = 86,
154 > W = 87,
155 > X = 88,
156 > Y = 89,
157 > Z = 90,
158 >
159 > /**
160 > * The `[` character.
161 > */
162 > OpenSquareBracket = 91,
163 > /**
164 > * The `\` character.
165 > */
166 > Backslash = 92,
167 > /**
168 > * The `]` character.
169 > */
170 > CloseSquareBracket = 93,
171 > /**
172 > * The `^` character.
173 > */
174 > Caret = 94,
175 > /**
176 > * The `_` character.
177 > */
178 > Underline = 95,
179 > /**
180 > * The ``(`)`` character.
181 > */
182 > BackTick = 96,
183 >
184 > a = 97,
185 > b = 98,
186 > c = 99,
187 > d = 100,
188 > e = 101,
189 > f = 102,
190 > g = 103,
191 > h = 104,
192 > i = 105,
193 > j = 106,
194 > k = 107,
195 > l = 108,
196 > m = 109,
197 > n = 110,
198 > o = 111,
199 > p = 112,
200 > q = 113,
201 > r = 114,
202 > s = 115,
203 > t = 116,
204 > u = 117,
205 > v = 118,
206 > w = 119,
207 > x = 120,
208 > y = 121,
209 > z = 122,
210 >
211 > /**
212 > * The `{` character.
213 > */
214 > OpenCurlyBrace = 123,
215 > /**
216 > * The `|` character.
217 > */
218 > Pipe = 124,
219 > /**
220 > * The `}` character.
221 > */
222 > CloseCurlyBrace = 125,
223 > /**
224 > * The `~` character.
225 > */
226 > Tilde = 126,
227 >
228 > /**
229 > * The &nbsp; (no-break space) character.
230 > * Unicode Character 'NO-BREAK SPACE' (U+00A0)
231 > */
232 > NoBreakSpace = 160,
233 >
234 > U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent
235 > U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent
236 > U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent
237 > U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde
238 > U_Combining_Macron = 0x0304, // U+0304 Combining Macron
239 > U_Combining_Overline = 0x0305, // U+0305 Combining Overline
240 > U_Combining_Breve = 0x0306, // U+0306 Combining Breve
241 > U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above
242 > U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis
243 > U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above
244 > U_Combining_Ring_Above = 0x030A, // U+030A Combining Ring Above
245 > U_Combining_Double_Acute_Accent = 0x030B, // U+030B Combining Double Acute Accent
246 > U_Combining_Caron = 0x030C, // U+030C Combining Caron
247 > U_Combining_Vertical_Line_Above = 0x030D, // U+030D Combining Vertical Line Above
248 > U_Combining_Double_Vertical_Line_Above = 0x030E, // U+030E Combining Double Vertical Line Above
249 > U_Combining_Double_Grave_Accent = 0x030F, // U+030F Combining Double Grave Accent
250 > U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu
251 > U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve
252 > U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above
253 > U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above
254 > U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above
255 > U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right
256 > U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below
257 > U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below
258 > U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below
259 > U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below
260 > U_Combining_Left_Angle_Above = 0x031A, // U+031A Combining Left Angle Above
261 > U_Combining_Horn = 0x031B, // U+031B Combining Horn
262 > U_Combining_Left_Half_Ring_Below = 0x031C, // U+031C Combining Left Half Ring Below
263 > U_Combining_Up_Tack_Below = 0x031D, // U+031D Combining Up Tack Below
264 > U_Combining_Down_Tack_Below = 0x031E, // U+031E Combining Down Tack Below
265 > U_Combining_Plus_Sign_Below = 0x031F, // U+031F Combining Plus Sign Below
266 > U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below
267 > U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below
268 > U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below
269 > U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below
270 > U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below
271 > U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below
272 > U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below
273 > U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla
274 > U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek
275 > U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below
276 > U_Combining_Bridge_Below = 0x032A, // U+032A Combining Bridge Below
277 > U_Combining_Inverted_Double_Arch_Below = 0x032B, // U+032B Combining Inverted Double Arch Below
278 > U_Combining_Caron_Below = 0x032C, // U+032C Combining Caron Below
279 > U_Combining_Circumflex_Accent_Below = 0x032D, // U+032D Combining Circumflex Accent Below
280 > U_Combining_Breve_Below = 0x032E, // U+032E Combining Breve Below
281 > U_Combining_Inverted_Breve_Below = 0x032F, // U+032F Combining Inverted Breve Below
282 > U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below
283 > U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below
284 > U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line
285 > U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line
286 > U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay
287 > U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay
288 > U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay
289 > U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay
290 > U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay
291 > U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below
292 > U_Combining_Inverted_Bridge_Below = 0x033A, // U+033A Combining Inverted Bridge Below
293 > U_Combining_Square_Below = 0x033B, // U+033B Combining Square Below
294 > U_Combining_Seagull_Below = 0x033C, // U+033C Combining Seagull Below
295 > U_Combining_X_Above = 0x033D, // U+033D Combining X Above
296 > U_Combining_Vertical_Tilde = 0x033E, // U+033E Combining Vertical Tilde
297 > U_Combining_Double_Overline = 0x033F, // U+033F Combining Double Overline
298 > U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark
299 > U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark
300 > U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni
301 > U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis
302 > U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos
303 > U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni
304 > U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above
305 > U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below
306 > U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below
307 > U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below
308 > U_Combining_Not_Tilde_Above = 0x034A, // U+034A Combining Not Tilde Above
309 > U_Combining_Homothetic_Above = 0x034B, // U+034B Combining Homothetic Above
310 > U_Combining_Almost_Equal_To_Above = 0x034C, // U+034C Combining Almost Equal To Above
311 > U_Combining_Left_Right_Arrow_Below = 0x034D, // U+034D Combining Left Right Arrow Below
312 > U_Combining_Upwards_Arrow_Below = 0x034E, // U+034E Combining Upwards Arrow Below
313 > U_Combining_Grapheme_Joiner = 0x034F, // U+034F Combining Grapheme Joiner
314 > U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above
315 > U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above
316 > U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata
317 > U_Combining_X_Below = 0x0353, // U+0353 Combining X Below
318 > U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below
319 > U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below
320 > U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below
321 > U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above
322 > U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right
323 > U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below
324 > U_Combining_Double_Ring_Below = 0x035A, // U+035A Combining Double Ring Below
325 > U_Combining_Zigzag_Above = 0x035B, // U+035B Combining Zigzag Above
326 > U_Combining_Double_Breve_Below = 0x035C, // U+035C Combining Double Breve Below
327 > U_Combining_Double_Breve = 0x035D, // U+035D Combining Double Breve
328 > U_Combining_Double_Macron = 0x035E, // U+035E Combining Double Macron
329 > U_Combining_Double_Macron_Below = 0x035F, // U+035F Combining Double Macron Below
330 > U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde
331 > U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve
332 > U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below
333 > U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A
334 > U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E
335 > U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I
336 > U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O
337 > U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U
338 > U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C
339 > U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D
340 > U_Combining_Latin_Small_Letter_H = 0x036A, // U+036A Combining Latin Small Letter H
341 > U_Combining_Latin_Small_Letter_M = 0x036B, // U+036B Combining Latin Small Letter M
342 > U_Combining_Latin_Small_Letter_R = 0x036C, // U+036C Combining Latin Small Letter R
343 > U_Combining_Latin_Small_Letter_T = 0x036D, // U+036D Combining Latin Small Letter T
344 > U_Combining_Latin_Small_Letter_V = 0x036E, // U+036E Combining Latin Small Letter V
345 > U_Combining_Latin_Small_Letter_X = 0x036F, // U+036F Combining Latin Small Letter X
346 >
347 > /**
348 > * Unicode Character 'LINE SEPARATOR' (U+2028)
349 > * http://www.fileformat.info/info/unicode/char/2028/index.htm
350 > */
351 > LINE_SEPARATOR = 0x2028,
352 > /**
353 > * Unicode Character 'PARAGRAPH SEPARATOR' (U+2029)
354 > * http://www.fileformat.info/info/unicode/char/2029/index.htm
355 > */
356 > PARAGRAPH_SEPARATOR = 0x2029,
357 > /**
358 > * Unicode Character 'NEXT LINE' (U+0085)
359 > * http://www.fileformat.info/info/unicode/char/0085/index.htm
360 > */
361 > NEXT_LINE = 0x0085,
362 >
363 > // http://www.fileformat.info/info/unicode/category/Sk/list.htm
364 > U_CIRCUMFLEX = 0x005E, // U+005E CIRCUMFLEX
365 > U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT
366 > U_DIAERESIS = 0x00A8, // U+00A8 DIAERESIS
367 > U_MACRON = 0x00AF, // U+00AF MACRON
368 > U_ACUTE_ACCENT = 0x00B4, // U+00B4 ACUTE ACCENT
369 > U_CEDILLA = 0x00B8, // U+00B8 CEDILLA
370 > U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD
371 > U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD
372 > U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4, // U+02C4 MODIFIER LETTER UP ARROWHEAD
373 > U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD
374 > U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING
375 > U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING
376 > U_MODIFIER_LETTER_UP_TACK = 0x02D4, // U+02D4 MODIFIER LETTER UP TACK
377 > U_MODIFIER_LETTER_DOWN_TACK = 0x02D5, // U+02D5 MODIFIER LETTER DOWN TACK
378 > U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6, // U+02D6 MODIFIER LETTER PLUS SIGN
379 > U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7, // U+02D7 MODIFIER LETTER MINUS SIGN
380 > U_BREVE = 0x02D8, // U+02D8 BREVE
381 > U_DOT_ABOVE = 0x02D9, // U+02D9 DOT ABOVE
382 > U_RING_ABOVE = 0x02DA, // U+02DA RING ABOVE
383 > U_OGONEK = 0x02DB, // U+02DB OGONEK
384 > U_SMALL_TILDE = 0x02DC, // U+02DC SMALL TILDE
385 > U_DOUBLE_ACUTE_ACCENT = 0x02DD, // U+02DD DOUBLE ACUTE ACCENT
386 > U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE, // U+02DE MODIFIER LETTER RHOTIC HOOK
387 > U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF, // U+02DF MODIFIER LETTER CROSS ACCENT
388 > U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR
389 > U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6, // U+02E6 MODIFIER LETTER HIGH TONE BAR
390 > U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7, // U+02E7 MODIFIER LETTER MID TONE BAR
391 > U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8, // U+02E8 MODIFIER LETTER LOW TONE BAR
392 > U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR
393 > U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK
394 > U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK
395 > U_MODIFIER_LETTER_UNASPIRATED = 0x02ED, // U+02ED MODIFIER LETTER UNASPIRATED
396 > U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD
397 > U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD
398 > U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD
399 > U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD
400 > U_MODIFIER_LETTER_LOW_RING = 0x02F3, // U+02F3 MODIFIER LETTER LOW RING
401 > U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT
402 > U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT
403 > U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT
404 > U_MODIFIER_LETTER_LOW_TILDE = 0x02F7, // U+02F7 MODIFIER LETTER LOW TILDE
405 > U_MODIFIER_LETTER_RAISED_COLON = 0x02F8, // U+02F8 MODIFIER LETTER RAISED COLON
406 > U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE
407 > U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA, // U+02FA MODIFIER LETTER END HIGH TONE
408 > U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB, // U+02FB MODIFIER LETTER BEGIN LOW TONE
409 > U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC, // U+02FC MODIFIER LETTER END LOW TONE
410 > U_MODIFIER_LETTER_SHELF = 0x02FD, // U+02FD MODIFIER LETTER SHELF
411 > U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE, // U+02FE MODIFIER LETTER OPEN SHELF
412 > U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF, // U+02FF MODIFIER LETTER LOW LEFT ARROW
413 > U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN
414 > U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS
415 > U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS
416 > U_GREEK_KORONIS = 0x1FBD, // U+1FBD GREEK KORONIS
417 > U_GREEK_PSILI = 0x1FBF, // U+1FBF GREEK PSILI
418 > U_GREEK_PERISPOMENI = 0x1FC0, // U+1FC0 GREEK PERISPOMENI
419 > U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI
420 > U_GREEK_PSILI_AND_VARIA = 0x1FCD, // U+1FCD GREEK PSILI AND VARIA
421 > U_GREEK_PSILI_AND_OXIA = 0x1FCE, // U+1FCE GREEK PSILI AND OXIA
422 > U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF, // U+1FCF GREEK PSILI AND PERISPOMENI
423 > U_GREEK_DASIA_AND_VARIA = 0x1FDD, // U+1FDD GREEK DASIA AND VARIA
424 > U_GREEK_DASIA_AND_OXIA = 0x1FDE, // U+1FDE GREEK DASIA AND OXIA
425 > U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF, // U+1FDF GREEK DASIA AND PERISPOMENI
426 > U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED, // U+1FED GREEK DIALYTIKA AND VARIA
427 > U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE, // U+1FEE GREEK DIALYTIKA AND OXIA
428 > U_GREEK_VARIA = 0x1FEF, // U+1FEF GREEK VARIA
429 > U_GREEK_OXIA = 0x1FFD, // U+1FFD GREEK OXIA
430 > U_GREEK_DASIA = 0x1FFE, // U+1FFE GREEK DASIA
431 >
432 > U_IDEOGRAPHIC_FULL_STOP = 0x3002, // U+3002 IDEOGRAPHIC FULL STOP
433 > U_LEFT_CORNER_BRACKET = 0x300C, // U+300C LEFT CORNER BRACKET
434 > U_RIGHT_CORNER_BRACKET = 0x300D, // U+300D RIGHT CORNER BRACKET
435 > U_LEFT_BLACK_LENTICULAR_BRACKET = 0x3010, // U+3010 LEFT BLACK LENTICULAR BRACKET
436 > U_RIGHT_BLACK_LENTICULAR_BRACKET = 0x3011, // U+3011 RIGHT BLACK LENTICULAR BRACKET
437 >
438 >
439 > U_OVERLINE = 0x203E, // Unicode Character 'OVERLINE'
440 >
441 > /**
442 > * UTF-8 BOM
443 > * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
444 > * http://www.fileformat.info/info/unicode/char/feff/index.htm
445 > */
446 > UTF8_BOM = 65279,
447 >
448 > U_FULLWIDTH_SEMICOLON = 0xFF1B, // U+FF1B FULLWIDTH SEMICOLON
449 > U_FULLWIDTH_COMMA = 0xFF0C, // U+FF0C FULLWIDTH COMMA
450 > }
src/vs/platform/log/common/log.ts 447 covered LOC · 73 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- log.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as nls from '../../../nls.js';
7 > import { toErrorMessage } from '../../../base/common/errorMessage.js';
8 > import { Emitter, Event } from '../../../base/common/event.js';
9 > import { hash } from '../../../base/common/hash.js';
10 > import { Disposable, IDisposable, toDisposable } from '../../../base/common/lifecycle.js';
11 > import { ResourceMap } from '../../../base/common/map.js';
12 > import { isWindows } from '../../../base/common/platform.js';
13 > import { joinPath } from '../../../base/common/resources.js';
14 > import { Mutable, isNumber, isString } from '../../../base/common/types.js';
15 > import { URI } from '../../../base/common/uri.js';
16 > import { ILocalizedString } from '../../action/common/action.js';
17 > import { RawContextKey } from '../../contextkey/common/contextkey.js';
18 > import { IEnvironmentService } from '../../environment/common/environment.js';
19 > import { createDecorator } from '../../instantiation/common/instantiation.js';
20 >
21 > export const ILogService = createDecorator<ILogService>('logService');
22 > export const ILoggerService = createDecorator<ILoggerService>('loggerService');
23 >
24 function now(): string {
25 return new Date().toISOString();
26 }
27 > log.ts
28 > export function isLogLevel(thing: unknown): thing is LogLevel {
29 return isNumber(thing);
30 }
31 > log.ts
32 > export enum LogLevel {
33 > Off,
34 > Trace,
35 > Debug,
36 > Info,
37 > Warning,
38 > Error
39 > }
40 >
41 > export const DEFAULT_LOG_LEVEL: LogLevel = LogLevel.Info;
42 >
43 > export interface ILogger extends IDisposable {
44 > readonly onDidChangeLogLevel: Event<LogLevel>;
45 > getLevel(): LogLevel;
46 > setLevel(level: LogLevel): void;
47 >
48 > trace(message: string, ...args: unknown[]): void;
49 > debug(message: string, ...args: unknown[]): void;
50 > info(message: string, ...args: unknown[]): void;
51 > warn(message: string, ...args: unknown[]): void;
52 > error(message: string | Error, ...args: unknown[]): void;
53 >
54 > /**
55 > * An operation to flush the contents. Can be synchronous.
56 > */
57 > flush(): void;
58 > }
59 >
60 > export function canLog(loggerLevel: LogLevel, messageLevel: LogLevel): boolean {
61 return loggerLevel !== LogLevel.Off && loggerLevel <= messageLevel;
62 }
63 > log.ts
64 > export function log(logger: ILogger, level: LogLevel, message: string): void {
65 switch (level) {
66 case LogLevel.Trace: logger.trace(message); break;
73 }
74 }
75 > log.ts
76 > type ConsoleMethod = 'debug' | 'error' | 'info' | 'log' | 'warn';
77 > type ConsoleMethodFn = (...args: unknown[]) => void;
78 >
79 > /**
80 > * Flag to enable forwarding of console.* calls to the log service in development.
81 > * This is intended for the use of agents to quickly instrument the code with console.logs
82 > * which will end up in the log service's file outputs.
83 > */
84 > export const isDevConsoleLogForwardingEnabled = false
85 > // || Boolean("true") // done "weirdly" so that a lint warning prevents you from pushing this
86 > ;
87 >
88 > let isConsoleForwarding = false;
89 > let isLogServiceConsoleEcho = false;
90 >
91 function getConsoleMethod(method: ConsoleMethod): ConsoleMethodFn {
92 switch (method) {
98 }
99 }
100 > log.ts
101 function setConsoleMethod(method: ConsoleMethod, fn: ConsoleMethodFn): void {
102 switch (method) {
108 }
109 }
110 > log.ts
111 function logToConsole(method: ConsoleMethod, ...args: unknown[]): void {
112 if (isConsoleForwarding) {
120 }
121 }
122 > log.ts
123 > export function registerDevConsoleLogForwarder(logService: ILogService): IDisposable {
124 const originalConsoleMethods: Record<ConsoleMethod, ConsoleMethodFn> = {
125 debug: console.debug,
177 });
178 }
179 > log.ts
180 > export function format(args: any, verbose: boolean = false): string {
181 let result = '';
182
199 return result;
200 }
201 > log.ts
202 > export type LoggerGroup = {
203 > readonly id: string;
204 > readonly name: string;
205 > };
206 >
207 > export interface ILogService extends ILogger {
208 > readonly _serviceBrand: undefined;
209 > }
210 >
211 > export interface ILoggerOptions {
212 >
213 > /**
214 > * Id of the logger.
215 > */
216 > id?: string;
217 >
218 > /**
219 > * Name of the logger.
220 > */
221 > name?: string;
222 >
223 > /**
224 > * Do not create rotating files if max size exceeds.
225 > */
226 > donotRotate?: boolean;
227 >
228 > /**
229 > * Do not use formatters.
230 > */
231 > donotUseFormatters?: boolean;
232 >
233 > /**
234 > * When to log. Set to `always` to log always.
235 > */
236 > logLevel?: 'always' | LogLevel;
237 >
238 > /**
239 > * Whether the log should be hidden from the user.
240 > */
241 > hidden?: boolean;
242 >
243 > /**
244 > * Condition which must be true to show this logger
245 > */
246 > when?: string;
247 >
248 > /**
249 > * Id of the extension that created this logger.
250 > */
251 > extensionId?: string;
252 >
253 > /**
254 > * Group of the logger.
255 > */
256 > group?: LoggerGroup;
257 > }
258 >
259 > export interface ILoggerResource {
260 > readonly resource: URI;
261 > readonly id: string;
262 > readonly name?: string;
263 > readonly logLevel?: LogLevel;
264 > readonly hidden?: boolean;
265 > readonly when?: string;
266 > readonly extensionId?: string;
267 > readonly group?: LoggerGroup;
268 > }
269 >
270 > export type DidChangeLoggersEvent = {
271 > readonly added: Iterable<ILoggerResource>;
272 > readonly removed: Iterable<ILoggerResource>;
273 > };
274 >
275 > export interface ILoggerService {
276 >
277 > readonly _serviceBrand: undefined;
278 >
279 > /**
280 > * Creates a logger for the given resource, or gets one if it already exists.
281 > *
282 > * This will also register the logger with the logger service.
283 > */
284 > createLogger(resource: URI, options?: ILoggerOptions): ILogger;
285 >
286 > /**
287 > * Creates a logger with the given id in the logs folder, or gets one if it already exists.
288 > *
289 > * This will also register the logger with the logger service.
290 > */
291 > createLogger(id: string, options?: Omit<ILoggerOptions, 'id'>): ILogger;
292 >
293 > /**
294 > * Gets an existing logger, if any.
295 > */
296 > getLogger(resourceOrId: URI | string): ILogger | undefined;
297 >
298 > /**
299 > * An event which fires when the log level of a logger has changed
300 > */
301 > readonly onDidChangeLogLevel: Event<LogLevel | [URI, LogLevel]>;
302 >
303 > /**
304 > * Set default log level.
305 > */
306 > setLogLevel(level: LogLevel): void;
307 >
308 > /**
309 > * Set log level for a logger.
310 > */
311 > setLogLevel(resource: URI, level: LogLevel): void;
312 >
313 > /**
314 > * Get log level for a logger or the default log level.
315 > */
316 > getLogLevel(resource?: URI): LogLevel;
317 >
318 > /**
319 > * An event which fires when the visibility of a logger has changed
320 > */
321 > readonly onDidChangeVisibility: Event<[URI, boolean]>;
322 >
323 > /**
324 > * Set the visibility of a logger.
325 > */
326 > setVisibility(resourceOrId: URI | string, visible: boolean): void;
327 >
328 > /**
329 > * An event which fires when the logger resources are changed
330 > */
331 > readonly onDidChangeLoggers: Event<DidChangeLoggersEvent>;
332 >
333 > /**
334 > * Register a logger with the logger service.
335 > *
336 > * Note that this will not create a logger, but only register it.
337 > *
338 > * Use `createLogger` to create a logger and register it.
339 > *
340 > * Use it when you want to register a logger that is not created by the logger service.
341 > */
342 > registerLogger(resource: ILoggerResource): void;
343 >
344 > /**
345 > * Deregister the logger for the given resource.
346 > */
347 > deregisterLogger(idOrResource: URI | string): void;
348 >
349 > /**
350 > * Get all registered loggers
351 > */
352 > getRegisteredLoggers(): Iterable<ILoggerResource>;
353 >
354 > /**
355 > * Get the registered logger for the given resource.
356 > */
357 > getRegisteredLogger(resource: URI): ILoggerResource | undefined;
358 > }
359 >
360 > export abstract class AbstractLogger extends Disposable implements ILogger {
361
362 private level: LogLevel = DEFAULT_LOG_LEVEL;
363 private readonly _onDidChangeLogLevel: Emitter<LogLevel> = this._register(new Emitter<LogLevel>());
364 > get onDidChangeLogLevel(): Event<LogLevel> { return this._onDidChangeLogLevel.event; } log.ts
365 >
366 > setLevel(level: LogLevel): void {
367 if (this.level !== level) {
368 this.level = level;
370 }
371 }
372 > log.ts
373 > getLevel(): LogLevel {
374 return this.level;
375 }
376 > log.ts
377 > protected checkLogLevel(level: LogLevel): boolean {
378 return canLog(this.level, level);
379 }
380 > log.ts
381 > protected canLog(level: LogLevel): boolean {
382 if (this._store.isDisposed) {
383 return false;
385 return this.checkLogLevel(level);
386 }
387 > log.ts
388 > abstract trace(message: string, ...args: unknown[]): void;
389 > abstract debug(message: string, ...args: unknown[]): void;
390 > abstract info(message: string, ...args: unknown[]): void;
391 > abstract warn(message: string, ...args: unknown[]): void;
392 > abstract error(message: string | Error, ...args: unknown[]): void;
393 > abstract flush(): void;
394 > }
395 >
396 > export abstract class AbstractMessageLogger extends AbstractLogger implements ILogger {
397 >
398 > constructor(private readonly logAlways?: boolean) {
399 super();
400 }
401 > log.ts
402 > protected override checkLogLevel(level: LogLevel): boolean {
403 return this.logAlways || super.checkLogLevel(level);
404 }
405 > log.ts
406 > trace(message: string, ...args: unknown[]): void {
407 if (this.canLog(LogLevel.Trace)) {
408 this.log(LogLevel.Trace, format([message, ...args], true));
409 }
410 }
411 > log.ts
412 > debug(message: string, ...args: unknown[]): void {
413 if (this.canLog(LogLevel.Debug)) {
414 this.log(LogLevel.Debug, format([message, ...args]));
415 }
416 }
417 > log.ts
418 > info(message: string, ...args: unknown[]): void {
419 if (this.canLog(LogLevel.Info)) {
420 this.log(LogLevel.Info, format([message, ...args]));
421 }
422 }
423 > log.ts
424 > warn(message: string, ...args: unknown[]): void {
425 if (this.canLog(LogLevel.Warning)) {
426 this.log(LogLevel.Warning, format([message, ...args]));
427 }
428 }
429 > log.ts
430 > error(message: string | Error, ...args: unknown[]): void {
431 if (this.canLog(LogLevel.Error)) {
432 if (message instanceof Error) {
439 }
440 }
441 > log.ts
442 > flush(): void { }
443 >
444 > protected abstract log(level: LogLevel, message: string): void;
445 > }
446 >
447 >
448 > export class ConsoleMainLogger extends AbstractLogger implements ILogger {
449 >
450 > private useColors: boolean;
451 >
452 > constructor(logLevel: LogLevel = DEFAULT_LOG_LEVEL) {
453 super();
454 this.setLevel(logLevel);
455 this.useColors = !isWindows;
456 }
457 > log.ts
458 > trace(message: string, ...args: unknown[]): void {
459 if (this.canLog(LogLevel.Trace)) {
460 if (this.useColors) {
465 }
466 }
467 > log.ts
468 > debug(message: string, ...args: unknown[]): void {
469 if (this.canLog(LogLevel.Debug)) {
470 if (this.useColors) {
475 }
476 }
477 > log.ts
478 > info(message: string, ...args: unknown[]): void {
479 if (this.canLog(LogLevel.Info)) {
480 if (this.useColors) {
485 }
486 }
487 > log.ts
488 > warn(message: string | Error, ...args: unknown[]): void {
489 if (this.canLog(LogLevel.Warning)) {
490 if (this.useColors) {
495 }
496 }
497 > log.ts
498 > error(message: string, ...args: unknown[]): void {
499 if (this.canLog(LogLevel.Error)) {
500 if (this.useColors) {
505 }
506 }
507 > log.ts
508 > flush(): void {
509 // noop
510 }
511 > log.ts
512 > }
513 >
514 > export class ConsoleLogger extends AbstractLogger implements ILogger {
515 >
516 > constructor(logLevel: LogLevel = DEFAULT_LOG_LEVEL, private readonly useColors: boolean = true) {
517 super();
518 this.setLevel(logLevel);
519 }
520 > log.ts
521 > trace(message: string, ...args: unknown[]): void {
522 if (this.canLog(LogLevel.Trace)) {
523 if (this.useColors) {
528 }
529 }
530 > log.ts
531 > debug(message: string, ...args: unknown[]): void {
532 if (this.canLog(LogLevel.Debug)) {
533 if (this.useColors) {
538 }
539 }
540 > log.ts
541 > info(message: string, ...args: unknown[]): void {
542 if (this.canLog(LogLevel.Info)) {
543 if (this.useColors) {
548 }
549 }
550 > log.ts
551 > warn(message: string | Error, ...args: unknown[]): void {
552 if (this.canLog(LogLevel.Warning)) {
553 if (this.useColors) {
558 }
559 }
560 > log.ts
561 > error(message: string, ...args: unknown[]): void {
562 if (this.canLog(LogLevel.Error)) {
563 if (this.useColors) {
568 }
569 }
570 > log.ts
571 >
572 > flush(): void {
573 // noop
574 }
575 > } log.ts
576 >
577 > export class AdapterLogger extends AbstractLogger implements ILogger {
578 >
579 > constructor(private readonly adapter: { log: (logLevel: LogLevel, args: any[]) => void }, logLevel: LogLevel = DEFAULT_LOG_LEVEL) {
580 super();
581 this.setLevel(logLevel);
582 }
583 > log.ts
584 > trace(message: string, ...args: unknown[]): void {
585 if (this.canLog(LogLevel.Trace)) {
586 this.adapter.log(LogLevel.Trace, [this.extractMessage(message), ...args]);
587 }
588 }
589 > log.ts
590 > debug(message: string, ...args: unknown[]): void {
591 if (this.canLog(LogLevel.Debug)) {
592 this.adapter.log(LogLevel.Debug, [this.extractMessage(message), ...args]);
593 }
594 }
595 > log.ts
596 > info(message: string, ...args: unknown[]): void {
597 if (this.canLog(LogLevel.Info)) {
598 this.adapter.log(LogLevel.Info, [this.extractMessage(message), ...args]);
599 }
600 }
601 > log.ts
602 > warn(message: string | Error, ...args: unknown[]): void {
603 if (this.canLog(LogLevel.Warning)) {
604 this.adapter.log(LogLevel.Warning, [this.extractMessage(message), ...args]);
605 }
606 }
607 > log.ts
608 > error(message: string | Error, ...args: unknown[]): void {
609 if (this.canLog(LogLevel.Error)) {
610 this.adapter.log(LogLevel.Error, [this.extractMessage(message), ...args]);
611 }
612 }
613 > log.ts
614 > private extractMessage(msg: string | Error): string {
615 if (typeof msg === 'string') {
616 return msg;
619 return toErrorMessage(msg, this.canLog(LogLevel.Trace));
620 }
621 > log.ts
622 > flush(): void {
623 // noop
624 }
625 > } log.ts
626 >
627 > export class MultiplexLogger extends AbstractLogger implements ILogger {
628 >
629 > constructor(private readonly loggers: ReadonlyArray<ILogger>) {
630 super();
631 if (loggers.length) {
633 }
634 }
635 > log.ts
636 > override setLevel(level: LogLevel): void {
637 for (const logger of this.loggers) {
638 logger.setLevel(level);
640 super.setLevel(level);
641 }
642 > log.ts
643 > trace(message: string, ...args: unknown[]): void {
644 for (const logger of this.loggers) {
645 logger.trace(message, ...args);
646 }
647 }
648 > log.ts
649 > debug(message: string, ...args: unknown[]): void {
650 for (const logger of this.loggers) {
651 logger.debug(message, ...args);
652 }
653 }
654 > log.ts
655 > info(message: string, ...args: unknown[]): void {
656 for (const logger of this.loggers) {
657 logger.info(message, ...args);
658 }
659 }
660 > log.ts
661 > warn(message: string, ...args: unknown[]): void {
662 for (const logger of this.loggers) {
663 logger.warn(message, ...args);
664 }
665 }
666 > log.ts
667 > error(message: string | Error, ...args: unknown[]): void {
668 for (const logger of this.loggers) {
669 logger.error(message, ...args);
670 }
671 }
672 > log.ts
673 > flush(): void {
674 for (const logger of this.loggers) {
675 logger.flush();
676 }
677 }
678 > log.ts
679 > override dispose(): void {
680 for (const logger of this.loggers) {
681 logger.dispose();
683 super.dispose();
684 }
685 > } log.ts
686 >
687 > type LoggerEntry = { logger: ILogger | undefined; info: Mutable<ILoggerResource> };
688 >
689 > export abstract class AbstractLoggerService extends Disposable implements ILoggerService {
690 >
691 > declare readonly _serviceBrand: undefined;
692 >
693 > private readonly _loggers = new ResourceMap<LoggerEntry>();
694 >
695 > private _onDidChangeLoggers = this._register(new Emitter<{ added: ILoggerResource[]; removed: ILoggerResource[] }>);
696 > readonly onDidChangeLoggers = this._onDidChangeLoggers.event;
697 >
698 > private _onDidChangeLogLevel = this._register(new Emitter<LogLevel | [URI, LogLevel]>);
699 > readonly onDidChangeLogLevel = this._onDidChangeLogLevel.event;
700 >
701 > private _onDidChangeVisibility = this._register(new Emitter<[URI, boolean]>);
702 > readonly onDidChangeVisibility = this._onDidChangeVisibility.event;
703 >
704 > constructor(
705 protected logLevel: LogLevel,
706 private readonly logsHome: URI,
714 }
715 }
716 > log.ts
717 > private getLoggerEntry(resourceOrId: URI | string): LoggerEntry | undefined {
718 if (isString(resourceOrId)) {
719 return [...this._loggers.values()].find(logger => logger.info.id === resourceOrId);
721 return this._loggers.get(resourceOrId);
722 }
723 > log.ts
724 > getLogger(resourceOrId: URI | string): ILogger | undefined {
725 return this.getLoggerEntry(resourceOrId)?.logger;
726 }
727 > log.ts
728 > createLogger(idOrResource: URI | string, options?: ILoggerOptions): ILogger {
729 const resource = this.toResource(idOrResource);
730 const id = isString(idOrResource) ? idOrResource : (options?.id ?? hash(resource.toString()).toString(16));
752 return logger;
753 }
754 > log.ts
755 > protected toResource(idOrResource: string | URI): URI {
756 return isString(idOrResource) ? joinPath(this.logsHome, `${idOrResource.replace(/[\\/:\*\?"<>\|]/g, '')}.log`) : idOrResource;
757 }
758 > log.ts
759 > setLogLevel(logLevel: LogLevel): void;
760 > setLogLevel(resource: URI, logLevel: LogLevel): void;
761 > setLogLevel(arg1: any, arg2?: any): void {
762 if (URI.isUri(arg1)) {
763 const resource = arg1;
780 }
781 }
782 > log.ts
783 > setVisibility(resourceOrId: URI | string, visibility: boolean): void {
784 const logger = this.getLoggerEntry(resourceOrId);
785 if (logger && visibility !== !logger.info.hidden) {
789 }
790 }
791 > log.ts
792 > getLogLevel(resource?: URI): LogLevel {
793 let logLevel;
794 if (resource) {
797 return logLevel ?? this.logLevel;
798 }
799 > log.ts
800 > registerLogger(resource: ILoggerResource): void {
801 const existing = this._loggers.get(resource.resource);
802 if (existing) {
809 }
810 }
811 > log.ts
812 > deregisterLogger(idOrResource: URI | string): void {
813 const resource = this.toResource(idOrResource);
814 const existing = this._loggers.get(resource);
821 }
822 }
823 > log.ts
824 > *getRegisteredLoggers(): Iterable<ILoggerResource> {
825 for (const entry of this._loggers.values()) {
826 yield entry.info;
827 }
828 }
829 > log.ts
830 > getRegisteredLogger(resource: URI): ILoggerResource | undefined {
831 return this._loggers.get(resource)?.info;
832 }
833 > log.ts
834 > override dispose(): void {
835 this._loggers.forEach(logger => logger.logger?.dispose());
836 this._loggers.clear();
837 super.dispose();
838 }
839 > log.ts
840 > protected abstract doCreateLogger(resource: URI, logLevel: LogLevel, options?: ILoggerOptions): ILogger;
841 > }
842 >
843 > export class NullLogger implements ILogger {
844 > readonly onDidChangeLogLevel: Event<LogLevel> = new Emitter<LogLevel>().event; log.ts
845 > setLevel(level: LogLevel): void { } log.ts
846 > getLevel(): LogLevel { return LogLevel.Info; }
847 > trace(message: string, ...args: unknown[]): void { }
848 > debug(message: string, ...args: unknown[]): void { }
849 > info(message: string, ...args: unknown[]): void { }
850 > warn(message: string, ...args: unknown[]): void { }
851 > error(message: string | Error, ...args: unknown[]): void { }
852 > critical(message: string | Error, ...args: unknown[]): void { }
853 > dispose(): void { }
854 > flush(): void { }
855 > }
856 >
857 > export class NullLogService extends NullLogger implements ILogService {
858 > declare readonly _serviceBrand: undefined;
859 > }
860 >
861 > export class NullLoggerService extends AbstractLoggerService {
862 > constructor() {
863 super(LogLevel.Off, URI.parse('log:///log'));
864 }
865 > protected override doCreateLogger(resource: URI, logLevel: LogLevel, options?: ILoggerOptions): ILogger { log.ts
866 return new NullLogger();
867 }
868 > } log.ts
869 >
870 > export function getLogLevel(environmentService: IEnvironmentService): LogLevel {
871 if (environmentService.verbose) {
872 return LogLevel.Trace;
880 return DEFAULT_LOG_LEVEL;
881 }
882 > log.ts
883 > export function LogLevelToString(logLevel: LogLevel): string {
884 > switch (logLevel) {
885 > case LogLevel.Trace: return 'trace';
886 > case LogLevel.Debug: return 'debug';
887 > case LogLevel.Info: return 'info';
888 > case LogLevel.Warning: return 'warn';
889 > case LogLevel.Error: return 'error';
890 > case LogLevel.Off: return 'off';
891 > }
892 > }
893 >
894 > export function LogLevelToLocalizedString(logLevel: LogLevel): ILocalizedString {
895 switch (logLevel) {
896 case LogLevel.Trace: return { original: 'Trace', value: nls.localize('trace', "Trace") };
902 }
903 }
904 > log.ts
905 > export function parseLogLevel(logLevel: string): LogLevel | undefined {
906 switch (logLevel) {
907 case 'trace':
922 return undefined;
923 }
924 > log.ts
925 > // Contexts
926 > export const CONTEXT_LOG_LEVEL = new RawContextKey<string>('logLevel', LogLevelToString(LogLevel.Info));
src/vs/platform/userDataSync/common/userDataSyncStoreService.ts 439 covered LOC · 100 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSyncStoreService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancelablePromise, createCancelablePromise, timeout } from '../../../base/common/async.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { getErrorMessage, isCancellationError } from '../../../base/common/errors.js';
9 > import { Emitter, Event } from '../../../base/common/event.js';
10 > import { Disposable, DisposableStore, toDisposable } from '../../../base/common/lifecycle.js';
11 > import { Mimes } from '../../../base/common/mime.js';
12 > import { isWeb } from '../../../base/common/platform.js';
13 > import { ConfigurationSyncStore } from '../../../base/common/product.js';
14 > import { joinPath, relativePath } from '../../../base/common/resources.js';
15 > import { isObject, isString } from '../../../base/common/types.js';
16 > import { URI } from '../../../base/common/uri.js';
17 > import { generateUuid } from '../../../base/common/uuid.js';
18 > import { IHeaders, IRequestContext, IRequestOptions } from '../../../base/parts/request/common/request.js';
19 > import { IConfigurationService } from '../../configuration/common/configuration.js';
20 > import { IEnvironmentService } from '../../environment/common/environment.js';
21 > import { IFileService } from '../../files/common/files.js';
22 > import { IProductService } from '../../product/common/productService.js';
23 > import { asJson, asText, asTextOrError, hasNoContent, IRequestService, isSuccess, isSuccess as isSuccessContext } from '../../request/common/request.js';
24 > import { getServiceMachineId } from '../../externalServices/common/serviceMachineId.js';
25 > import { IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
26 > import { HEADER_EXECUTION_ID, HEADER_OPERATION_ID, IAuthenticationProvider, IResourceRefHandle, IUserData, IUserDataManifest, IUserDataSyncLatestData, IUserDataSyncLogService, IUserDataSyncStore, IUserDataSyncStoreManagementService, IUserDataSyncStoreService, ServerResource, SYNC_SERVICE_URL_TYPE, UserDataSyncErrorCode, UserDataSyncStoreError, UserDataSyncStoreType } from './userDataSync.js';
27 > import { VSBufferReadableStream } from '../../../base/common/buffer.js';
28 > import { IStringDictionary } from '../../../base/common/collections.js';
29 >
30 > type IDownloadLatestDataType = {
31 > resources?: {
32 > [resourceId: string]: [IUserData];
33 > };
34 > collections?: {
35 > [collectionId: string]: {
36 > resources?: {
37 > [resourceId: string]: [IUserData];
38 > } | undefined;
39 > };
40 > };
41 > };
42 >
43 > const CONFIGURATION_SYNC_STORE_KEY = 'configurationSync.store';
44 > const SYNC_PREVIOUS_STORE = 'sync.previous.store';
45 > const DONOT_MAKE_REQUESTS_UNTIL_KEY = 'sync.donot-make-requests-until';
46 > const USER_SESSION_ID_KEY = 'sync.user-session-id';
47 > const MACHINE_SESSION_ID_KEY = 'sync.machine-session-id';
48 > const REQUEST_SESSION_LIMIT = 100;
49 > const REQUEST_SESSION_INTERVAL = 1000 * 60 * 5; /* 5 minutes */
50 >
51 > type UserDataSyncStore = IUserDataSyncStore & { defaultType: UserDataSyncStoreType };
52 >
53 > export abstract class AbstractUserDataSyncStoreManagementService extends Disposable implements IUserDataSyncStoreManagementService {
54 >
55 > _serviceBrand: undefined;
56 >
57 > private readonly _onDidChangeUserDataSyncStore = this._register(new Emitter<void>());
58 > readonly onDidChangeUserDataSyncStore = this._onDidChangeUserDataSyncStore.event;
59 > private _userDataSyncStore: UserDataSyncStore | undefined;
60 > get userDataSyncStore(): UserDataSyncStore | undefined { return this._userDataSyncStore; }
61 >
62 > protected get userDataSyncStoreType(): UserDataSyncStoreType | undefined {
63 return this.storageService.get(SYNC_SERVICE_URL_TYPE, StorageScope.APPLICATION) as UserDataSyncStoreType;
64 }
65 > protected set userDataSyncStoreType(type: UserDataSyncStoreType | undefined) { userDataSyncStoreService.ts
66 this.storageService.store(SYNC_SERVICE_URL_TYPE, type, StorageScope.APPLICATION, isWeb ? StorageTarget.USER /* sync in web */ : StorageTarget.MACHINE);
67 }
69 > constructor(
70 > @IProductService protected readonly productService: IProductService, userDataSyncStoreService.ts
71 > @IConfigurationService protected readonly configurationService: IConfigurationService,
72 > @IStorageService protected readonly storageService: IStorageService,
73 > ) {
74 > super();
75 > this.updateUserDataSyncStore();
76 > const disposable = this._register(new DisposableStore());
77 > this._register(Event.filter(storageService.onDidChangeValue(StorageScope.APPLICATION, SYNC_SERVICE_URL_TYPE, disposable), () => this.userDataSyncStoreType !== this.userDataSyncStore?.type, disposable)(() => this.updateUserDataSyncStore()));
78 > }
80 > protected updateUserDataSyncStore(): void {
81 > this._userDataSyncStore = this.toUserDataSyncStore(this.productService[CONFIGURATION_SYNC_STORE_KEY]); userDataSyncStoreService.ts
82 > this._onDidChangeUserDataSyncStore.fire();
83 > }
85 > protected toUserDataSyncStore(configurationSyncStore: ConfigurationSyncStore & { web?: ConfigurationSyncStore } | undefined): UserDataSyncStore | undefined {
86 > if (!configurationSyncStore) { userDataSyncStoreService.ts
87 return undefined;
88 }
89 > // Check for web overrides for backward compatibility while reading previous store userDataSyncStoreService.ts
90 > configurationSyncStore = isWeb && configurationSyncStore.web ? { ...configurationSyncStore, ...configurationSyncStore.web } : configurationSyncStore;
91 > if (isString(configurationSyncStore.url)
92 > && isObject(configurationSyncStore.authenticationProviders)
93 > && Object.keys(configurationSyncStore.authenticationProviders).every(authenticationProviderId => Array.isArray(configurationSyncStore.authenticationProviders[authenticationProviderId].scopes))
94 > ) {
95 > const syncStore = configurationSyncStore as ConfigurationSyncStore;
96 > const canSwitch = !!syncStore.canSwitch;
97 > const defaultType: UserDataSyncStoreType = syncStore.url === syncStore.insidersUrl ? 'insiders' : 'stable';
98 > const type: UserDataSyncStoreType = (canSwitch ? this.userDataSyncStoreType : undefined) || defaultType;
99 > const url = type === 'insiders' ? syncStore.insidersUrl
100 : type === 'stable' ? syncStore.stableUrl
101 : syncStore.url;
103 > url: URI.parse(url),
104 > type,
105 > defaultType,
106 > defaultUrl: URI.parse(syncStore.url),
107 > stableUrl: URI.parse(syncStore.stableUrl),
108 > insidersUrl: URI.parse(syncStore.insidersUrl),
109 > canSwitch,
110 > authenticationProviders: Object.keys(syncStore.authenticationProviders).reduce<IAuthenticationProvider[]>((result, id) => {
111 > result.push({ id, scopes: syncStore.authenticationProviders[id].scopes });
112 > return result;
113 > }, [])
114 > };
115 > }
116 return undefined;
119 > abstract switch(type: UserDataSyncStoreType): Promise<void>;
120 > abstract getPreviousUserDataSyncStore(): Promise<IUserDataSyncStore | undefined>;
121 >
122 > }
123 >
124 > export class UserDataSyncStoreManagementService extends AbstractUserDataSyncStoreManagementService implements IUserDataSyncStoreManagementService {
125 >
126 > private readonly previousConfigurationSyncStore: ConfigurationSyncStore | undefined;
127 >
128 > constructor(
129 > @IProductService productService: IProductService, userDataSyncStoreService.ts
130 > @IConfigurationService configurationService: IConfigurationService,
131 > @IStorageService storageService: IStorageService,
132 > ) {
133 > super(productService, configurationService, storageService);
134 >
135 > const previousConfigurationSyncStore = this.storageService.get(SYNC_PREVIOUS_STORE, StorageScope.APPLICATION);
136 > if (previousConfigurationSyncStore) {
137 this.previousConfigurationSyncStore = JSON.parse(previousConfigurationSyncStore);
138 }
140 > const syncStore = this.productService[CONFIGURATION_SYNC_STORE_KEY];
141 > if (syncStore) {
142 > this.storageService.store(SYNC_PREVIOUS_STORE, JSON.stringify(syncStore), StorageScope.APPLICATION, StorageTarget.MACHINE);
143 > } else {
144 this.storageService.remove(SYNC_PREVIOUS_STORE, StorageScope.APPLICATION);
145 }
148 > async switch(type: UserDataSyncStoreType): Promise<void> {
149 if (type !== this.userDataSyncStoreType) {
150 this.userDataSyncStoreType = type;
152 }
153 }
155 > async getPreviousUserDataSyncStore(): Promise<IUserDataSyncStore | undefined> {
156 return this.toUserDataSyncStore(this.previousConfigurationSyncStore);
157 }
159 >
160 > export class UserDataSyncStoreClient extends Disposable {
161 >
162 > private userDataSyncStoreUrl: URI | undefined;
163 >
164 > private authToken: { token: string; type: string } | undefined;
165 > private readonly commonHeadersPromise: Promise<IHeaders>;
166 > private readonly session: RequestsSession;
167 >
168 > private _onTokenFailed = this._register(new Emitter<UserDataSyncErrorCode>());
169 > readonly onTokenFailed = this._onTokenFailed.event;
170 >
171 > private _onTokenSucceed: Emitter<void> = this._register(new Emitter<void>());
172 > readonly onTokenSucceed: Event<void> = this._onTokenSucceed.event;
173 >
174 > private _donotMakeRequestsUntil: Date | undefined = undefined;
175 > get donotMakeRequestsUntil() { return this._donotMakeRequestsUntil; }
176 > private _onDidChangeDonotMakeRequestsUntil = this._register(new Emitter<void>());
177 > readonly onDidChangeDonotMakeRequestsUntil = this._onDidChangeDonotMakeRequestsUntil.event;
178 >
179 > constructor(
180 > userDataSyncStoreUrl: URI | undefined, userDataSyncStoreService.ts
181 > @IProductService productService: IProductService,
182 > @IRequestService private readonly requestService: IRequestService,
183 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
184 > @IEnvironmentService environmentService: IEnvironmentService,
185 > @IFileService fileService: IFileService,
186 > @IStorageService private readonly storageService: IStorageService,
187 > ) {
188 > super();
189 > this.updateUserDataSyncStoreUrl(userDataSyncStoreUrl);
190 > this.commonHeadersPromise = getServiceMachineId(environmentService, fileService, storageService)
191 > .then(uuid => {
192 > const headers: IHeaders = {
193 > 'X-Client-Name': `${productService.applicationName}${isWeb ? '-web' : ''}`,
194 > 'X-Client-Version': productService.version,
195 > };
196 > if (productService.commit) {
197 headers['X-Client-Commit'] = productService.commit;
198 }
199 > return headers; userDataSyncStoreService.ts
200 > });
201 >
202 > /* A requests session that limits requests per sessions */
203 > this.session = new RequestsSession(REQUEST_SESSION_LIMIT, REQUEST_SESSION_INTERVAL, this.requestService, this.logService);
204 > this.initDonotMakeRequestsUntil();
205 > this._register(toDisposable(() => {
206 > if (this.resetDonotMakeRequestsUntilPromise) {
207 this.resetDonotMakeRequestsUntilPromise.cancel();
208 this.resetDonotMakeRequestsUntilPromise = undefined;
209 }
211 > }
213 > setAuthToken(token: string, type: string): void {
214 > this.authToken = { token, type }; userDataSyncStoreService.ts
215 > }
217 > protected updateUserDataSyncStoreUrl(userDataSyncStoreUrl: URI | undefined): void {
218 > this.userDataSyncStoreUrl = userDataSyncStoreUrl ? joinPath(userDataSyncStoreUrl, 'v1') : undefined; userDataSyncStoreService.ts
219 > }
221 > private initDonotMakeRequestsUntil(): void {
222 > const donotMakeRequestsUntil = this.storageService.getNumber(DONOT_MAKE_REQUESTS_UNTIL_KEY, StorageScope.APPLICATION); userDataSyncStoreService.ts
223 > if (donotMakeRequestsUntil && Date.now() < donotMakeRequestsUntil) {
224 this.setDonotMakeRequestsUntil(new Date(donotMakeRequestsUntil));
225 }
228 > private resetDonotMakeRequestsUntilPromise: CancelablePromise<void> | undefined = undefined;
229 > private setDonotMakeRequestsUntil(donotMakeRequestsUntil: Date | undefined): void {
230 > if (this._donotMakeRequestsUntil?.getTime() !== donotMakeRequestsUntil?.getTime()) { userDataSyncStoreService.ts
231 this._donotMakeRequestsUntil = donotMakeRequestsUntil;
232
246 this._onDidChangeDonotMakeRequestsUntil.fire();
247 }
250 > // #region Collection
251 >
252 > async getAllCollections(headers: IHeaders = {}): Promise<string[]> {
253 if (!this.userDataSyncStoreUrl) {
254 throw new Error('No settings sync store url configured.');
263 return (await asJson<{ id: string }[]>(context))?.map(({ id }) => id) || [];
264 }
266 > async createCollection(headers: IHeaders = {}): Promise<string> {
267 if (!this.userDataSyncStoreUrl) {
268 throw new Error('No settings sync store url configured.');
280 return collectionId;
281 }
283 > async deleteCollection(collection?: string, headers: IHeaders = {}): Promise<void> {
284 > if (!this.userDataSyncStoreUrl) { userDataSyncStoreService.ts
285 throw new Error('No settings sync store url configured.');
286 }
288 > const url = collection ? joinPath(this.userDataSyncStoreUrl, 'collection', collection).toString() : joinPath(this.userDataSyncStoreUrl, 'collection').toString();
289 > headers = { ...headers };
290 >
291 > await this.request(url, { type: 'DELETE', headers, callSite: 'userDataSync.deleteCollection' }, [], CancellationToken.None);
292 > }
294 > // #endregion
295 >
296 > // #region Resource
297 >
298 > async getAllResourceRefs(resource: ServerResource, collection?: string): Promise<IResourceRefHandle[]> {
299 if (!this.userDataSyncStoreUrl) {
300 throw new Error('No settings sync store url configured.');
309 return result.map(({ url, created }) => ({ ref: relativePath(uri, uri.with({ path: url }))!, created: created * 1000 /* Server returns in seconds */ }));
310 }
312 > async resolveResourceContent(resource: ServerResource, ref: string, collection?: string, headers: IHeaders = {}): Promise<string | null> {
313 if (!this.userDataSyncStoreUrl) {
314 throw new Error('No settings sync store url configured.');
323 return content;
324 }
326 > async deleteResource(resource: ServerResource, ref: string | null, collection?: string): Promise<void> {
327 if (!this.userDataSyncStoreUrl) {
328 throw new Error('No settings sync store url configured.');
334 await this.request(url, { type: 'DELETE', headers, callSite: 'userDataSync.deleteResource' }, [], CancellationToken.None);
335 }
337 > async deleteResources(): Promise<void> {
338 > if (!this.userDataSyncStoreUrl) { userDataSyncStoreService.ts
339 throw new Error('No settings sync store url configured.');
340 }
342 > const url = joinPath(this.userDataSyncStoreUrl, 'resource').toString();
343 > const headers: IHeaders = { 'Content-Type': Mimes.text };
344 >
345 > await this.request(url, { type: 'DELETE', headers, callSite: 'userDataSync.deleteResources' }, [], CancellationToken.None);
346 > }
348 > async readResource(resource: ServerResource, oldValue: IUserData | null, collection?: string, headers: IHeaders = {}): Promise<IUserData> {
349 if (!this.userDataSyncStoreUrl) {
350 throw new Error('No settings sync store url configured.');
382 return userData;
383 }
385 > async writeResource(resource: ServerResource, data: string, ref: string | null, collection?: string, headers: IHeaders = {}): Promise<string> {
386 > if (!this.userDataSyncStoreUrl) { userDataSyncStoreService.ts
387 throw new Error('No settings sync store url configured.');
388 }
390 > const url = this.getResourceUrl(this.userDataSyncStoreUrl, collection, resource).toString();
391 > headers = { ...headers };
392 > headers['Content-Type'] = Mimes.text;
393 > if (ref) {
394 > headers['If-Match'] = ref; userDataSyncStoreService.ts
395 > }
397 > const context = await this.request(url, { type: 'POST', data, headers, callSite: 'userDataSync.writeResource' }, [], CancellationToken.None);
398 >
399 > const newRef = context.res.headers['etag'];
400 > if (!newRef) {
401 throw new UserDataSyncStoreError('Server did not return the ref', url, UserDataSyncErrorCode.NoRef, context.res.statusCode, context.res.headers[HEADER_OPERATION_ID]);
402 }
403 > return newRef; userDataSyncStoreService.ts
404 > }
406 > // #endregion
407 >
408 > async manifest(oldValue: IUserDataManifest | null, headers: IHeaders = {}): Promise<IUserDataManifest | null> {
409 > if (!this.userDataSyncStoreUrl) { userDataSyncStoreService.ts
410 throw new Error('No settings sync store url configured.');
411 }
413 > const url = joinPath(this.userDataSyncStoreUrl, 'manifest').toString();
414 > headers = { ...headers };
415 > headers['Content-Type'] = 'application/json';
416 > if (oldValue) {
417 headers['If-None-Match'] = oldValue.ref;
418 }
420 > const context = await this.request(url, { type: 'GET', headers, callSite: 'userDataSync.manifest' }, [304], CancellationToken.None);
421 >
422 > let manifest: IUserDataManifest | null = null;
423 > if (context.res.statusCode === 304) {
424 manifest = oldValue;
425 }
427 > if (!manifest) {
428 > const ref = context.res.headers['etag'];
429 > if (!ref) {
430 throw new UserDataSyncStoreError('Server did not return the ref', url, UserDataSyncErrorCode.NoRef, context.res.statusCode, context.res.headers[HEADER_OPERATION_ID]);
431 }
433 > const content = await asTextOrError(context);
434 > if (!content && context.res.statusCode === 304) {
435 throw new UserDataSyncStoreError('Empty response', url, UserDataSyncErrorCode.EmptyResponse, context.res.statusCode, context.res.headers[HEADER_OPERATION_ID]);
436 }
438 > if (content) {
439 manifest = { ...JSON.parse(content), ref };
440 }
442 >
443 > const currentSessionId = this.storageService.get(USER_SESSION_ID_KEY, StorageScope.APPLICATION);
444 >
445 > if (currentSessionId && manifest && currentSessionId !== manifest.session) {
446 // Server session is different from client session so clear cached session.
447 this.clearSession();
448 }
450 > if (manifest === null && currentSessionId) {
451 // server session is cleared so clear cached session.
452 this.clearSession();
453 }
455 > if (manifest) {
456 // update session
457 this.storageService.store(USER_SESSION_ID_KEY, manifest.session, StorageScope.APPLICATION, StorageTarget.MACHINE);
458 }
460 > return manifest;
461 > }
463 > async clear(): Promise<void> {
464 > if (!this.userDataSyncStoreUrl) { userDataSyncStoreService.ts
465 throw new Error('No settings sync store url configured.');
466 }
468 > await this.deleteCollection();
469 > await this.deleteResources();
470 >
471 > // clear cached session.
472 > this.clearSession();
473 > }
475 > async getLatestData(headers: IHeaders = {}): Promise<IUserDataSyncLatestData | null> {
476 if (!this.userDataSyncStoreUrl) {
477 throw new Error('No settings sync store url configured.');
522 return result;
523 }
525 > async getActivityData(): Promise<VSBufferReadableStream> {
526 if (!this.userDataSyncStoreUrl) {
527 throw new Error('No settings sync store url configured.');
543 return context.stream;
544 }
546 > private getResourceUrl(userDataSyncStoreUrl: URI, collection: string | undefined, resource: ServerResource): URI {
547 > return collection ? joinPath(userDataSyncStoreUrl, 'collection', collection, 'resource', resource) : joinPath(userDataSyncStoreUrl, 'resource', resource); userDataSyncStoreService.ts
548 > }
550 > private clearSession(): void {
551 > this.storageService.remove(USER_SESSION_ID_KEY, StorageScope.APPLICATION); userDataSyncStoreService.ts
552 > this.storageService.remove(MACHINE_SESSION_ID_KEY, StorageScope.APPLICATION);
553 > }
555 > private async request(url: string, options: IRequestOptions, successCodes: number[], token: CancellationToken): Promise<IRequestContext> {
556 > if (!this.authToken) { userDataSyncStoreService.ts
557 throw new UserDataSyncStoreError('No Auth Token Available', url, UserDataSyncErrorCode.Unauthorized, undefined, undefined);
558 }
560 > if (this._donotMakeRequestsUntil && Date.now() < this._donotMakeRequestsUntil.getTime()) {
561 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed because of too many requests (429).`, url, UserDataSyncErrorCode.TooManyRequestsAndRetryAfter, undefined, undefined);
562 }
563 > this.setDonotMakeRequestsUntil(undefined); userDataSyncStoreService.ts
564 >
565 > const commonHeaders = await this.commonHeadersPromise;
566 > options.headers = {
567 > ...(options.headers || {}),
568 > ...commonHeaders,
569 > 'X-Account-Type': this.authToken.type,
570 > 'authorization': `Bearer ${this.authToken.token}`,
571 > };
572 >
573 > // Add session headers
574 > this.addSessionHeaders(options.headers);
575 >
576 > this.logService.trace('Sending request to server', { url, type: options.type, headers: { ...options.headers, ...{ authorization: undefined } } });
577 >
578 > let context;
579 > try {
580 > context = await this.session.request(url, options, token);
581 > } catch (e) {
582 if (!(e instanceof UserDataSyncStoreError)) {
583 let code = UserDataSyncErrorCode.RequestFailed;
614 throw e;
615 }
617 > const operationId = context.res.headers[HEADER_OPERATION_ID];
618 > const requestInfo = { url, status: context.res.statusCode, 'execution-id': options.headers[HEADER_EXECUTION_ID], 'operation-id': operationId };
619 > const isSuccess = isSuccessContext(context) || (context.res.statusCode && successCodes.includes(context.res.statusCode));
620 > let failureMessage = '';
621 > if (isSuccess) {
622 > this.logService.trace('Request succeeded', requestInfo);
623 > } else {
624 failureMessage = await asText(context) || '';
625 this.logService.info('Request failed', requestInfo, failureMessage);
626 }
628 > if (context.res.statusCode === 401 || context.res.statusCode === 403) {
629 this.authToken = undefined;
630 if (context.res.statusCode === 401) {
637 }
638 }
640 > this._onTokenSucceed.fire();
641 >
642 > if (context.res.statusCode === 404) {
643 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed because the requested resource is not found (404).`, url, UserDataSyncErrorCode.NotFound, context.res.statusCode, operationId);
644 }
646 > if (context.res.statusCode === 405) {
647 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed because the requested endpoint is not found (405). ${failureMessage}`, url, UserDataSyncErrorCode.MethodNotFound, context.res.statusCode, operationId);
648 }
650 > if (context.res.statusCode === 409) {
651 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed because of Conflict (409). There is new data for this resource. Make the request again with latest data.`, url, UserDataSyncErrorCode.Conflict, context.res.statusCode, operationId);
652 }
654 > if (context.res.statusCode === 410) {
655 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed because the requested resource is not longer available (410).`, url, UserDataSyncErrorCode.Gone, context.res.statusCode, operationId);
656 }
658 > if (context.res.statusCode === 412) {
659 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed because of Precondition Failed (412). There is new data for this resource. Make the request again with latest data.`, url, UserDataSyncErrorCode.PreconditionFailed, context.res.statusCode, operationId);
660 }
662 > if (context.res.statusCode === 413) {
663 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed because of too large payload (413).`, url, UserDataSyncErrorCode.TooLarge, context.res.statusCode, operationId);
664 }
666 > if (context.res.statusCode === 426) {
667 throw new UserDataSyncStoreError(`${options.type} request '${url}' failed with status Upgrade Required (426). Please upgrade the client and try again.`, url, UserDataSyncErrorCode.UpgradeRequired, context.res.statusCode, operationId);
668 }
670 > if (context.res.statusCode === 429) {
671 const retryAfter = context.res.headers['retry-after'];
672 if (retryAfter) {
677 }
678 }
680 > if (!isSuccess) {
681 throw new UserDataSyncStoreError('Server returned ' + context.res.statusCode, url, UserDataSyncErrorCode.Unknown, context.res.statusCode, operationId);
682 }
684 > return context;
685 > }
687 > private addSessionHeaders(headers: IHeaders): void {
688 > let machineSessionId = this.storageService.get(MACHINE_SESSION_ID_KEY, StorageScope.APPLICATION); userDataSyncStoreService.ts
689 > if (machineSessionId === undefined) {
690 > machineSessionId = generateUuid();
691 > this.storageService.store(MACHINE_SESSION_ID_KEY, machineSessionId, StorageScope.APPLICATION, StorageTarget.MACHINE);
692 > }
693 > headers['X-Machine-Session-Id'] = machineSessionId;
694 >
695 > const userSessionId = this.storageService.get(USER_SESSION_ID_KEY, StorageScope.APPLICATION);
696 > if (userSessionId !== undefined) {
697 headers['X-User-Session-Id'] = userSessionId;
698 }
701 > }
702 >
703 > export class UserDataSyncStoreService extends UserDataSyncStoreClient implements IUserDataSyncStoreService {
704 >
705 > _serviceBrand: undefined;
706 >
707 > constructor(
708 > @IUserDataSyncStoreManagementService userDataSyncStoreManagementService: IUserDataSyncStoreManagementService, userDataSyncStoreService.ts
709 > @IProductService productService: IProductService,
710 > @IRequestService requestService: IRequestService,
711 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
712 > @IEnvironmentService environmentService: IEnvironmentService,
713 > @IFileService fileService: IFileService,
714 > @IStorageService storageService: IStorageService,
715 > ) {
716 > super(userDataSyncStoreManagementService.userDataSyncStore?.url, productService, requestService, logService, environmentService, fileService, storageService);
717 > this._register(userDataSyncStoreManagementService.onDidChangeUserDataSyncStore(() => this.updateUserDataSyncStoreUrl(userDataSyncStoreManagementService.userDataSyncStore?.url)));
718 > }
720 > }
721 >
722 > export class RequestsSession {
723 >
724 > private requests: string[] = [];
725 > private startTime: Date | undefined = undefined;
726 >
727 > constructor(
728 > private readonly limit: number, userDataSyncStoreService.ts
729 > private readonly interval: number, /* in ms */
730 > private readonly requestService: IRequestService,
731 > private readonly logService: IUserDataSyncLogService,
732 > ) { }
734 > request(url: string, options: IRequestOptions, token: CancellationToken): Promise<IRequestContext> {
735 > if (this.isExpired()) { userDataSyncStoreService.ts
736 this.reset();
737 }
739 > options.url = url;
740 >
741 > if (this.requests.length >= this.limit) {
742 this.logService.info('Too many requests', ...this.requests);
743 throw new UserDataSyncStoreError(`Too many requests. Only ${this.limit} requests allowed in ${this.interval / (1000 * 60)} minutes.`, url, UserDataSyncErrorCode.LocalTooManyRequests, undefined, undefined);
744 }
746 > this.startTime = this.startTime || new Date();
747 > this.requests.push(url);
748 >
749 > return this.requestService.request(options, token);
750 > }
752 > private isExpired(): boolean {
753 > return this.startTime !== undefined && new Date().getTime() - this.startTime.getTime() > this.interval; userDataSyncStoreService.ts
754 > }
756 > private reset(): void {
757 this.requests = [];
758 this.startTime = undefined;
759 }
761 > }
src/vs/base/common/arrays.ts 429 covered LOC · 86 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- arrays.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { findFirstIdxMonotonousOrArrLen } from './arraysFind.js';
7 > import { CancellationToken } from './cancellation.js';
8 > import { CancellationError } from './errors.js';
9 > import { ISplice } from './sequence.js';
10 >
11 > /**
12 > * Returns the last entry and the initial N-1 entries of the array, as a tuple of [rest, last].
13 > *
14 > * The array must have at least one element.
15 > *
16 > * @param arr The input array
17 > * @returns A tuple of [rest, last] where rest is all but the last element and last is the last element
18 > * @throws Error if the array is empty
19 > */
20 > export function tail<T>(arr: T[]): [T[], T] {
21 if (arr.length === 0) {
22 throw new Error('Invalid tail call');
25 return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
26 }
27 > arrays.ts
28 > export function equals<T>(one: ReadonlyArray<T> | undefined, other: ReadonlyArray<T> | undefined, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean {
29 > if (one === other) { arrays.ts
30 return true;
31 }
32 > arrays.ts
33 > if (!one || !other) { arrays.ts
34 return false;
35 }
36 > arrays.ts
37 > if (one.length !== other.length) {
38 return false;
39 }
40 > arrays.ts
41 > for (let i = 0, len = one.length; i < len; i++) {
42 if (!itemEquals(one[i], other[i])) {
43 return false;
44 }
45 }
46 > arrays.ts
47 > return true;
48 > }
49 > arrays.ts
50 > /**
51 > * Remove the element at `index` by replacing it with the last element. This is faster than `splice`
52 > * but changes the order of the array
53 > */
54 > export function removeFastWithoutKeepingOrder<T>(array: T[], index: number) {
55 const last = array.length - 1;
56 if (index < last) {
59 array.pop();
60 }
61 > arrays.ts
62 > /**
63 > * Performs a binary search algorithm over a sorted array.
64 > *
65 > * @param array The array being searched.
66 > * @param key The value we search for.
67 > * @param comparator A function that takes two array elements and returns zero
68 > * if they are equal, a negative number if the first element precedes the
69 > * second one in the sorting order, or a positive number if the second element
70 > * precedes the first one.
71 > * @return See {@link binarySearch2}
72 > */
73 > export function binarySearch<T>(array: ReadonlyArray<T>, key: T, comparator: (op1: T, op2: T) => number): number {
74 return binarySearch2(array.length, i => comparator(array[i], key));
75 }
76 > arrays.ts
77 > /**
78 > * Performs a binary search algorithm over a sorted collection. Useful for cases
79 > * when we need to perform a binary search over something that isn't actually an
80 > * array, and converting data to an array would defeat the use of binary search
81 > * in the first place.
82 > *
83 > * @param length The collection length.
84 > * @param compareToKey A function that takes an index of an element in the
85 > * collection and returns zero if the value at this index is equal to the
86 > * search key, a negative number if the value precedes the search key in the
87 > * sorting order, or a positive number if the search key precedes the value.
88 > * @return A non-negative index of an element, if found. If not found, the
89 > * result is -(n+1) (or ~n, using bitwise notation), where n is the index
90 > * where the key should be inserted to maintain the sorting order.
91 > */
92 > export function binarySearch2(length: number, compareToKey: (index: number) => number): number {
93 let low = 0,
94 high = length - 1;
107 return -(low + 1);
108 }
109 > arrays.ts
110 > type Compare<T> = (a: T, b: T) => number;
111 >
112 > /**
113 > * Finds the nth smallest element in the array using quickselect algorithm.
114 > * The data does not need to be sorted.
115 > *
116 > * @param nth The zero-based index of the element to find (0 = smallest, 1 = second smallest, etc.)
117 > * @param data The unsorted array
118 > * @param compare A comparator function that defines the sort order
119 > * @returns The nth smallest element
120 > * @throws TypeError if nth is >= data.length
121 > */
122 > export function quickSelect<T>(nth: number, data: T[], compare: Compare<T>): T {
123
124 nth = nth | 0;
152 }
153 }
154 > arrays.ts
155 > export function groupBy<T>(data: ReadonlyArray<T>, compare: (a: T, b: T) => number): T[][] {
156 const result: T[][] = [];
157 let currentGroup: T[] | undefined = undefined;
166 return result;
167 }
168 > arrays.ts
169 > /**
170 > * Splits the given items into a list of (non-empty) groups.
171 > * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group.
172 > * The order of the items is preserved.
173 > */
174 > export function* groupAdjacentBy<T>(items: Iterable<T>, shouldBeGrouped: (item1: T, item2: T) => boolean): Iterable<T[]> {
175 let currentGroup: T[] | undefined;
176 let last: T | undefined;
190 }
191 }
192 > arrays.ts
193 > export function forEachAdjacent<T>(arr: T[], f: (item1: T | undefined, item2: T | undefined) => void): void {
194 for (let i = 0; i <= arr.length; i++) {
195 f(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]);
196 }
197 }
198 > arrays.ts
199 > export function forEachWithNeighbors<T>(arr: T[], f: (before: T | undefined, element: T, after: T | undefined) => void): void {
200 for (let i = 0; i < arr.length; i++) {
201 f(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]);
202 }
203 }
204 > arrays.ts
205 > export function concatArrays<T extends any[]>(...arrays: T): T[number][number][] {
206 return [].concat(...arrays);
207 }
208 > arrays.ts
209 > interface IMutableSplice<T> extends ISplice<T> {
210 > readonly toInsert: T[];
211 > deleteCount: number;
212 > }
213 >
214 > /**
215 > * Diffs two *sorted* arrays and computes the splices which apply the diff.
216 > */
217 > export function sortedDiff<T>(before: ReadonlyArray<T>, after: ReadonlyArray<T>, compare: (a: T, b: T) => number): ISplice<T>[] {
218 const result: IMutableSplice<T>[] = [];
219
266 return result;
267 }
268 > arrays.ts
269 > /**
270 > * Takes two *sorted* arrays and computes their delta (removed, added elements).
271 > * Finishes in `Math.min(before.length, after.length)` steps.
272 > */
273 > export function delta<T>(before: ReadonlyArray<T>, after: ReadonlyArray<T>, compare: (a: T, b: T) => number): { removed: T[]; added: T[] } {
274 const splices = sortedDiff(before, after, compare);
275 const removed: T[] = [];
283 return { removed, added };
284 }
285 > arrays.ts
286 > /**
287 > * Returns the top N elements from the array.
288 > *
289 > * Faster than sorting the entire array when the array is a lot larger than N.
290 > *
291 > * @param array The unsorted array.
292 > * @param compare A sort function for the elements.
293 > * @param n The number of elements to return.
294 > * @return The first n elements from array when sorted with compare.
295 > */
296 > export function top<T>(array: ReadonlyArray<T>, compare: (a: T, b: T) => number, n: number): T[] {
297 if (n === 0) {
298 return [];
302 return result;
303 }
304 > arrays.ts
305 > /**
306 > * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run.
307 > *
308 > * Returns the top N elements from the array.
309 > *
310 > * Faster than sorting the entire array when the array is a lot larger than N.
311 > *
312 > * @param array The unsorted array.
313 > * @param compare A sort function for the elements.
314 > * @param n The number of elements to return.
315 > * @param batch The number of elements to examine before yielding to the event loop.
316 > * @return The first n elements from array when sorted with compare.
317 > */
318 > export function topAsync<T>(array: T[], compare: (a: T, b: T) => number, n: number, batch: number, token?: CancellationToken): Promise<T[]> {
319 if (n === 0) {
320 return Promise.resolve([]);
339 });
340 }
341 > arrays.ts
342 function topStep<T>(array: ReadonlyArray<T>, compare: (a: T, b: T) => number, result: T[], i: number, m: number): void {
343 for (const n = result.length; i < m; i++) {
350 }
351 }
352 > arrays.ts
353 > /**
354 > * @returns New array with all falsy values removed. The original array IS NOT modified.
355 > */
356 > export function coalesce<T>(array: ReadonlyArray<T | undefined | null>): T[] {
357 > return array.filter((e): e is T => !!e); arrays.ts
358 > }
359 > arrays.ts
360 > /**
361 > * Remove all falsy values from `array`. The original array IS modified.
362 > */
363 > export function coalesceInPlace<T>(array: Array<T | undefined | null>): asserts array is Array<T> {
364 let to = 0;
365 for (let i = 0; i < array.length; i++) {
371 array.length = to;
372 }
373 > arrays.ts
374 > /**
375 > * @deprecated Use `Array.copyWithin` instead
376 > */
377 > export function move(array: unknown[], from: number, to: number): void {
378 array.splice(to, 0, array.splice(from, 1)[0]);
379 }
380 > arrays.ts
381 > /**
382 > * @returns false if the provided object is an array and not empty.
383 > */
384 > export function isFalsyOrEmpty(obj: unknown): boolean {
385 return !Array.isArray(obj) || obj.length === 0;
386 }
387 > arrays.ts
388 > /**
389 > * @returns True if the provided object is an array and has at least one element.
390 > */
391 > export function isNonEmptyArray<T>(obj: T[] | undefined | null): obj is T[];
392 > export function isNonEmptyArray<T>(obj: readonly T[] | undefined | null): obj is readonly T[];
393 > export function isNonEmptyArray<T>(obj: T[] | readonly T[] | undefined | null): obj is T[] | readonly T[] {
394 return Array.isArray(obj) && obj.length > 0;
395 }
396 > arrays.ts
397 > /**
398 > * Removes duplicates from the given array. The optional keyFn allows to specify
399 > * how elements are checked for equality by returning an alternate value for each.
400 > */
401 > export function distinct<T>(array: ReadonlyArray<T>, keyFn: (value: T) => unknown = value => value): T[] {
402 > const seen = new Set<any>(); arrays.ts
403 >
404 > return array.filter(element => {
405 > const key = keyFn(element); arrays.ts
406 > if (seen.has(key)) {
407 return false;
408 }
409 > seen.add(key); arrays.ts
410 > return true;
411 > }); arrays.ts
412 > }
413 > arrays.ts
414 > export function uniqueFilter<T, R>(keyFn: (t: T) => R): (t: T) => boolean {
415 const seen = new Set<R>();
416
426 };
427 }
428 > arrays.ts
429 > export function commonPrefixLength<T>(one: ReadonlyArray<T>, other: ReadonlyArray<T>, equals: (a: T, b: T) => boolean = (a, b) => a === b): number {
430 let result = 0;
431
436 return result;
437 }
438 > arrays.ts
439 > export function range(to: number): number[];
440 > export function range(from: number, to: number): number[];
441 > export function range(arg: number, to?: number): number[] {
442 let from = typeof to === 'number' ? arg : 0;
443
463 return result;
464 }
465 > arrays.ts
466 > export function index<T>(array: ReadonlyArray<T>, indexer: (t: T) => string): { [key: string]: T };
467 > export function index<T, R>(array: ReadonlyArray<T>, indexer: (t: T) => string, mapper: (t: T) => R): { [key: string]: R };
468 > export function index<T, R>(array: ReadonlyArray<T>, indexer: (t: T) => string, mapper?: (t: T) => R): { [key: string]: R } {
469 return array.reduce((r, t) => {
470 r[indexer(t)] = mapper ? mapper(t) : t;
472 }, Object.create(null));
473 }
474 > arrays.ts
475 > /**
476 > * Inserts an element into an array. Returns a function which, when
477 > * called, will remove that element from the array.
478 > *
479 > * @deprecated In almost all cases, use a `Set<T>` instead.
480 > */
481 > export function insert<T>(array: T[], element: T): () => void {
482 array.push(element);
483
484 return () => remove(array, element);
485 }
486 > arrays.ts
487 > /**
488 > * Removes an element from an array if it can be found.
489 > *
490 > * @deprecated In almost all cases, use a `Set<T>` instead.
491 > */
492 > export function remove<T>(array: T[], element: T): T | undefined {
493 const index = array.indexOf(element);
494 if (index > -1) {
500 return undefined;
501 }
502 > arrays.ts
503 > /**
504 > * Insert `insertArr` inside `target` at `insertIndex`.
505 > * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array
506 > */
507 > export function arrayInsert<T>(target: T[], insertIndex: number, insertArr: T[]): T[] {
508 const before = target.slice(0, insertIndex);
509 const after = target.slice(insertIndex);
510 return before.concat(insertArr, after);
511 }
512 > arrays.ts
513 > /**
514 > * Uses Fisher-Yates shuffle to shuffle the given array
515 > */
516 > export function shuffle<T>(array: T[], _seed?: number): void {
517 let rand: () => number;
518
536 }
537 }
538 > arrays.ts
539 > /**
540 > * Pushes an element to the start of the array, if found.
541 > */
542 > export function pushToStart<T>(arr: T[], value: T): void {
543 const index = arr.indexOf(value);
544
548 }
549 }
550 > arrays.ts
551 > /**
552 > * Pushes an element to the end of the array, if found.
553 > */
554 > export function pushToEnd<T>(arr: T[], value: T): void {
555 const index = arr.indexOf(value);
556
560 }
561 }
562 > arrays.ts
563 > export function pushMany<T>(arr: T[], items: ReadonlyArray<T>): void {
564 for (const item of items) {
565 arr.push(item);
566 }
567 }
568 > arrays.ts
569 > export function mapArrayOrNot<T, U>(items: T | T[], fn: (_: T) => U): U | U[] {
570 return Array.isArray(items) ?
571 items.map(fn) :
572 fn(items);
573 }
574 > arrays.ts
575 > export function mapFilter<T, U>(array: ReadonlyArray<T>, fn: (t: T) => U | undefined): U[] {
576 const result: U[] = [];
577 for (const item of array) {
583 return result;
584 }
585 > arrays.ts
586 > export function withoutDuplicates<T>(array: ReadonlyArray<T>): T[] {
587 const s = new Set(array);
588 return Array.from(s);
589 }
590 > arrays.ts
591 > export function asArray<T>(x: T | T[]): T[];
592 > export function asArray<T>(x: T | readonly T[]): readonly T[];
593 > export function asArray<T>(x: T | T[]): T[] {
594 return Array.isArray(x) ? x : [x];
595 }
596 > arrays.ts
597 > export function getRandomElement<T>(arr: T[]): T | undefined {
598 return arr[Math.floor(Math.random() * arr.length)];
599 }
600 > arrays.ts
601 > /**
602 > * Insert the new items in the array.
603 > * @param array The original array.
604 > * @param start The zero-based location in the array from which to start inserting elements.
605 > * @param newItems The items to be inserted
606 > */
607 > export function insertInto<T>(array: T[], start: number, newItems: T[]): void {
608 const startIdx = getActualStartIndex(array, start);
609 const originalLength = array.length;
619 }
620 }
621 > arrays.ts
622 > /**
623 > * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it
624 > * can only support limited number of items due to the maximum call stack size limit.
625 > * @param array The original array.
626 > * @param start The zero-based location in the array from which to start removing elements.
627 > * @param deleteCount The number of elements to remove.
628 > * @returns An array containing the elements that were deleted.
629 > */
630 > export function splice<T>(array: T[], start: number, deleteCount: number, newItems: T[]): T[] {
631 const index = getActualStartIndex(array, start);
632 let result = array.splice(index, deleteCount);
638 return result;
639 }
640 > arrays.ts
641 > /**
642 > * Determine the actual start index (same logic as the native splice() or slice())
643 > * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.
644 > * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0.
645 > * @param array The target array.
646 > * @param start The operation index.
647 > */
648 function getActualStartIndex<T>(array: T[], start: number): number {
649 return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length);
650 }
651 > arrays.ts
652 >
653 >
654 > /**
655 > * When comparing two values,
656 > * a negative number indicates that the first value is less than the second,
657 > * a positive number indicates that the first value is greater than the second,
658 > * and zero indicates that neither is the case.
659 > */
660 > export type CompareResult = number;
661 >
662 > export namespace CompareResult {
663 > export function isLessThan(result: CompareResult): boolean {
664 return result < 0;
665 }
666 > arrays.ts
667 > export function isLessThanOrEqual(result: CompareResult): boolean {
668 return result <= 0;
669 }
670 > arrays.ts
671 > export function isGreaterThan(result: CompareResult): boolean {
672 return result > 0;
673 }
674 > arrays.ts
675 > export function isNeitherLessOrGreaterThan(result: CompareResult): boolean {
676 return result === 0;
677 }
678 > arrays.ts
679 > export const greaterThan = 1;
680 > export const lessThan = -1;
681 > export const neitherLessOrGreaterThan = 0;
682 > }
683 >
684 > /**
685 > * A comparator `c` defines a total order `<=` on `T` as following:
686 > * `c(a, b) <= 0` iff `a` <= `b`.
687 > * We also have `c(a, b) == 0` iff `c(b, a) == 0`.
688 > */
689 > export type Comparator<T> = (a: T, b: T) => CompareResult;
690 >
691 > export function compareBy<TItem, TCompareBy>(selector: (item: TItem) => TCompareBy, comparator: Comparator<TCompareBy>): Comparator<TItem> {
692 > return (a, b) => comparator(selector(a), selector(b)); arrays.ts
693 > }
694 > arrays.ts
695 > export function tieBreakComparators<TItem>(...comparators: Comparator<TItem>[]): Comparator<TItem> {
696 > return (item1, item2) => { arrays.ts
697 for (const comparator of comparators) {
698 const result = comparator(item1, item2);
703 return CompareResult.neitherLessOrGreaterThan;
704 };
705 > } arrays.ts
706 > arrays.ts
707 > /**
708 > * The natural order on numbers.
709 > */
710 > export const numberComparator: Comparator<number> = (a, b) => a - b;
711 >
712 > export const booleanComparator: Comparator<boolean> = (a, b) => numberComparator(a ? 1 : 0, b ? 1 : 0);
713 >
714 > export function reverseOrder<TItem>(comparator: Comparator<TItem>): Comparator<TItem> {
715 return (a, b) => -comparator(a, b);
716 }
717 > arrays.ts
718 > /**
719 > * Returns a new comparator that treats `undefined` as the smallest value.
720 > * All other values are compared using the given comparator.
721 > */
722 > export function compareUndefinedSmallest<T>(comparator: Comparator<T>): Comparator<T | undefined> {
723 return (a, b) => {
724 if (a === undefined) {
731 };
732 }
733 > arrays.ts
734 > export class ArrayQueue<T> {
735 > private readonly items: readonly T[];
736 > private firstIdx = 0;
737 > private lastIdx: number;
738 >
739 > /**
740 > * Constructs a queue that is backed by the given array. Runtime is O(1).
741 > */
742 > constructor(items: readonly T[]) {
743 this.items = items;
744 this.lastIdx = this.items.length - 1;
745 }
746 > arrays.ts
747 > get length(): number {
748 return this.lastIdx - this.firstIdx + 1;
749 }
750 > arrays.ts
751 > /**
752 > * Consumes elements from the beginning of the queue as long as the predicate returns true.
753 > * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).
754 > */
755 > takeWhile(predicate: (value: T) => boolean): T[] | null {
756 // P(k) := k <= this.lastIdx && predicate(this.items[k])
757 // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s)
765 return result;
766 }
767 > arrays.ts
768 > /**
769 > * Consumes elements from the end of the queue as long as the predicate returns true.
770 > * If no elements were consumed, `null` is returned.
771 > * The result has the same order as the underlying array!
772 > */
773 > takeFromEndWhile(predicate: (value: T) => boolean): T[] | null {
774 // P(k) := this.firstIdx >= k && predicate(this.items[k])
775 // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx]
783 return result;
784 }
785 > arrays.ts
786 > peek(): T | undefined {
787 if (this.length === 0) {
788 return undefined;
790 return this.items[this.firstIdx];
791 }
792 > arrays.ts
793 > peekLast(): T | undefined {
794 if (this.length === 0) {
795 return undefined;
797 return this.items[this.lastIdx];
798 }
799 > arrays.ts
800 > dequeue(): T | undefined {
801 const result = this.items[this.firstIdx];
802 this.firstIdx++;
803 return result;
804 }
805 > arrays.ts
806 > removeLast(): T | undefined {
807 const result = this.items[this.lastIdx];
808 this.lastIdx--;
809 return result;
810 }
811 > arrays.ts
812 > takeCount(count: number): T[] {
813 const result = this.items.slice(this.firstIdx, this.firstIdx + count);
814 this.firstIdx += count;
815 return result;
816 }
817 > } arrays.ts
818 >
819 > /**
820 > * This class is faster than an iterator and array for lazy computed data.
821 > */
822 > export class CallbackIterable<T> {
823 > public static readonly empty = new CallbackIterable<never>(_callback => { });
824 >
825 > constructor(
826 > /**
827 > * Calls the callback for every item.
828 > * Stops when the callback returns false.
829 > */
830 > public readonly iterate: (callback: (item: T) => boolean) => void
831 > ) {
832 > }
833 >
834 > forEach(handler: (item: T) => void) {
835 this.iterate(item => { handler(item); return true; });
836 }
837 > arrays.ts
838 > toArray(): T[] {
839 const result: T[] = [];
840 this.iterate(item => { result.push(item); return true; });
841 return result;
842 }
843 > arrays.ts
844 > filter(predicate: (item: T) => boolean): CallbackIterable<T> {
845 return new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true));
846 }
847 > arrays.ts
848 > map<TResult>(mapFn: (item: T) => TResult): CallbackIterable<TResult> {
849 return new CallbackIterable<TResult>(cb => this.iterate(item => cb(mapFn(item))));
850 }
851 > arrays.ts
852 > some(predicate: (item: T) => boolean): boolean {
853 let result = false;
854 this.iterate(item => { result = predicate(item); return !result; });
855 return result;
856 }
857 > arrays.ts
858 > findFirst(predicate: (item: T) => boolean): T | undefined {
859 let result: T | undefined;
860 this.iterate(item => {
867 return result;
868 }
869 > arrays.ts
870 > findLast(predicate: (item: T) => boolean): T | undefined {
871 let result: T | undefined;
872 this.iterate(item => {
878 return result;
879 }
880 > arrays.ts
881 > findLastMaxBy(comparator: Comparator<T>): T | undefined {
882 let result: T | undefined;
883 let first = true;
891 return result;
892 }
893 > } arrays.ts
894 >
895 > /**
896 > * Represents a re-arrangement of items in an array.
897 > */
898 > export class Permutation {
899 > constructor(private readonly _indexMap: readonly number[]) { }
900 >
901 > /**
902 > * Returns a permutation that sorts the given array according to the given compare function.
903 > */
904 > public static createSortPermutation<T>(arr: readonly T[], compareFn: (a: T, b: T) => number): Permutation {
905 const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2]));
906 return new Permutation(sortIndices);
907 }
908 > arrays.ts
909 > /**
910 > * Returns a new array with the elements of the given array re-arranged according to this permutation.
911 > */
912 > apply<T>(arr: readonly T[]): T[] {
913 return arr.map((_, index) => arr[this._indexMap[index]]);
914 }
915 > arrays.ts
916 > /**
917 > * Returns a new permutation that undoes the re-arrangement of this permutation.
918 > */
919 > inverse(): Permutation {
920 const inverseIndexMap = this._indexMap.slice();
921 for (let i = 0; i < this._indexMap.length; i++) {
924 return new Permutation(inverseIndexMap);
925 }
926 > } arrays.ts
927 >
928 > /**
929 > * Asynchronous variant of `Array.find()`, returning the first element in
930 > * the array for which the predicate returns true.
931 > *
932 > * This implementation does not bail early and waits for all promises to
933 > * resolve before returning.
934 > */
935 export async function findAsync<T>(array: readonly T[], predicate: (element: T, index: number) => Promise<boolean>): Promise<T | undefined> {
936 const results = await Promise.all(array.map(
940 return results.find(r => r.ok)?.element;
941 }
942 > arrays.ts
943 > export function sum(array: readonly number[]): number {
944 return array.reduce((acc, value) => acc + value, 0);
945 }
946 > arrays.ts
947 > export function sumBy<T>(array: readonly T[], selector: (value: T) => number): number {
948 return array.reduce((acc, value) => acc + selector(value), 0);
949 }
src/vs/base/common/path.ts 415 covered LOC · 100 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- path.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // NOTE: VSCode's copy of nodejs path library to be usable in common (non-node) namespace
7 > // Copied from: https://github.com/nodejs/node/commits/v22.15.0/lib/path.js
8 > // Excluding: the change that adds primordials
9 > // (https://github.com/nodejs/node/commit/187a862d221dec42fa9a5c4214e7034d9092792f and others)
10 > // Excluding: the change that adds glob matching
11 > // (https://github.com/nodejs/node/commit/57b8b8e18e5e2007114c63b71bf0baedc01936a6)
12 >
13 > /**
14 > * Copyright Joyent, Inc. and other Node contributors.
15 > *
16 > * Permission is hereby granted, free of charge, to any person obtaining a
17 > * copy of this software and associated documentation files (the
18 > * "Software"), to deal in the Software without restriction, including
19 > * without limitation the rights to use, copy, modify, merge, publish,
20 > * distribute, sublicense, and/or sell copies of the Software, and to permit
21 > * persons to whom the Software is furnished to do so, subject to the
22 > * following conditions:
23 > *
24 > * The above copyright notice and this permission notice shall be included
25 > * in all copies or substantial portions of the Software.
26 > *
27 > * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
28 > * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 > * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
30 > * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
31 > * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
32 > * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
33 > * USE OR OTHER DEALINGS IN THE SOFTWARE.
34 > */
35 >
36 > import * as process from './process.js';
37 >
38 > const CHAR_UPPERCASE_A = 65;/* A */
39 > const CHAR_LOWERCASE_A = 97; /* a */
40 > const CHAR_UPPERCASE_Z = 90; /* Z */
41 > const CHAR_LOWERCASE_Z = 122; /* z */
42 > const CHAR_DOT = 46; /* . */
43 > const CHAR_FORWARD_SLASH = 47; /* / */
44 > const CHAR_BACKWARD_SLASH = 92; /* \ */
45 > const CHAR_COLON = 58; /* : */
46 > const CHAR_QUESTION_MARK = 63; /* ? */
47 >
48 > class ErrorInvalidArgType extends Error {
49 > code: 'ERR_INVALID_ARG_TYPE';
50 > constructor(name: string, expected: string, actual: unknown) {
51 // determiner: 'must be' or 'must not be'
52 let determiner;
66 this.code = 'ERR_INVALID_ARG_TYPE';
67 }
68 > } path.ts
69 >
70 function validateObject(pathObject: object, name: string) {
71 if (pathObject === null || typeof pathObject !== 'object') {
73 }
74 }
75 > path.ts
76 > function validateString(value: string, name: string) { path.ts
77 > if (typeof value !== 'string') {
78 throw new ErrorInvalidArgType(name, 'string', value);
79 }
80 > } path.ts
81 > path.ts
82 > const platformIsWin32 = (process.platform === 'win32');
83 >
84 function isPathSeparator(code: number | undefined) {
85 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
86 }
87 > path.ts
88 > function isPosixPathSeparator(code: number | undefined) { path.ts
89 > return code === CHAR_FORWARD_SLASH;
90 > }
91 > path.ts
92 function isWindowsDeviceRoot(code: number) {
93 return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
94 (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z);
95 }
96 > path.ts
97 > // Resolves . and .. elements in a path with directory names
98 > function normalizeString(path: string, allowAboveRoot: boolean, separator: string, isPathSeparator: (code?: number) => boolean) { path.ts
99 > let res = '';
100 > let lastSegmentLength = 0;
101 > let lastSlash = -1;
102 > let dots = 0;
103 > let code = 0;
104 > for (let i = 0; i <= path.length; ++i) {
105 > if (i < path.length) {
106 > code = path.charCodeAt(i);
107 > }
108 > else if (isPathSeparator(code)) {
109 > break; path.ts
110 > }
111 > else { path.ts
112 > code = CHAR_FORWARD_SLASH;
113 > }
114 > path.ts
115 > if (isPathSeparator(code)) {
116 > if (lastSlash === i - 1 || dots === 1) {
117 > // NOOP path.ts
118 > } else if (dots === 2) { path.ts
119 if (res.length < 2 || lastSegmentLength !== 2 ||
120 res.charCodeAt(res.length - 1) !== CHAR_DOT ||
144 lastSegmentLength = 2;
145 }
146 > } else { path.ts
147 > if (res.length > 0) {
148 > res += `${separator}${path.slice(lastSlash + 1, i)}`; path.ts
149 > }
150 > else { path.ts
151 > res = path.slice(lastSlash + 1, i);
152 > }
153 > lastSegmentLength = i - lastSlash - 1;
154 > }
155 > lastSlash = i; path.ts
156 > dots = 0;
157 > } else if (code === CHAR_DOT && dots !== -1) {
158 > ++dots; path.ts
159 > } else { path.ts
160 > dots = -1;
161 > }
162 > } path.ts
163 > return res;
164 > }
165 > path.ts
166 function formatExt(ext: string): string {
167 return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : '';
168 }
169 > path.ts
170 function _format(sep: string, pathObject: ParsedPath) {
171 validateObject(pathObject, 'pathObject');
178 return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`;
179 }
180 > path.ts
181 > export interface ParsedPath {
182 > root: string;
183 > dir: string;
184 > base: string;
185 > ext: string;
186 > name: string;
187 > }
188 >
189 > export interface IPath {
190 > normalize(path: string): string;
191 > isAbsolute(path: string): boolean;
192 > join(...paths: string[]): string;
193 > resolve(...pathSegments: string[]): string;
194 > relative(from: string, to: string): string;
195 > dirname(path: string): string;
196 > basename(path: string, suffix?: string): string;
197 > extname(path: string): string;
198 > format(pathObject: ParsedPath): string;
199 > parse(path: string): ParsedPath;
200 > toNamespacedPath(path: string): string;
201 > sep: '\\' | '/';
202 > delimiter: string;
203 > win32: IPath | null;
204 > posix: IPath | null;
205 > }
206 >
207 > export const win32: IPath = {
208 > // path.resolve([from ...], to)
209 > resolve(...pathSegments: string[]): string {
210 let resolvedDevice = '';
211 let resolvedTail = '';
343 `${resolvedDevice}${resolvedTail}` || '.';
344 },
345 > path.ts
346 > normalize(path: string): string {
347 validateString(path, 'path');
348 const len = path.length;
450 return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
451 },
452 > path.ts
453 > isAbsolute(path: string): boolean {
454 validateString(path, 'path');
455 const len = path.length;
466 isPathSeparator(path.charCodeAt(2)));
467 },
468 > path.ts
469 > join(...paths: string[]): string {
470 if (paths.length === 0) {
471 return '.';
536 return win32.normalize(joined);
537 },
538 > path.ts
539 >
540 > // It will solve the relative path from `from` to `to`, for instance:
541 > // from = 'C:\\orandea\\test\\aaa'
542 > // to = 'C:\\orandea\\impl\\bbb'
543 > // The output of the function should be: '..\\..\\impl\\bbb'
544 > relative(from: string, to: string): string {
545 validateString(from, 'from');
546 validateString(to, 'to');
699 return toOrig.slice(toStart, toEnd);
700 },
701 > path.ts
702 > toNamespacedPath(path: string): string {
703 // Note: this will *probably* throw somewhere.
704 if (typeof path !== 'string' || path.length === 0) {
730 return resolvedPath;
731 },
732 > path.ts
733 > dirname(path: string): string {
734 validateString(path, 'path');
735 const len = path.length;
818 return path.slice(0, end);
819 },
820 > path.ts
821 > basename(path: string, suffix?: string): string {
822 if (suffix !== undefined) {
823 validateString(suffix, 'suffix');
906 return path.slice(start, end);
907 },
908 > path.ts
909 > extname(path: string): string {
910 validateString(path, 'path');
911 let start = 0;
972 return path.slice(startDot, end);
973 },
974 > path.ts
975 > format: _format.bind(null, '\\'),
976 >
977 > parse(path) {
978 validateString(path, 'path');
979
1126 return ret;
1127 },
1128 > path.ts
1129 > sep: '\\',
1130 > delimiter: ';',
1131 > win32: null,
1132 > posix: null
1133 > };
1134 >
1135 > const posixCwd = (() => {
1136 > if (platformIsWin32) {
1137 // Converts Windows' backslash path separators to POSIX forward slashes
1138 // and truncates any drive indicator
1143 };
1144 }
1145 > path.ts
1146 > // We're already on POSIX, no need for any transformations
1147 > return () => process.cwd();
1148 > })();
1149 >
1150 > export const posix: IPath = {
1151 > // path.resolve([from ...], to)
1152 > resolve(...pathSegments: string[]): string {
1153 > let resolvedPath = ''; path.ts
1154 > let resolvedAbsolute = false;
1155 >
1156 > for (let i = pathSegments.length - 1; i >= 0 && !resolvedAbsolute; i--) {
1157 > const path = pathSegments[i];
1158 > validateString(path, `paths[${i}]`);
1159 >
1160 > // Skip empty entries
1161 > if (path.length === 0) {
1162 continue;
1163 }
1164 > path.ts
1165 > resolvedPath = `${path}/${resolvedPath}`;
1166 > resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
1167 > }
1168 >
1169 > if (!resolvedAbsolute) {
1170 const cwd = posixCwd();
1171 resolvedPath = `${cwd}/${resolvedPath}`;
1173 cwd.charCodeAt(0) === CHAR_FORWARD_SLASH;
1174 }
1175 > path.ts
1176 > // At this point the path should be resolved to a full absolute path, but
1177 > // handle relative paths to be safe (might happen when process.cwd() fails)
1178 >
1179 > // Normalize the path
1180 > resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/',
1181 > isPosixPathSeparator);
1182 >
1183 > if (resolvedAbsolute) {
1184 > return `/${resolvedPath}`;
1185 > }
1186 > return resolvedPath.length > 0 ? resolvedPath : '.';
1187 > },
1188 > path.ts
1189 > normalize(path: string): string {
1190 > validateString(path, 'path'); path.ts
1191 >
1192 > if (path.length === 0) {
1193 return '.';
1194 }
1195 > path.ts
1196 > const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
1197 > const trailingSeparator =
1198 > path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
1199 >
1200 > // Normalize the path
1201 > path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator);
1202 >
1203 > if (path.length === 0) {
1204 if (isAbsolute) {
1205 return '/';
1207 return trailingSeparator ? './' : '.';
1208 }
1209 > if (trailingSeparator) { path.ts
1210 path += '/';
1211 }
1212 > path.ts
1213 > return isAbsolute ? `/${path}` : path; path.ts
1214 > },
1215 > path.ts
1216 > isAbsolute(path: string): boolean {
1217 validateString(path, 'path');
1218 return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
1219 },
1220 > path.ts
1221 > join(...paths: string[]): string {
1222 > if (paths.length === 0) { path.ts
1223 return '.';
1224 }
1225 > path.ts
1226 > const path = [];
1227 > for (let i = 0; i < paths.length; ++i) {
1228 > const arg = paths[i];
1229 > validateString(arg, 'path');
1230 > if (arg.length > 0) {
1231 > path.push(arg);
1232 > }
1233 > }
1234 >
1235 > if (path.length === 0) {
1236 return '.';
1237 }
1238 > path.ts
1239 > return posix.normalize(path.join('/'));
1240 > },
1241 > path.ts
1242 > relative(from: string, to: string): string {
1243 > validateString(from, 'from'); path.ts
1244 > validateString(to, 'to');
1245 >
1246 > if (from === to) {
1247 return '';
1248 }
1249 > path.ts
1250 > // Trim leading forward slashes.
1251 > from = posix.resolve(from);
1252 > to = posix.resolve(to);
1253 >
1254 > if (from === to) {
1255 return '';
1256 }
1257 > path.ts
1258 > const fromStart = 1;
1259 > const fromEnd = from.length;
1260 > const fromLen = fromEnd - fromStart;
1261 > const toStart = 1;
1262 > const toLen = to.length - toStart;
1263 >
1264 > // Compare paths to find the longest common path from root
1265 > const length = (fromLen < toLen ? fromLen : toLen); path.ts
1266 > let lastCommonSep = -1;
1267 > let i = 0;
1268 > for (; i < length; i++) {
1269 > const fromCode = from.charCodeAt(fromStart + i); path.ts
1270 > if (fromCode !== to.charCodeAt(toStart + i)) {
1271 break;
1272 > } else if (fromCode === CHAR_FORWARD_SLASH) { path.ts
1273 > lastCommonSep = i; path.ts
1274 > }
1275 > } path.ts
1276 > if (i === length) { path.ts
1277 > if (toLen > length) { path.ts
1278 > if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
1279 > // We get here if `from` is the exact base path for `to`. path.ts
1280 > // For example: from='/foo/bar'; to='/foo/bar/baz'
1281 > return to.slice(toStart + i + 1);
1282 > }
1283 if (i === 0) {
1284 // We get here if `from` is the root
1286 return to.slice(toStart + i);
1287 }
1288 > } else if (fromLen > length) { path.ts
1289 if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
1290 // We get here if `to` is the exact base path for `from`.
1297 }
1298 }
1299 > } path.ts
1300
1301 let out = '';
1311 // the common path parts.
1312 return `${out}${to.slice(toStart + lastCommonSep)}`;
1313 > }, path.ts
1314 > path.ts
1315 > toNamespacedPath(path: string): string {
1316 // Non-op on posix systems
1317 return path;
1318 },
1319 > path.ts
1320 > dirname(path: string): string {
1321 > validateString(path, 'path'); path.ts
1322 > if (path.length === 0) {
1323 return '.';
1324 }
1325 > const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; path.ts
1326 > let end = -1;
1327 > let matchedSlash = true;
1328 > for (let i = path.length - 1; i >= 1; --i) {
1329 > if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
1330 > if (!matchedSlash) { path.ts
1331 > end = i;
1332 > break;
1333 > }
1334 > } else { path.ts
1335 > // We saw the first non-path separator
1336 > matchedSlash = false;
1337 > }
1338 > }
1339 >
1340 > if (end === -1) {
1341 > return hasRoot ? '/' : '.'; path.ts
1342 > }
1343 > if (hasRoot && end === 1) { path.ts
1344 return '//';
1345 }
1346 > return path.slice(0, end); path.ts
1347 > }, path.ts
1348 > path.ts
1349 > basename(path: string, suffix?: string): string {
1350 > if (suffix !== undefined) { path.ts
1351 validateString(suffix, 'suffix');
1352 }
1353 > validateString(path, 'path'); path.ts
1354 >
1355 > let start = 0;
1356 > let end = -1;
1357 > let matchedSlash = true;
1358 > let i;
1359 >
1360 > if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
1361 if (suffix === path) {
1362 return '';
1405 return path.slice(start, end);
1406 }
1407 > for (i = path.length - 1; i >= 0; --i) { path.ts
1408 > if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { path.ts
1409 > // If we reached a path separator that was not part of a set of path path.ts
1410 > // separators at the end of the string, stop now
1411 > if (!matchedSlash) {
1412 > start = i + 1;
1413 > break;
1414 > }
1415 > } else if (end === -1) { path.ts
1416 > // We saw the first non-path separator, mark this as the end of our
1417 > // path component
1418 > matchedSlash = false;
1419 > end = i + 1;
1420 > }
1421 > }
1422 > path.ts
1423 > if (end === -1) {
1424 return '';
1425 }
1426 > return path.slice(start, end); path.ts
1427 > }, path.ts
1428 > path.ts
1429 > extname(path: string): string {
1430 > validateString(path, 'path'); path.ts
1431 > let startDot = -1;
1432 > let startPart = 0;
1433 > let end = -1;
1434 > let matchedSlash = true;
1435 > // Track the state of characters (if any) we see before our first dot and
1436 > // after any path separator we find
1437 > let preDotState = 0;
1438 > for (let i = path.length - 1; i >= 0; --i) {
1439 > const char = path[i];
1440 > if (char === '/') {
1441 > // If we reached a path separator that was not part of a set of path path.ts
1442 > // separators at the end of the string, stop now
1443 > if (!matchedSlash) {
1444 > startPart = i + 1;
1445 > break;
1446 > }
1447 continue;
1448 }
1449 > if (end === -1) { path.ts
1450 > // We saw the first non-path separator, mark this as the end of our
1451 > // extension
1452 > matchedSlash = false;
1453 > end = i + 1;
1454 > }
1455 > if (char === '.') {
1456 > // If this is our first dot, mark it as the start of our extension path.ts
1457 > if (startDot === -1) {
1458 > startDot = i;
1459 > }
1460 else if (preDotState !== 1) {
1461 preDotState = 1;
1462 }
1463 > } else if (startDot !== -1) { path.ts
1464 > // We saw a non-dot and non-path separator before our dot, so we should path.ts
1465 > // have a good chance at having a non-empty extension
1466 > preDotState = -1;
1467 > }
1468 > } path.ts
1469 >
1470 > if (startDot === -1 ||
1471 > end === -1 || path.ts
1472 > // We saw a non-dot character immediately before the dot
1473 > preDotState === 0 ||
1474 > // The (right-most) trimmed path component is exactly '..'
1475 > (preDotState === 1 &&
1476 startDot === end - 1 &&
1477 > startDot === startPart + 1)) { path.ts
1478 return '';
1479 }
1480 > return path.slice(startDot, end); path.ts
1481 > }, path.ts
1482 > path.ts
1483 > format: _format.bind(null, '/'),
1484 >
1485 > parse(path: string): ParsedPath {
1486 validateString(path, 'path');
1487
1565 return ret;
1566 },
1567 > path.ts
1568 > sep: '/',
1569 > delimiter: ':',
1570 > win32: null,
1571 > posix: null
1572 > };
1573 >
1574 > posix.win32 = win32.win32 = win32;
1575 > posix.posix = win32.posix = posix;
1576 >
1577 > export const normalize = (platformIsWin32 ? win32.normalize : posix.normalize);
1578 > export const isAbsolute = (platformIsWin32 ? win32.isAbsolute : posix.isAbsolute);
1579 > export const join = (platformIsWin32 ? win32.join : posix.join);
1580 > export const resolve = (platformIsWin32 ? win32.resolve : posix.resolve);
1581 > export const relative = (platformIsWin32 ? win32.relative : posix.relative);
1582 > export const dirname = (platformIsWin32 ? win32.dirname : posix.dirname);
1583 > export const basename = (platformIsWin32 ? win32.basename : posix.basename);
1584 > export const extname = (platformIsWin32 ? win32.extname : posix.extname);
1585 > export const format = (platformIsWin32 ? win32.format : posix.format);
1586 > export const parse = (platformIsWin32 ? win32.parse : posix.parse);
1587 > export const toNamespacedPath = (platformIsWin32 ? win32.toNamespacedPath : posix.toNamespacedPath);
1588 > export const sep = (platformIsWin32 ? win32.sep : posix.sep);
1589 > export const delimiter = (platformIsWin32 ? win32.delimiter : posix.delimiter);
src/vs/base/common/ternarySearchTree.ts 367 covered LOC · 117 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- ternarySearchTree.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { shuffle } from './arrays.js';
7 > import { assert } from './assert.js';
8 > import { CharCode } from './charCode.js';
9 > import { compare, compareIgnoreCase, compareSubstring, compareSubstringIgnoreCase } from './strings.js';
10 > import { URI } from './uri.js';
11 >
12 > export interface IKeyIterator<K> {
13 > reset(key: K): this;
14 > next(): this;
15 >
16 > hasNext(): boolean;
17 > cmp(a: string): number;
18 > value(): string;
19 > }
20 >
21 > export class StringIterator implements IKeyIterator<string> {
22
23 private _value: string = '';
24 private _pos: number = 0;
26 > reset(key: string): this {
27 this._value = key;
28 this._pos = 0;
29 return this;
30 }
32 > next(): this {
33 this._pos += 1;
34 return this;
35 }
37 > hasNext(): boolean {
38 return this._pos < this._value.length - 1;
39 }
41 > cmp(a: string): number {
42 const aCode = a.charCodeAt(0);
43 const thisCode = this._value.charCodeAt(this._pos);
44 return aCode - thisCode;
45 }
47 > value(): string {
48 return this._value[this._pos];
49 }
51 >
52 > export class ConfigKeysIterator implements IKeyIterator<string> {
53 >
54 > private _value!: string;
55 > private _from!: number;
56 > private _to!: number;
57 >
58 > constructor(
59 private readonly _caseSensitive: boolean = true
60 ) { }
62 > reset(key: string): this {
63 this._value = key;
64 this._from = 0;
66 return this.next();
67 }
69 > hasNext(): boolean {
70 return this._to < this._value.length;
71 }
73 > next(): this {
74 // this._data = key.split(/[\\/]/).filter(s => !!s);
75 this._from = this._to;
89 return this;
90 }
92 > cmp(a: string): number {
93 return this._caseSensitive
94 ? compareSubstring(a, this._value, 0, a.length, this._from, this._to)
95 : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
96 }
98 > value(): string {
99 return this._value.substring(this._from, this._to);
100 }
102 >
103 > export class PathIterator implements IKeyIterator<string> {
104 >
105 > private _value!: string;
106 > private _valueLen!: number;
107 > private _from!: number;
108 > private _to!: number;
109 >
110 > constructor(
111 > private readonly _splitOnBackslash: boolean = true, ternarySearchTree.ts
112 > private readonly _caseSensitive: boolean = true
113 > ) { }
115 > reset(key: string): this {
116 > this._from = 0; ternarySearchTree.ts
117 > this._to = 0;
118 > this._value = key;
119 > this._valueLen = key.length;
120 > for (let pos = key.length - 1; pos >= 0; pos--, this._valueLen--) {
121 > const ch = this._value.charCodeAt(pos);
122 > if (!(ch === CharCode.Slash || this._splitOnBackslash && ch === CharCode.Backslash)) {
123 > break;
124 > }
125 > }
126 >
127 > return this.next();
128 > }
130 > hasNext(): boolean {
131 > return this._to < this._valueLen; ternarySearchTree.ts
132 > }
134 > next(): this {
135 > // this._data = key.split(/[\\/]/).filter(s => !!s); ternarySearchTree.ts
136 > this._from = this._to;
137 > let justSeps = true;
138 > for (; this._to < this._valueLen; this._to++) {
139 > const ch = this._value.charCodeAt(this._to);
140 > if (ch === CharCode.Slash || this._splitOnBackslash && ch === CharCode.Backslash) {
141 > if (justSeps) { ternarySearchTree.ts
142 > this._from++;
143 > } else {
144 > break; ternarySearchTree.ts
145 > }
146 > } else { ternarySearchTree.ts
147 > justSeps = false;
148 > }
149 > }
150 > return this;
151 > }
153 > cmp(a: string): number {
154 > return this._caseSensitive ternarySearchTree.ts
155 > ? compareSubstring(a, this._value, 0, a.length, this._from, this._to) ternarySearchTree.ts
156 : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
159 > value(): string {
160 > return this._value.substring(this._from, this._to); ternarySearchTree.ts
161 > }
163 >
164 > const enum UriIteratorState {
165 > Scheme = 1, Authority = 2, Path = 3, Query = 4, Fragment = 5
166 > }
167 >
168 > export class UriIterator implements IKeyIterator<URI> {
169 >
170 > private _pathIterator!: PathIterator;
171 > private _value!: URI;
172 > private _states: UriIteratorState[] = [];
173 > private _stateIdx: number = 0;
174 >
175 > constructor(
176 > private readonly _ignorePathCasing: (uri: URI) => boolean, ternarySearchTree.ts
177 > private readonly _ignoreQueryAndFragment: (uri: URI) => boolean) { }
179 > reset(key: URI): this {
180 > this._value = key; ternarySearchTree.ts
181 > this._states = [];
182 > if (this._value.scheme) {
183 > this._states.push(UriIteratorState.Scheme);
184 > }
185 > if (this._value.authority) {
186 this._states.push(UriIteratorState.Authority);
187 }
188 > if (this._value.path) { ternarySearchTree.ts
189 > this._pathIterator = new PathIterator(false, !this._ignorePathCasing(key));
190 > this._pathIterator.reset(key.path);
191 > if (this._pathIterator.value()) {
192 > this._states.push(UriIteratorState.Path);
193 > }
194 > }
195 > if (!this._ignoreQueryAndFragment(key)) {
196 > if (this._value.query) { ternarySearchTree.ts
197 this._states.push(UriIteratorState.Query);
198 }
199 > if (this._value.fragment) { ternarySearchTree.ts
200 this._states.push(UriIteratorState.Fragment);
201 }
203 > this._stateIdx = 0; ternarySearchTree.ts
204 > return this;
205 > }
207 > next(): this {
208 > if (this._states[this._stateIdx] === UriIteratorState.Path && this._pathIterator.hasNext()) { ternarySearchTree.ts
209 > this._pathIterator.next(); ternarySearchTree.ts
210 > } else { ternarySearchTree.ts
211 > this._stateIdx += 1;
212 > }
213 > return this;
214 > }
216 > hasNext(): boolean {
217 > return (this._states[this._stateIdx] === UriIteratorState.Path && this._pathIterator.hasNext()) ternarySearchTree.ts
218 > || this._stateIdx < this._states.length - 1;
219 > }
221 > cmp(a: string): number {
222 > if (this._states[this._stateIdx] === UriIteratorState.Scheme) { ternarySearchTree.ts
223 > return compareIgnoreCase(a, this._value.scheme);
224 > } else if (this._states[this._stateIdx] === UriIteratorState.Authority) {
225 return compareIgnoreCase(a, this._value.authority);
226 > } else if (this._states[this._stateIdx] === UriIteratorState.Path) { ternarySearchTree.ts
227 > return this._pathIterator.cmp(a); ternarySearchTree.ts
228 > } else if (this._states[this._stateIdx] === UriIteratorState.Query) { ternarySearchTree.ts
229 return compare(a, this._value.query);
230 } else if (this._states[this._stateIdx] === UriIteratorState.Fragment) {
232 }
233 throw new Error();
236 > value(): string {
237 > if (this._states[this._stateIdx] === UriIteratorState.Scheme) { ternarySearchTree.ts
238 > return this._value.scheme;
239 > } else if (this._states[this._stateIdx] === UriIteratorState.Authority) {
240 return this._value.authority;
241 > } else if (this._states[this._stateIdx] === UriIteratorState.Path) { ternarySearchTree.ts
242 > return this._pathIterator.value();
243 > } else if (this._states[this._stateIdx] === UriIteratorState.Query) {
244 return this._value.query;
245 } else if (this._states[this._stateIdx] === UriIteratorState.Fragment) {
247 }
248 throw new Error();
251 >
252 > abstract class Undef {
253 >
254 > static readonly Val: unique symbol = Symbol('undefined_placeholder');
255 >
256 > static wrap<V>(value: V | undefined): V | typeof Undef.Val {
257 > return value === undefined ? Undef.Val : value; ternarySearchTree.ts
258 > }
260 > static unwrap<V>(value: V | typeof Undef.Val): V | undefined {
261 > return value === Undef.Val ? undefined : value; ternarySearchTree.ts
262 > }
264 >
265 > class TernarySearchTreeNode<K, V> { ternarySearchTree.ts
266 > height: number = 1;
267 > segment!: string;
268 > value: V | typeof Undef.Val | undefined = undefined;
269 > key: K | undefined = undefined;
270 > left: TernarySearchTreeNode<K, V> | undefined = undefined;
271 > mid: TernarySearchTreeNode<K, V> | undefined = undefined;
272 > right: TernarySearchTreeNode<K, V> | undefined = undefined;
274 > isEmpty(): boolean {
275 return !this.left && !this.mid && !this.right && this.value === undefined;
276 }
278 > rotateLeft() {
279 const tmp = this.right!;
280 this.right = tmp.left;
284 return tmp;
285 }
287 > rotateRight() {
288 const tmp = this.left!;
289 this.left = tmp.right;
293 return tmp;
294 }
296 > updateHeight() {
297 > this.height = 1 + Math.max(this.heightLeft, this.heightRight); ternarySearchTree.ts
298 > }
300 > balanceFactor() {
301 > return this.heightRight - this.heightLeft; ternarySearchTree.ts
302 > }
304 > get heightLeft() {
305 > return this.left?.height ?? 0; ternarySearchTree.ts
306 > }
308 > get heightRight() {
309 > return this.right?.height ?? 0; ternarySearchTree.ts
310 > }
312 >
313 > const enum Dir {
314 > Left = -1,
315 > Mid = 0,
316 > Right = 1
317 > }
318 >
319 > export class TernarySearchTree<K, V> {
320 >
321 > static forUris<E>(ignorePathCasing: (key: URI) => boolean = () => false, ignoreQueryAndFragment: (key: URI) => boolean = () => false): TernarySearchTree<URI, E> {
322 > return new TernarySearchTree<URI, E>(new UriIterator(ignorePathCasing, ignoreQueryAndFragment)); ternarySearchTree.ts
323 > }
325 > static forPaths<E>(ignorePathCasing = false): TernarySearchTree<string, E> {
326 return new TernarySearchTree<string, E>(new PathIterator(undefined, !ignorePathCasing));
327 }
329 > static forStrings<E>(): TernarySearchTree<string, E> {
330 return new TernarySearchTree<string, E>(new StringIterator());
331 }
333 > static forConfigKeys<E>(): TernarySearchTree<string, E> {
334 return new TernarySearchTree<string, E>(new ConfigKeysIterator());
335 }
337 > private _iter: IKeyIterator<K>;
338 > private _root: TernarySearchTreeNode<K, V> | undefined;
339 >
340 > constructor(segments: IKeyIterator<K>) {
341 > this._iter = segments; ternarySearchTree.ts
342 > }
344 > clear(): void {
345 this._root = undefined;
346 }
348 > /**
349 > * Fill the tree with the same value of the given keys
350 > */
351 > fill(element: V, keys: readonly K[]): void;
352 > /**
353 > * Fill the tree with given [key,value]-tuples
354 > */
355 > fill(values: readonly [K, V][]): void;
356 > fill(values: readonly [K, V][] | V, keys?: readonly K[]): void {
357 if (keys) {
358 const arr = keys.slice(0);
369 }
370 }
372 > set(key: K, element: V): V | undefined {
373 > const iter = this._iter.reset(key); ternarySearchTree.ts
374 > let node: TernarySearchTreeNode<K, V>;
375 >
376 > if (!this._root) {
377 > this._root = new TernarySearchTreeNode<K, V>();
378 > this._root.segment = iter.value();
379 > }
380 > const stack: [Dir, TernarySearchTreeNode<K, V>][] = [];
381 >
382 > // find insert_node
383 > node = this._root;
384 > while (true) {
385 > const val = iter.cmp(node.segment);
386 > if (val > 0) {
387 // left
388 if (!node.left) {
393 node = node.left;
394
395 > } else if (val < 0) { ternarySearchTree.ts
396 // right
397 if (!node.right) {
402 node = node.right;
403
404 > } else if (iter.hasNext()) { ternarySearchTree.ts
405 > // mid ternarySearchTree.ts
406 > iter.next();
407 > if (!node.mid) {
408 > node.mid = new TernarySearchTreeNode<K, V>();
409 > node.mid.segment = iter.value();
410 > }
411 > stack.push([Dir.Mid, node]);
412 > node = node.mid;
413 > } else { ternarySearchTree.ts
414 > break;
415 > }
416 > }
417 >
418 > // set value
419 > const oldElement = Undef.unwrap(node.value);
420 > node.value = Undef.wrap(element);
421 > node.key = key;
422 >
423 > // balance
424 > for (let i = stack.length - 1; i >= 0; i--) {
425 > const node = stack[i][1]; ternarySearchTree.ts
426 >
427 > node.updateHeight();
428 > const bf = node.balanceFactor();
429 >
430 > if (bf < -1 || bf > 1) {
431 // needs rotate
432 const d1 = stack[i][0];
472 }
473 }
476 > return oldElement;
477 > }
479 > get(key: K): V | undefined {
480 > return Undef.unwrap(this._getNode(key)?.value); ternarySearchTree.ts
481 > }
483 > private _getNode(key: K) {
484 > const iter = this._iter.reset(key); ternarySearchTree.ts
485 > let node = this._root;
486 > while (node) {
487 > const val = iter.cmp(node.segment); ternarySearchTree.ts
488 > if (val > 0) {
489 // left
490 node = node.left;
491 > } else if (val < 0) { ternarySearchTree.ts
492 // right
493 node = node.right;
494 > } else if (iter.hasNext()) { ternarySearchTree.ts
495 > // mid ternarySearchTree.ts
496 > iter.next();
497 > node = node.mid;
498 > } else { ternarySearchTree.ts
499 > break; ternarySearchTree.ts
500 > }
502 > return node; ternarySearchTree.ts
503 > }
505 > has(key: K): boolean {
506 const node = this._getNode(key);
507 return !(node?.value === undefined && node?.mid === undefined);
508 }
510 > delete(key: K): void {
511 return this._delete(key, false);
512 }
514 > deleteSuperstr(key: K): void {
515 return this._delete(key, true);
516 }
518 > private _delete(key: K, superStr: boolean): void {
519 const iter = this._iter.reset(key);
520 const stack: [Dir, TernarySearchTreeNode<K, V>][] = [];
620 this._root = this._balanceByStack(stack) ?? this._root;
621 }
623 > private _min(node: TernarySearchTreeNode<K, V>, stack: [Dir, TernarySearchTreeNode<K, V>][]): TernarySearchTreeNode<K, V> {
624 while (node.left) {
625 stack.push([Dir.Left, node]);
628 return node;
629 }
631 > private _balanceByStack(stack: [Dir, TernarySearchTreeNode<K, V>][]) {
632
633 for (let i = stack.length - 1; i >= 0; i--) {
679 return undefined;
680 }
682 > findSubstr(key: K): V | undefined {
683 const iter = this._iter.reset(key);
684 let node = this._root;
703 return node && Undef.unwrap(node.value) || candidate;
704 }
706 > findSuperstr(key: K): IterableIterator<[K, V]> | undefined {
707 return this._findSuperstrOrElement(key, false);
708 }
710 > private _findSuperstrOrElement(key: K, allowValue: true): IterableIterator<[K, V]> | V | undefined;
711 > private _findSuperstrOrElement(key: K, allowValue: false): IterableIterator<[K, V]> | undefined;
712 > private _findSuperstrOrElement(key: K, allowValue: boolean): IterableIterator<[K, V]> | V | undefined {
713 const iter = this._iter.reset(key);
714 let node = this._root;
740 return undefined;
741 }
743 > hasElementOrSubtree(key: K): boolean {
744 return this._findSuperstrOrElement(key, true) !== undefined;
745 }
747 > forEach(callback: (value: V, index: K) => unknown): void {
748 for (const [key, value] of this) {
749 callback(value, key);
750 }
751 }
753 > *[Symbol.iterator](): IterableIterator<[K, V]> {
754 yield* this._entries(this._root);
755 }
757 > private _entries(node: TernarySearchTreeNode<K, V> | undefined): IterableIterator<[K, V]> {
758 const result: [K, V][] = [];
759 this._dfsEntries(node, result);
760 return result[Symbol.iterator]();
761 }
763 > private _dfsEntries(node: TernarySearchTreeNode<K, V> | undefined, bucket: [K, V][]) {
764 // DFS
765 if (!node) {
779 }
780 }
782 > // for debug/testing
783 > _isBalanced(): boolean {
784 const nodeIsBalanced = (node: TernarySearchTreeNode<unknown, unknown> | undefined): boolean => {
785 if (!node) {
src/vs/base/common/map.ts 325 covered LOC · 103 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- map.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { URI } from './uri.js';
7 >
8 > export function getOrSet<K, V>(map: Map<K, V>, key: K, value: V): V {
9 let result = map.get(key);
10 if (result === undefined) {
15 return result;
16 }
17 > map.ts
18 > export function mapToString<K, V>(map: Map<K, V>): string {
19 const entries: string[] = [];
20 map.forEach((value, key) => {
24 return `Map(${map.size}) {${entries.join(', ')}}`;
25 }
26 > map.ts
27 > export function setToString<K>(set: Set<K>): string {
28 const entries: K[] = [];
29 set.forEach(value => {
33 return `Set(${set.size}) {${entries.join(', ')}}`;
34 }
35 > map.ts
36 > interface ResourceMapKeyFn {
37 > (resource: URI): string;
38 > }
39 >
40 > class ResourceMapEntry<T> {
41 > constructor(readonly uri: URI, readonly value: T) { }
42 > }
43 >
44 > function isEntries<T>(arg: ResourceMap<T> | ResourceMapKeyFn | readonly (readonly [URI, T])[] | undefined): arg is readonly (readonly [URI, T])[] { map.ts
45 > return Array.isArray(arg);
46 > }
47 > map.ts
48 > export class ResourceMap<T> implements Map<URI, T> {
49 >
50 > private static readonly defaultToKey = (resource: URI) => resource.toString();
51 >
52 > readonly [Symbol.toStringTag] = 'ResourceMap';
53 >
54 > private readonly map: Map<string, ResourceMapEntry<T>>;
55 > private readonly toKey: ResourceMapKeyFn;
56 >
57 > /**
58 > *
59 > * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util
60 > */
61 > constructor(toKey?: ResourceMapKeyFn);
62 >
63 > /**
64 > *
65 > * @param other Another resource which this maps is created from
66 > * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util
67 > */
68 > constructor(other?: ResourceMap<T>, toKey?: ResourceMapKeyFn);
69 >
70 > /**
71 > *
72 > * @param other Another resource which this maps is created from
73 > * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util
74 > */
75 > constructor(entries?: readonly (readonly [URI, T])[], toKey?: ResourceMapKeyFn);
76 >
77 > constructor(arg?: ResourceMap<T> | ResourceMapKeyFn | readonly (readonly [URI, T])[], toKey?: ResourceMapKeyFn) {
78 > if (arg instanceof ResourceMap) { map.ts
79 this.map = new Map(arg.map);
80 this.toKey = toKey ?? ResourceMap.defaultToKey;
81 > } else if (isEntries(arg)) { map.ts
82 this.map = new Map();
83 this.toKey = toKey ?? ResourceMap.defaultToKey;
86 this.set(resource, value);
87 }
88 > } else { map.ts
89 > this.map = new Map();
90 > this.toKey = arg ?? ResourceMap.defaultToKey;
91 > }
92 > }
93 > map.ts
94 > set(resource: URI, value: T): this {
95 this.map.set(this.toKey(resource), new ResourceMapEntry(resource, value));
96 return this;
97 }
98 > map.ts
99 > get(resource: URI): T | undefined {
100 return this.map.get(this.toKey(resource))?.value;
101 }
102 > map.ts
103 > has(resource: URI): boolean {
104 return this.map.has(this.toKey(resource));
105 }
106 > map.ts
107 > get size(): number {
108 return this.map.size;
109 }
110 > map.ts
111 > clear(): void {
112 this.map.clear();
113 }
114 > map.ts
115 > delete(resource: URI): boolean {
116 return this.map.delete(this.toKey(resource));
117 }
118 > map.ts
119 > forEach(clb: (value: T, key: URI, map: Map<URI, T>) => void, thisArg?: object): void {
120 if (typeof thisArg !== 'undefined') {
121 clb = clb.bind(thisArg);
125 }
126 }
127 > map.ts
128 > *values(): MapIterator<T> {
129 for (const entry of this.map.values()) {
130 yield entry.value;
131 }
132 }
133 > map.ts
134 > *keys(): MapIterator<URI> {
135 > for (const entry of this.map.values()) { map.ts
136 yield entry.uri;
137 }
138 > } map.ts
139 > map.ts
140 > *entries(): MapIterator<[URI, T]> {
141 for (const entry of this.map.values()) {
142 yield [entry.uri, entry.value];
143 }
144 }
145 > map.ts
146 > *[Symbol.iterator](): MapIterator<[URI, T]> {
147 for (const [, entry] of this.map) {
148 yield [entry.uri, entry.value];
149 }
150 }
151 > } map.ts
152 >
153 > export class ResourceSet implements Set<URI> {
154 >
155 > readonly [Symbol.toStringTag]: string = 'ResourceSet';
156 >
157 > private readonly _map: ResourceMap<URI>;
158 >
159 > constructor(toKey?: ResourceMapKeyFn);
160 > constructor(entries: readonly URI[], toKey?: ResourceMapKeyFn);
161 > constructor(entriesOrKey?: readonly URI[] | ResourceMapKeyFn, toKey?: ResourceMapKeyFn) {
162 if (!entriesOrKey || typeof entriesOrKey === 'function') {
163 this._map = new ResourceMap(entriesOrKey);
167 }
168 }
169 > map.ts
170 >
171 > get size(): number {
172 return this._map.size;
173 }
174 > map.ts
175 > add(value: URI): this {
176 this._map.set(value, value);
177 return this;
178 }
179 > map.ts
180 > clear(): void {
181 this._map.clear();
182 }
183 > map.ts
184 > delete(value: URI): boolean {
185 return this._map.delete(value);
186 }
187 > map.ts
188 > forEach(callbackfn: (value: URI, value2: URI, set: Set<URI>) => void, thisArg?: unknown): void {
189 this._map.forEach((_value, key) => callbackfn.call(thisArg, key, key, this));
190 }
191 > map.ts
192 > has(value: URI): boolean {
193 return this._map.has(value);
194 }
195 > map.ts
196 > entries(): SetIterator<[URI, URI]> {
197 return this._map.entries() as unknown as SetIterator<[URI, URI]>;
198 }
199 > map.ts
200 > keys(): SetIterator<URI> {
201 return this._map.keys() as unknown as SetIterator<URI>;
202 }
203 > map.ts
204 > values(): SetIterator<URI> {
205 return this._map.keys() as unknown as SetIterator<URI>;
206 }
207 > map.ts
208 > [Symbol.iterator](): SetIterator<URI> {
209 return this.keys();
210 }
211 > } map.ts
212 >
213 >
214 > interface Item<K, V> {
215 > previous: Item<K, V> | undefined;
216 > next: Item<K, V> | undefined;
217 > key: K;
218 > value: V;
219 > }
220 >
221 > export const enum Touch {
222 > None = 0,
223 > AsOld = 1,
224 > AsNew = 2
225 > }
226 >
227 > export class LinkedMap<K, V> implements Map<K, V> {
228 >
229 > readonly [Symbol.toStringTag] = 'LinkedMap';
230 >
231 > private _map: Map<K, Item<K, V>>;
232 > private _head: Item<K, V> | undefined;
233 > private _tail: Item<K, V> | undefined;
234 > private _size: number;
235 >
236 > private _state: number;
237 >
238 > constructor() {
239 this._map = new Map<K, Item<K, V>>();
240 this._head = undefined;
243 this._state = 0;
244 }
245 > map.ts
246 > clear(): void {
247 this._map.clear();
248 this._head = undefined;
251 this._state++;
252 }
253 > map.ts
254 > isEmpty(): boolean {
255 return !this._head && !this._tail;
256 }
257 > map.ts
258 > get size(): number {
259 return this._size;
260 }
261 > map.ts
262 > get first(): V | undefined {
263 return this._head?.value;
264 }
265 > map.ts
266 > get last(): V | undefined {
267 return this._tail?.value;
268 }
269 > map.ts
270 > has(key: K): boolean {
271 return this._map.has(key);
272 }
273 > map.ts
274 > get(key: K, touch: Touch = Touch.None): V | undefined {
275 const item = this._map.get(key);
276 if (!item) {
282 return item.value;
283 }
284 > map.ts
285 > set(key: K, value: V, touch: Touch = Touch.None): this {
286 let item = this._map.get(key);
287 if (item) {
311 return this;
312 }
313 > map.ts
314 > delete(key: K): boolean {
315 return !!this.remove(key);
316 }
317 > map.ts
318 > remove(key: K): V | undefined {
319 const item = this._map.get(key);
320 if (!item) {
326 return item.value;
327 }
328 > map.ts
329 > shift(): V | undefined {
330 if (!this._head && !this._tail) {
331 return undefined;
340 return item.value;
341 }
342 > map.ts
343 > forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
344 const state = this._state;
345 let current = this._head;
356 }
357 }
358 > map.ts
359 > keys(): MapIterator<K> {
360 const map = this;
361 const state = this._state;
381 return iterator;
382 }
383 > map.ts
384 > values(): MapIterator<V> {
385 const map = this;
386 const state = this._state;
406 return iterator;
407 }
408 > map.ts
409 > entries(): MapIterator<[K, V]> {
410 const map = this;
411 const state = this._state;
431 return iterator;
432 }
433 > map.ts
434 > [Symbol.iterator](): MapIterator<[K, V]> {
435 return this.entries();
436 }
437 > map.ts
438 > protected trimOld(newSize: number) {
439 if (newSize >= this.size) {
440 return;
458 this._state++;
459 }
460 > map.ts
461 > protected trimNew(newSize: number) {
462 if (newSize >= this.size) {
463 return;
481 this._state++;
482 }
483 > map.ts
484 > private addItemFirst(item: Item<K, V>): void {
485 // First time Insert
486 if (!this._head && !this._tail) {
495 this._state++;
496 }
497 > map.ts
498 > private addItemLast(item: Item<K, V>): void {
499 // First time Insert
500 if (!this._head && !this._tail) {
509 this._state++;
510 }
511 > map.ts
512 > private removeItem(item: Item<K, V>): void {
513 if (item === this._head && item === this._tail) {
514 this._head = undefined;
546 this._state++;
547 }
548 > map.ts
549 > private touch(item: Item<K, V>, touch: Touch): void {
550 if (!this._head || !this._tail) {
551 throw new Error('Invalid list');
608 }
609 }
610 > map.ts
611 > toJSON(): [K, V][] {
612 const data: [K, V][] = [];
613
618 return data;
619 }
620 > map.ts
621 > fromJSON(data: [K, V][]): void {
622 this.clear();
623
626 }
627 }
628 > } map.ts
629 >
630 > abstract class Cache<K, V> extends LinkedMap<K, V> {
631 >
632 > protected _limit: number;
633 > protected _ratio: number;
634 >
635 > constructor(limit: number, ratio: number = 1) {
636 super();
637 this._limit = limit;
638 this._ratio = Math.min(Math.max(0, ratio), 1);
639 }
640 > map.ts
641 > get limit(): number {
642 return this._limit;
643 }
644 > map.ts
645 > set limit(limit: number) {
646 this._limit = limit;
647 this.checkTrim();
648 }
649 > map.ts
650 > get ratio(): number {
651 return this._ratio;
652 }
653 > map.ts
654 > set ratio(ratio: number) {
655 this._ratio = Math.min(Math.max(0, ratio), 1);
656 this.checkTrim();
657 }
658 > map.ts
659 > override get(key: K, touch: Touch = Touch.AsNew): V | undefined {
660 return super.get(key, touch);
661 }
662 > map.ts
663 > peek(key: K): V | undefined {
664 return super.get(key, Touch.None);
665 }
666 > map.ts
667 > override set(key: K, value: V): this {
668 super.set(key, value, Touch.AsNew);
669 return this;
670 }
671 > map.ts
672 > protected checkTrim() {
673 if (this.size > this._limit) {
674 this.trim(Math.round(this._limit * this._ratio));
675 }
676 }
677 > map.ts
678 > protected abstract trim(newSize: number): void;
679 > }
680 >
681 > export class LRUCache<K, V> extends Cache<K, V> {
682 >
683 > constructor(limit: number, ratio: number = 1) {
684 super(limit, ratio);
685 }
686 > map.ts
687 > protected override trim(newSize: number) {
688 this.trimOld(newSize);
689 }
690 > map.ts
691 > override set(key: K, value: V): this {
692 super.set(key, value);
693 this.checkTrim();
694 return this;
695 }
696 > } map.ts
697 >
698 > export class MRUCache<K, V> extends Cache<K, V> {
699 >
700 > constructor(limit: number, ratio: number = 1) {
701 super(limit, ratio);
702 }
703 > map.ts
704 > protected override trim(newSize: number) {
705 this.trimNew(newSize);
706 }
707 > map.ts
708 > override set(key: K, value: V): this {
709 if (this._limit <= this.size && !this.has(key)) {
710 this.trim(Math.round(this._limit * this._ratio) - 1);
714 return this;
715 }
716 > } map.ts
717 >
718 > export class CounterSet<T> {
719
720 private map = new Map<T, number>();
721 > map.ts
722 > add(value: T): CounterSet<T> {
723 this.map.set(value, (this.map.get(value) || 0) + 1);
724 return this;
725 }
726 > map.ts
727 > delete(value: T): boolean {
728 let counter = this.map.get(value) || 0;
729
742 return true;
743 }
744 > map.ts
745 > has(value: T): boolean {
746 return this.map.has(value);
747 }
748 > } map.ts
749 >
750 > /**
751 > * A map that allows access both by keys and values.
752 > * **NOTE**: values need to be unique.
753 > */
754 > export class BidirectionalMap<K, V> {
755 >
756 > private readonly _m1 = new Map<K, V>();
757 > private readonly _m2 = new Map<V, K>();
758 >
759 > constructor(entries?: readonly (readonly [K, V])[]) {
760 if (entries) {
761 for (const [key, value] of entries) {
764 }
765 }
766 > map.ts
767 > clear(): void {
768 this._m1.clear();
769 this._m2.clear();
770 }
771 > map.ts
772 > set(key: K, value: V): void {
773 this._m1.set(key, value);
774 this._m2.set(value, key);
775 }
776 > map.ts
777 > get(key: K): V | undefined {
778 return this._m1.get(key);
779 }
780 > map.ts
781 > getKey(value: V): K | undefined {
782 return this._m2.get(value);
783 }
784 > map.ts
785 > delete(key: K): boolean {
786 const value = this._m1.get(key);
787 if (value === undefined) {
792 return true;
793 }
794 > map.ts
795 > forEach(callbackfn: (value: V, key: K, map: BidirectionalMap<K, V>) => void, thisArg?: unknown): void {
796 this._m1.forEach((value, key) => {
797 callbackfn.call(thisArg, value, key, this);
798 });
799 }
800 > map.ts
801 > keys(): IterableIterator<K> {
802 return this._m1.keys();
803 }
804 > map.ts
805 > values(): IterableIterator<V> {
806 return this._m1.values();
807 }
808 > } map.ts
809 >
810 > export class SetMap<K, V> {
811
812 private map = new Map<K, Set<V>>();
813 > map.ts
814 > add(key: K, value: V): void {
815 let values = this.map.get(key);
816
822 values.add(value);
823 }
824 > map.ts
825 > delete(key: K, value: V): void {
826 const values = this.map.get(key);
827
836 }
837 }
838 > map.ts
839 > forEach(key: K, fn: (value: V) => void): void {
840 const values = this.map.get(key);
841
846 values.forEach(fn);
847 }
848 > map.ts
849 > get(key: K): ReadonlySet<V> {
850 const values = this.map.get(key);
851 if (!values) {
854 return values;
855 }
856 > } map.ts
857 >
858 > export function mapsStrictEqualIgnoreOrder(a: Map<unknown, unknown>, b: Map<unknown, unknown>): boolean {
859 if (a === b) {
860 return true;
879 return true;
880 }
881 > map.ts
882 > /**
883 > * A map that is addressable with an arbitrary number of keys. This is useful in high performance
884 > * scenarios where creating a composite key whenever the data is accessed is too expensive. For
885 > * example for a very hot function, constructing a string like `first-second-third` for every call
886 > * will cause a significant hit to performance.
887 > */
888 > export class NKeyMap<TValue, TKeys extends (string | boolean | number)[]> {
889 private _data: Map<any, any> = new Map();
890 > map.ts
891 > /**
892 > * Sets a value on the map. Note that unlike a standard `Map`, the first argument is the value.
893 > * This is because the spread operator is used for the keys and must be last..
894 > * @param value The value to set.
895 > * @param keys The keys for the value.
896 > */
897 > public set(value: TValue, ...keys: [...TKeys]): void {
898 let currentMap = this._data;
899 for (let i = 0; i < keys.length - 1; i++) {
907 currentMap.set(keys[keys.length - 1], value);
908 }
909 > map.ts
910 > public get(...keys: [...TKeys]): TValue | undefined {
911 let currentMap = this._data;
912 for (let i = 0; i < keys.length - 1; i++) {
919 return currentMap.get(keys[keys.length - 1]);
920 }
921 > map.ts
922 > public delete(...keys: [...TKeys]): boolean {
923 const maps: Map<any, any>[] = [this._data];
924 let currentMap = this._data;
939 return deleted;
940 }
941 > map.ts
942 > public deleteAll(...keys: Partial<TKeys>): boolean {
943 if (keys.length === 0) {
944 const hadData = this._data.size > 0;
964 return deleted;
965 }
966 > map.ts
967 > public clear(): void {
968 this._data.clear();
969 }
970 > map.ts
971 > public *getAll(...keys: Partial<TKeys>): IterableIterator<TValue> {
972 let currentMap = this._data;
973 for (const key of keys) {
980 yield* this._values(currentMap);
981 }
982 > map.ts
983 > public *values(): IterableIterator<TValue> {
984 yield* this._values(this._data);
985 }
986 > map.ts
987 > private *_values(map: Map<any, any>): IterableIterator<TValue> {
988 for (const value of map.values()) {
989 if (value instanceof Map) {
994 }
995 }
996 > map.ts
997 > /**
998 > * Get a textual representation of the map for debugging purposes.
999 > */
1000 > public toString(): string {
1001 const printMap = (map: Map<any, any>, depth: number): string => {
1002 let result = '';
1014 return printMap(this._data, 0);
1015 }
1016 > } map.ts
src/vs/platform/workspace/common/workspace.ts 322 covered LOC · 27 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- workspace.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { localize } from '../../../nls.js';
7 > import { Event } from '../../../base/common/event.js';
8 > import { basename, extname } from '../../../base/common/path.js';
9 > import { TernarySearchTree } from '../../../base/common/ternarySearchTree.js';
10 > import { extname as resourceExtname, basenameOrAuthority, joinPath, extUriBiasedIgnorePathCase } from '../../../base/common/resources.js';
11 > import { URI, UriComponents } from '../../../base/common/uri.js';
12 > import { createDecorator } from '../../instantiation/common/instantiation.js';
13 > import { IEnvironmentService } from '../../environment/common/environment.js';
14 > import { Schemas } from '../../../base/common/network.js';
15 >
16 > export const IWorkspaceContextService = createDecorator<IWorkspaceContextService>('contextService');
17 >
18 > export interface IWorkspaceContextService {
19 >
20 > readonly _serviceBrand: undefined;
21 >
22 > /**
23 > * An event which fires on workbench state changes.
24 > */
25 > readonly onDidChangeWorkbenchState: Event<WorkbenchState>;
26 >
27 > /**
28 > * An event which fires on workspace name changes.
29 > */
30 > readonly onDidChangeWorkspaceName: Event<void>;
31 >
32 > /**
33 > * An event which fires before workspace folders change.
34 > */
35 > readonly onWillChangeWorkspaceFolders: Event<IWorkspaceFoldersWillChangeEvent>;
36 >
37 > /**
38 > * An event which fires on workspace folders change.
39 > */
40 > readonly onDidChangeWorkspaceFolders: Event<IWorkspaceFoldersChangeEvent>;
41 >
42 > /**
43 > * Provides access to the complete workspace object.
44 > */
45 > getCompleteWorkspace(): Promise<IWorkspace>;
46 >
47 > /**
48 > * Provides access to the workspace object the window is running with.
49 > * Use `getCompleteWorkspace` to get complete workspace object.
50 > */
51 > getWorkspace(): IWorkspace;
52 >
53 > /**
54 > * Return the state of the workbench.
55 > *
56 > * WorkbenchState.EMPTY - if the workbench was opened with empty window or file
57 > * WorkbenchState.FOLDER - if the workbench was opened with a folder
58 > * WorkbenchState.WORKSPACE - if the workbench was opened with a workspace
59 > */
60 > getWorkbenchState(): WorkbenchState;
61 >
62 > /**
63 > * Returns the folder for the given resource from the workspace.
64 > * Can be null if there is no workspace or the resource is not inside the workspace.
65 > */
66 > getWorkspaceFolder(resource: URI): IWorkspaceFolder | null;
67 >
68 > /**
69 > * Return `true` if the current workspace has the given identifier or root URI otherwise `false`.
70 > */
71 > isCurrentWorkspace(workspaceIdOrFolder: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | URI): boolean;
72 >
73 > /**
74 > * Returns if the provided resource is inside the workspace or not.
75 > */
76 > isInsideWorkspace(resource: URI): boolean;
77 >
78 > /**
79 > * Return `true` if the current workspace has data (e.g. folders or a workspace configuration) that can be sent to the extension host, otherwise `false`.
80 > */
81 > hasWorkspaceData(): boolean;
82 > }
83 >
84 > export interface IResolvedWorkspace extends IWorkspaceIdentifier, IBaseWorkspace {
85 > readonly folders: IWorkspaceFolder[];
86 > }
87 >
88 > export interface IBaseWorkspace {
89 >
90 > /**
91 > * If present, marks the window that opens the workspace
92 > * as a remote window with the given authority.
93 > */
94 > readonly remoteAuthority?: string;
95 >
96 > /**
97 > * Transient workspaces are meant to go away after being used
98 > * once, e.g. a window reload of a transient workspace will
99 > * open an empty window.
100 > *
101 > * See: https://github.com/microsoft/vscode/issues/119695
102 > */
103 > readonly transient?: boolean;
104 > }
105 >
106 > export interface IBaseWorkspaceIdentifier {
107 >
108 > /**
109 > * Every workspace (multi-root, single folder or empty)
110 > * has a unique identifier. It is not possible to open
111 > * a workspace with the same `id` in multiple windows
112 > */
113 > readonly id: string;
114 > }
115 >
116 > /**
117 > * A single folder workspace identifier is a path to a folder + id.
118 > */
119 > export interface ISingleFolderWorkspaceIdentifier extends IBaseWorkspaceIdentifier {
120 >
121 > /**
122 > * Folder path as `URI`.
123 > */
124 > readonly uri: URI;
125 > }
126 >
127 > /**
128 > * A multi-root workspace identifier is a path to a workspace file + id.
129 > */
130 > export interface IWorkspaceIdentifier extends IBaseWorkspaceIdentifier {
131 >
132 > /**
133 > * Workspace config file path as `URI`.
134 > */
135 > configPath: URI;
136 > }
137 >
138 > export interface IEmptyWorkspaceIdentifier extends IBaseWorkspaceIdentifier { }
139 >
140 > export type IAnyWorkspaceIdentifier = IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier;
141 >
142 > export function isSingleFolderWorkspaceIdentifier(obj: unknown): obj is ISingleFolderWorkspaceIdentifier {
143 const singleFolderIdentifier = obj as ISingleFolderWorkspaceIdentifier | undefined;
144
145 return typeof singleFolderIdentifier?.id === 'string' && URI.isUri(singleFolderIdentifier.uri);
146 }
147 > workspace.ts
148 > export function isEmptyWorkspaceIdentifier(obj: unknown): obj is IEmptyWorkspaceIdentifier {
149 const emptyWorkspaceIdentifier = obj as IEmptyWorkspaceIdentifier | undefined;
150 return typeof emptyWorkspaceIdentifier?.id === 'string'
152 && !isWorkspaceIdentifier(obj);
153 }
154 > workspace.ts
155 > export const EXTENSION_DEVELOPMENT_EMPTY_WINDOW_WORKSPACE: IEmptyWorkspaceIdentifier = { id: 'ext-dev' };
156 > export const UNKNOWN_EMPTY_WINDOW_WORKSPACE: IEmptyWorkspaceIdentifier = { id: 'empty-window' };
157 >
158 > export function toWorkspaceIdentifier(workspace: IWorkspace): IAnyWorkspaceIdentifier;
159 > export function toWorkspaceIdentifier(backupPath: string | undefined, isExtensionDevelopment: boolean): IEmptyWorkspaceIdentifier;
160 > export function toWorkspaceIdentifier(arg0: IWorkspace | string | undefined, isExtensionDevelopment?: boolean): IAnyWorkspaceIdentifier {
161
162 // Empty workspace
202 };
203 }
204 > workspace.ts
205 > export function isWorkspaceIdentifier(obj: unknown): obj is IWorkspaceIdentifier {
206 const workspaceIdentifier = obj as IWorkspaceIdentifier | undefined;
207
208 return typeof workspaceIdentifier?.id === 'string' && URI.isUri(workspaceIdentifier.configPath);
209 }
210 > workspace.ts
211 > export interface ISerializedSingleFolderWorkspaceIdentifier extends IBaseWorkspaceIdentifier {
212 > readonly uri: UriComponents;
213 > }
214 >
215 > export interface ISerializedWorkspaceIdentifier extends IBaseWorkspaceIdentifier {
216 > readonly configPath: UriComponents;
217 > }
218 >
219 > export function reviveIdentifier(identifier: undefined): undefined;
220 > export function reviveIdentifier(identifier: ISerializedWorkspaceIdentifier): IWorkspaceIdentifier;
221 > export function reviveIdentifier(identifier: ISerializedSingleFolderWorkspaceIdentifier): ISingleFolderWorkspaceIdentifier;
222 > export function reviveIdentifier(identifier: IEmptyWorkspaceIdentifier): IEmptyWorkspaceIdentifier;
223 > export function reviveIdentifier(identifier: ISerializedWorkspaceIdentifier | ISerializedSingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier | undefined): IAnyWorkspaceIdentifier | undefined;
224 > export function reviveIdentifier(identifier: ISerializedWorkspaceIdentifier | ISerializedSingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier | undefined): IAnyWorkspaceIdentifier | undefined {
225
226 // Single Folder
243 return undefined;
244 }
245 > workspace.ts
246 > export const enum WorkbenchState {
247 > EMPTY = 1,
248 > FOLDER,
249 > WORKSPACE
250 > }
251 >
252 > export interface IWorkspaceFoldersWillChangeEvent {
253 >
254 > readonly changes: IWorkspaceFoldersChangeEvent;
255 > readonly fromCache: boolean;
256 >
257 > join(promise: Promise<void>): void;
258 > }
259 >
260 > export interface IWorkspaceFoldersChangeEvent {
261 > added: IWorkspaceFolder[];
262 > removed: IWorkspaceFolder[];
263 > changed: IWorkspaceFolder[];
264 > }
265 >
266 > export interface IWorkspace {
267 >
268 > /**
269 > * the unique identifier of the workspace.
270 > */
271 > readonly id: string;
272 >
273 > /**
274 > * Folders in the workspace.
275 > */
276 > readonly folders: IWorkspaceFolder[];
277 >
278 > /**
279 > * Transient workspaces are meant to go away after being used
280 > * once, e.g. a window reload of a transient workspace will
281 > * open an empty window.
282 > */
283 > readonly transient?: boolean;
284 >
285 > /**
286 > * the location of the workspace configuration
287 > */
288 > readonly configuration?: URI | null;
289 >
290 > /**
291 > * Optional display name for the workspace.
292 > */
293 > readonly name?: string;
294 >
295 > }
296 >
297 > export function isWorkspace(thing: unknown): thing is IWorkspace {
298 const candidate = thing as IWorkspace | undefined;
299
302 && Array.isArray(candidate.folders));
303 }
304 > workspace.ts
305 > export interface IWorkspaceFolderData {
306 >
307 > /**
308 > * The associated URI for this workspace folder.
309 > */
310 > readonly uri: URI;
311 >
312 > /**
313 > * The name of this workspace folder. Defaults to
314 > * the basename of its [uri-path](#Uri.path)
315 > */
316 > readonly name: string;
317 >
318 > /**
319 > * The ordinal number of this workspace folder.
320 > */
321 > readonly index: number;
322 > }
323 >
324 > export interface IWorkspaceFolder extends IWorkspaceFolderData {
325 >
326 > /**
327 > * Given workspace folder relative path, returns the resource with the absolute path.
328 > */
329 > toResource: (relativePath: string) => URI;
330 > }
331 >
332 > export function isWorkspaceFolder(thing: unknown): thing is IWorkspaceFolder {
333 const candidate = thing as IWorkspaceFolder;
334
338 && typeof candidate.toResource === 'function');
339 }
340 > workspace.ts
341 > export class Workspace implements IWorkspace {
342 >
343 > private foldersMap: TernarySearchTree<URI, WorkspaceFolder>;
344 >
345 > private _folders!: WorkspaceFolder[];
346 > get folders(): WorkspaceFolder[] { return this._folders; }
347 > set folders(folders: WorkspaceFolder[]) {
348 this._folders = folders;
349 this.updateFoldersMap();
350 }
351 > workspace.ts
352 > constructor(
353 private _id: string,
354 folders: WorkspaceFolder[],
361 this.folders = folders;
362 }
363 > workspace.ts
364 > update(workspace: Workspace) {
365 this._id = workspace.id;
366 this._configuration = workspace.configuration;
370 this.folders = workspace.folders;
371 }
372 > workspace.ts
373 > get id(): string {
374 return this._id;
375 }
376 > workspace.ts
377 > get transient(): boolean {
378 return this._transient;
379 }
380 > workspace.ts
381 > get configuration(): URI | null {
382 return this._configuration;
383 }
384 > workspace.ts
385 > set configuration(configuration: URI | null) {
386 this._configuration = configuration;
387 }
388 > workspace.ts
389 > get name(): string | undefined {
390 return this._workspaceName;
391 }
392 > workspace.ts
393 > getFolder(resource: URI): IWorkspaceFolder | null {
394 if (!resource) {
395 return null;
398 return this.foldersMap.findSubstr(resource) || null;
399 }
400 > workspace.ts
401 > private updateFoldersMap(): void {
402 this.foldersMap = TernarySearchTree.forUris<WorkspaceFolder>(this.ignorePathCasing, () => true);
403 for (const folder of this.folders) {
405 }
406 }
407 > workspace.ts
408 > toJSON(): IWorkspace {
409 return { id: this.id, folders: this.folders, transient: this.transient, configuration: this.configuration, name: this.name };
410 }
411 > } workspace.ts
412 >
413 > export interface IRawFileWorkspaceFolder {
414 > readonly path: string;
415 > name?: string;
416 > }
417 >
418 > export interface IRawUriWorkspaceFolder {
419 > readonly uri: string;
420 > name?: string;
421 > }
422 >
423 > export class WorkspaceFolder implements IWorkspaceFolder {
424 >
425 > readonly uri: URI;
426 > readonly name: string;
427 > readonly index: number;
428 >
429 > constructor(
430 data: IWorkspaceFolderData,
431 /**
442 this.name = data.name;
443 }
444 > workspace.ts
445 > toResource(relativePath: string): URI {
446 return joinPath(this.uri, relativePath);
447 }
448 > workspace.ts
449 > toJSON(): IWorkspaceFolderData {
450 return { uri: this.uri, name: this.name, index: this.index };
451 }
452 > } workspace.ts
453 >
454 > export function toWorkspaceFolder(resource: URI): WorkspaceFolder {
455 return new WorkspaceFolder({ uri: resource, index: 0, name: basenameOrAuthority(resource) }, { uri: resource.toString() });
456 }
457 > workspace.ts
458 > export const WORKSPACE_EXTENSION = 'code-workspace';
459 > export const WORKSPACE_SUFFIX = `.${WORKSPACE_EXTENSION}`;
460 > export const WORKSPACE_FILTER = [{ name: localize('codeWorkspace', "Code Workspace"), extensions: [WORKSPACE_EXTENSION] }];
461 > export const UNTITLED_WORKSPACE_NAME = 'workspace.json';
462 >
463 > export function isUntitledWorkspace(path: URI, environmentService: IEnvironmentService): boolean {
464 return extUriBiasedIgnorePathCase.isEqualOrParent(path, environmentService.untitledWorkspacesHome);
465 }
466 > workspace.ts
467 > export function isTemporaryWorkspace(workspace: IWorkspace): boolean;
468 > export function isTemporaryWorkspace(path: URI): boolean;
469 > export function isTemporaryWorkspace(arg1: IWorkspace | URI): boolean {
470 let path: URI | null | undefined;
471 if (URI.isUri(arg1)) {
477 return path?.scheme === Schemas.tmp;
478 }
479 > workspace.ts
480 > export const STANDALONE_EDITOR_WORKSPACE_ID = '4064f6ec-cb38-4ad0-af64-ee6467e63c82';
481 > export function isStandaloneEditorWorkspace(workspace: IWorkspace): boolean {
482 return workspace.id === STANDALONE_EDITOR_WORKSPACE_ID;
483 }
484 > workspace.ts
485 > export function isSavedWorkspace(path: URI, environmentService: IEnvironmentService): boolean {
486 return !isUntitledWorkspace(path, environmentService) && !isTemporaryWorkspace(path);
487 }
488 > workspace.ts
489 > export function hasWorkspaceFileExtension(path: string | URI) {
490 const ext = (typeof path === 'string') ? extname(path) : resourceExtname(path);
491
src/vs/base/parts/storage/common/storage.ts 317 covered LOC · 63 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- storage.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { ThrottledDelayer } from '../../../common/async.js';
7 > import { Event, PauseableEmitter } from '../../../common/event.js';
8 > import { Disposable, IDisposable } from '../../../common/lifecycle.js';
9 > import { parse, stringify } from '../../../common/marshalling.js';
10 > import { isObject, isUndefined, isUndefinedOrNull } from '../../../common/types.js';
11 >
12 > export enum StorageHint {
13 >
14 > // A hint to the storage that the storage
15 > // does not exist on disk yet. This allows
16 > // the storage library to improve startup
17 > // time by not checking the storage for data.
18 > STORAGE_DOES_NOT_EXIST,
19 >
20 > // A hint to the storage that the storage
21 > // is backed by an in-memory storage.
22 > STORAGE_IN_MEMORY
23 > }
24 >
25 > export interface IStorageOptions {
26 > readonly hint?: StorageHint;
27 > }
28 >
29 > export interface IUpdateRequest {
30 > readonly insert?: Map<string, string>;
31 > readonly delete?: Set<string>;
32 > }
33 >
34 > export interface IStorageItemsChangeEvent {
35 > readonly changed?: Map<string, string>;
36 > readonly deleted?: Set<string>;
37 > }
38 >
39 > export function isStorageItemsChangeEvent(thing: unknown): thing is IStorageItemsChangeEvent {
40 const candidate = thing as IStorageItemsChangeEvent | undefined;
41
42 return candidate?.changed instanceof Map || candidate?.deleted instanceof Set;
43 }
44 > storage.ts
45 > export interface IStorageDatabase {
46 >
47 > readonly onDidChangeItemsExternal: Event<IStorageItemsChangeEvent>;
48 >
49 > getItems(): Promise<Map<string, string>>;
50 > updateItems(request: IUpdateRequest): Promise<void>;
51 >
52 > optimize(): Promise<void>;
53 >
54 > close(recovery?: () => Map<string, string>): Promise<void>;
55 > }
56 >
57 > export interface IStorageChangeEvent {
58 >
59 > /**
60 > * The `key` of the storage entry that was changed
61 > * or was removed.
62 > */
63 > readonly key: string;
64 >
65 > /**
66 > * A hint how the storage change event was triggered. If
67 > * `true`, the storage change was triggered by an external
68 > * source, such as:
69 > * - another process (for example another window)
70 > * - operations such as settings sync or profiles change
71 > */
72 > readonly external?: boolean;
73 > }
74 >
75 > export type StorageValue = string | boolean | number | undefined | null | object;
76 >
77 > export interface IStorage extends IDisposable {
78 >
79 > readonly onDidChangeStorage: Event<IStorageChangeEvent>;
80 >
81 > readonly items: Map<string, string>;
82 > readonly size: number;
83 >
84 > init(): Promise<void>;
85 >
86 > get(key: string, fallbackValue: string): string;
87 > get(key: string, fallbackValue?: string): string | undefined;
88 >
89 > getBoolean(key: string, fallbackValue: boolean): boolean;
90 > getBoolean(key: string, fallbackValue?: boolean): boolean | undefined;
91 >
92 > getNumber(key: string, fallbackValue: number): number;
93 > getNumber(key: string, fallbackValue?: number): number | undefined;
94 >
95 > getObject<T extends object>(key: string, fallbackValue: T): T;
96 > getObject<T extends object>(key: string, fallbackValue?: T): T | undefined;
97 >
98 > set(key: string, value: StorageValue, external?: boolean): Promise<void>;
99 > delete(key: string, external?: boolean): Promise<void>;
100 >
101 > flush(delay?: number): Promise<void>;
102 > whenFlushed(): Promise<void>;
103 >
104 > optimize(): Promise<void>;
105 >
106 > close(): Promise<void>;
107 > }
108 >
109 > export enum StorageState {
110 > None,
111 > Initialized,
112 > Closed
113 > }
114 >
115 > export class Storage extends Disposable implements IStorage {
116 >
117 > private static readonly DEFAULT_FLUSH_DELAY = 100;
118 >
119 > private readonly _onDidChangeStorage = this._register(new PauseableEmitter<IStorageChangeEvent>());
120 > readonly onDidChangeStorage = this._onDidChangeStorage.event;
121 >
122 > private state = StorageState.None;
123 >
124 > private cache = new Map<string, string>();
125 >
126 > private readonly flushDelayer = this._register(new ThrottledDelayer<void>(Storage.DEFAULT_FLUSH_DELAY));
127 >
128 > private pendingDeletes = new Set<string>();
129 > private pendingInserts = new Map<string, string>();
130 >
131 > private pendingClose: Promise<void> | undefined = undefined;
132 >
133 > private readonly whenFlushedCallbacks: Function[] = [];
134 >
135 > constructor(
136 > protected readonly database: IStorageDatabase, storage.ts
137 > private readonly options: IStorageOptions = Object.create(null)
138 > ) {
139 > super();
140 >
141 > this.registerListeners();
142 > }
143 > storage.ts
144 > private registerListeners(): void {
145 > this._register(this.database.onDidChangeItemsExternal(e => this.onDidChangeItemsExternal(e))); storage.ts
146 > }
147 > storage.ts
148 > private onDidChangeItemsExternal(e: IStorageItemsChangeEvent): void {
149 this._onDidChangeStorage.pause();
150
161 }
162 }
163 > storage.ts
164 > private acceptExternal(key: string, value: string | undefined): void {
165 if (this.state === StorageState.Closed) {
166 return; // Return early if we are already closed
188 }
189 }
190 > storage.ts
191 > get items(): Map<string, string> {
192 return this.cache;
193 }
194 > storage.ts
195 > get size(): number {
196 return this.cache.size;
197 }
198 > storage.ts
199 > async init(): Promise<void> {
200 if (this.state !== StorageState.None) {
201 return; // either closed or already initialized
213 this.cache = await this.database.getItems();
214 }
215 > storage.ts
216 > get(key: string, fallbackValue: string): string;
217 > get(key: string, fallbackValue?: string): string | undefined;
218 > get(key: string, fallbackValue?: string): string | undefined {
219 > const value = this.cache.get(key); storage.ts
220 >
221 > if (isUndefinedOrNull(value)) {
222 > return fallbackValue; storage.ts
223 > }
224 > storage.ts
225 > return value;
226 > } storage.ts
227 > storage.ts
228 > getBoolean(key: string, fallbackValue: boolean): boolean;
229 > getBoolean(key: string, fallbackValue?: boolean): boolean | undefined;
230 > getBoolean(key: string, fallbackValue?: boolean): boolean | undefined {
231 > const value = this.get(key); storage.ts
232 >
233 > if (isUndefinedOrNull(value)) {
234 > return fallbackValue; storage.ts
235 > }
236 > storage.ts
237 > return value === 'true';
238 > } storage.ts
239 > storage.ts
240 > getNumber(key: string, fallbackValue: number): number;
241 > getNumber(key: string, fallbackValue?: number): number | undefined;
242 > getNumber(key: string, fallbackValue?: number): number | undefined {
243 > const value = this.get(key); storage.ts
244 >
245 > if (isUndefinedOrNull(value)) {
246 > return fallbackValue;
247 > }
248
249 return parseInt(value, 10);
250 > } storage.ts
251 > storage.ts
252 > getObject(key: string, fallbackValue: object): object;
253 > getObject(key: string, fallbackValue?: object | undefined): object | undefined;
254 > getObject(key: string, fallbackValue?: object): object | undefined {
255 const value = this.get(key);
256
261 return parse(value);
262 }
263 > storage.ts
264 > async set(key: string, value: string | boolean | number | null | undefined | object, external = false): Promise<void> {
265 > if (this.state === StorageState.Closed) { storage.ts
266 return; // Return early if we are already closed
267 }
268 > storage.ts
269 > // We remove the key for undefined/null values
270 > if (isUndefinedOrNull(value)) {
271 return this.delete(key, external);
272 }
273 > storage.ts
274 > // Otherwise, convert to String and store
275 > const valueStr = isObject(value) || Array.isArray(value) ? stringify(value) : String(value);
276 >
277 > // Return early if value already set
278 > const currentValue = this.cache.get(key);
279 > if (currentValue === valueStr) {
280 return;
281 }
282 > storage.ts
283 > // Update in cache and pending
284 > this.cache.set(key, valueStr);
285 > this.pendingInserts.set(key, valueStr);
286 > this.pendingDeletes.delete(key);
287 >
288 > // Event
289 > this._onDidChangeStorage.fire({ key, external });
290 >
291 > // Accumulate work by scheduling after timeout
292 > return this.doFlush();
293 > }
294 > storage.ts
295 > async delete(key: string, external = false): Promise<void> {
296 > if (this.state === StorageState.Closed) { storage.ts
297 return; // Return early if we are already closed
298 }
299 > storage.ts
300 > // Remove from cache and add to pending
301 > const wasDeleted = this.cache.delete(key);
302 > if (!wasDeleted) {
303 > return; // Return early if value already deleted storage.ts
304 > }
305 > storage.ts
306 > if (!this.pendingDeletes.has(key)) {
307 > this.pendingDeletes.add(key);
308 > }
309 >
310 > this.pendingInserts.delete(key);
311 >
312 > // Event
313 > this._onDidChangeStorage.fire({ key, external });
314 >
315 > // Accumulate work by scheduling after timeout
316 > return this.doFlush();
317 > } storage.ts
318 > storage.ts
319 > async optimize(): Promise<void> {
320 if (this.state === StorageState.Closed) {
321 return; // Return early if we are already closed
328 return this.database.optimize();
329 }
330 > storage.ts
331 > async close(): Promise<void> {
332 if (!this.pendingClose) {
333 this.pendingClose = this.doClose();
336 return this.pendingClose;
337 }
338 > storage.ts
339 > private async doClose(): Promise<void> {
340
341 // Update state
356 await this.database.close(() => this.cache);
357 }
358 > storage.ts
359 > private get hasPending() {
360 > return this.pendingInserts.size > 0 || this.pendingDeletes.size > 0; storage.ts
361 > }
362 > storage.ts
363 > private async flushPending(): Promise<void> {
364 > if (!this.hasPending) { storage.ts
365 return; // return early if nothing to do
366 }
367 > storage.ts
368 > // Get pending data
369 > const updateRequest: IUpdateRequest = { insert: this.pendingInserts, delete: this.pendingDeletes };
370 >
371 > // Reset pending data for next run
372 > this.pendingDeletes = new Set<string>();
373 > this.pendingInserts = new Map<string, string>();
374 >
375 > // Update in storage and release any
376 > // waiters we have once done
377 > return this.database.updateItems(updateRequest).finally(() => {
378 > if (!this.hasPending) {
379 > while (this.whenFlushedCallbacks.length) {
380 this.whenFlushedCallbacks.pop()?.();
381 }
382 > } storage.ts
383 > });
384 > }
385 > storage.ts
386 > async flush(delay?: number): Promise<void> {
387 if (
388 this.state === StorageState.Closed || // Return early if we are already closed
394 return this.doFlush(delay);
395 }
396 > storage.ts
397 > private async doFlush(delay?: number): Promise<void> {
398 > if (this.options.hint === StorageHint.STORAGE_IN_MEMORY) { storage.ts
399 > return this.flushPending(); // return early if in-memory storage.ts
400 > }
401
402 return this.flushDelayer.trigger(() => this.flushPending(), delay);
403 > } storage.ts
404 > storage.ts
405 > async whenFlushed(): Promise<void> {
406 if (!this.hasPending) {
407 return; // return early if nothing to do
410 return new Promise(resolve => this.whenFlushedCallbacks.push(resolve));
411 }
412 > storage.ts
413 > isInMemory(): boolean {
414 return this.options.hint === StorageHint.STORAGE_IN_MEMORY;
415 }
416 > } storage.ts
417 >
418 > export class InMemoryStorageDatabase implements IStorageDatabase {
419 > storage.ts
420 > readonly onDidChangeItemsExternal = Event.None;
421 >
422 > private readonly items = new Map<string, string>();
423 > storage.ts
424 > async getItems(): Promise<Map<string, string>> {
425 return this.items;
426 }
427 > storage.ts
428 > async updateItems(request: IUpdateRequest): Promise<void> {
429 > request.insert?.forEach((value, key) => this.items.set(key, value)); storage.ts
430 >
431 > request.delete?.forEach(key => this.items.delete(key));
432 > }
433 > storage.ts
434 > async optimize(): Promise<void> { }
435 > async close(): Promise<void> { }
436 > }
437 >
438 >
439 > export const MIGRATED_KEY = '__$__migratedStorageMarker';
440 >
441 > export class MigratingStorage extends Storage {
442
443 private migratedKeys: Set<string> = new Set();
444 private fallbackStorage: IStorage | undefined = undefined;
445 private isFallbackStorageReadonly: boolean = false;
446 > storage.ts
447 > override async init(): Promise<void> {
448 await super.init();
449
451 this.migratedKeys = this.loadMigratedKeys();
452 }
453 > storage.ts
454 > public setFallbackStorage(storage: IStorage, isReadonly: boolean): void {
455 this.fallbackStorage = storage;
456 this.isFallbackStorageReadonly = isReadonly;
457 }
458 > storage.ts
459 > private static readonly INTERNAL_KEY_PREFIX = '__$__';
460 >
461 > override get(key: string, fallbackValue: string): string;
462 > override get(key: string, fallbackValue?: string): string | undefined;
463 > override get(key: string, fallbackValue?: string): string | undefined {
464 if (!key.startsWith(MigratingStorage.INTERNAL_KEY_PREFIX) && !this.migratedKeys.has(key) && isUndefined(super.get(key))) {
465 // Check fallback storage and auto-migrate on hit.
480 return super.get(key, fallbackValue);
481 }
482 > storage.ts
483 > private loadMigratedKeys(): Set<string> {
484 const raw = super.get(MIGRATED_KEY);
485 if (raw) {
492 return new Set();
493 }
494 > storage.ts
495 > private persistMigratedKeys(): void {
496 this.set(MIGRATED_KEY, JSON.stringify([...this.migratedKeys]));
497 }
498 > } storage.ts
499
src/vs/platform/userDataProfile/common/userDataProfile.ts 316 covered LOC · 38 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataProfile.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { hash } from '../../../base/common/hash.js';
7 > import { Emitter, Event } from '../../../base/common/event.js';
8 > import { Disposable } from '../../../base/common/lifecycle.js';
9 > import { basename, joinPath } from '../../../base/common/resources.js';
10 > import { URI, UriDto } from '../../../base/common/uri.js';
11 > import { localize } from '../../../nls.js';
12 > import { IEnvironmentService } from '../../environment/common/environment.js';
13 > import { FileOperationResult, IFileService, toFileOperationResult } from '../../files/common/files.js';
14 > import { createDecorator } from '../../instantiation/common/instantiation.js';
15 > import { ILogService } from '../../log/common/log.js';
16 > import { IAnyWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier } from '../../workspace/common/workspace.js';
17 > import { IStringDictionary } from '../../../base/common/collections.js';
18 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
19 > import { Promises } from '../../../base/common/async.js';
20 > import { generateUuid } from '../../../base/common/uuid.js';
21 > import { escapeRegExpCharacters } from '../../../base/common/strings.js';
22 > import { isString, Mutable } from '../../../base/common/types.js';
23 >
24 > export const AGENTS_WINDOW_PROFILE_ID = 'agents';
25 >
26 > const AGENTS_WINDOW_PROFILE_FLAGS: UseDefaultProfileFlags = {
27 > settings: true,
28 > keybindings: true,
29 > prompts: true,
30 > mcp: true,
31 > languageModels: true,
32 > snippets: true,
33 > tasks: true,
34 > extensions: true,
35 > };
36 >
37 > export const enum ProfileResourceType {
38 > Settings = 'settings',
39 > Keybindings = 'keybindings',
40 > Snippets = 'snippets',
41 > Prompts = 'prompts',
42 > Tasks = 'tasks',
43 > Extensions = 'extensions',
44 > GlobalState = 'globalState',
45 > Mcp = 'mcp',
46 > LanguageModels = 'languageModels',
47 > }
48 >
49 > /**
50 > * Flags to indicate whether to use the default profile or not.
51 > */
52 > export type UseDefaultProfileFlags = { [key in ProfileResourceType]?: boolean };
53 > export type ProfileResourceTypeFlags = UseDefaultProfileFlags;
54 > export type SettingValue = string | boolean | number | undefined | null | object;
55 > export type ISettingsDictionary = Record<string, SettingValue>;
56 >
57 > export interface IUserDataProfile {
58 > readonly id: string;
59 > readonly isDefault: boolean;
60 > readonly name: string;
61 > readonly icon?: string;
62 > readonly location: URI;
63 > readonly globalStorageHome: URI;
64 > readonly settingsResource: URI;
65 > readonly keybindingsResource: URI;
66 > readonly tasksResource: URI;
67 > readonly snippetsHome: URI;
68 > readonly promptsHome: URI;
69 > readonly extensionsResource: URI;
70 > readonly mcpResource: URI;
71 > readonly languageModelsResource: URI;
72 > readonly agentPluginsHome: URI;
73 > readonly cacheHome: URI;
74 > readonly useDefaultFlags?: UseDefaultProfileFlags;
75 > readonly isInternal?: boolean;
76 > readonly isTransient?: boolean;
77 > readonly isAgentsWindowProfile?: boolean;
78 > readonly workspaces?: readonly URI[];
79 > }
80 >
81 > export function isUserDataProfile(thing: unknown): thing is IUserDataProfile {
82 const candidate = thing as IUserDataProfile | undefined;
83
99 );
100 }
102 > export interface IParsedUserDataProfileTemplate {
103 > readonly name: string;
104 > readonly icon?: string;
105 > readonly settings?: ISettingsDictionary;
106 > readonly globalState?: IStringDictionary<string>;
107 > }
108 >
109 > export interface ISystemProfileTemplate extends IParsedUserDataProfileTemplate {
110 > readonly id: string;
111 > }
112 >
113 > export type DidChangeProfilesEvent = { readonly added: readonly IUserDataProfile[]; readonly removed: readonly IUserDataProfile[]; readonly updated: readonly IUserDataProfile[]; readonly all: readonly IUserDataProfile[] };
114 >
115 > export type WillCreateProfileEvent = {
116 > profile: IUserDataProfile;
117 > join(promise: Promise<void>): void;
118 > };
119 >
120 > export type WillRemoveProfileEvent = {
121 > profile: IUserDataProfile;
122 > join(promise: Promise<void>): void;
123 > };
124 >
125 > export interface IUserDataProfileOptions {
126 > readonly icon?: string;
127 > readonly useDefaultFlags?: UseDefaultProfileFlags;
128 > readonly transient?: boolean;
129 > readonly workspaces?: readonly URI[];
130 > }
131 >
132 > export interface IUserDataProfileUpdateOptions extends Omit<IUserDataProfileOptions, 'icon'> {
133 > readonly name?: string;
134 > readonly icon?: string | null;
135 > }
136 >
137 > export const IUserDataProfilesService = createDecorator<IUserDataProfilesService>('IUserDataProfilesService');
138 > export interface IUserDataProfilesService {
139 > readonly _serviceBrand: undefined;
140 >
141 > readonly profilesHome: URI;
142 > readonly defaultProfile: IUserDataProfile;
143 >
144 > readonly onDidChangeProfiles: Event<DidChangeProfilesEvent>;
145 > readonly profiles: readonly IUserDataProfile[];
146 >
147 > readonly onDidResetWorkspaces: Event<void>;
148 >
149 > createNamedProfile(name: string, options?: IUserDataProfileOptions, workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile>;
150 > createTransientProfile(workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile>;
151 > createProfile(id: string, name: string, options?: IUserDataProfileOptions, workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile>;
152 > updateProfile(profile: IUserDataProfile, options?: IUserDataProfileUpdateOptions,): Promise<IUserDataProfile>;
153 > removeProfile(profile: IUserDataProfile): Promise<void>;
154 >
155 > setProfileForWorkspace(workspaceIdentifier: IAnyWorkspaceIdentifier, profile: IUserDataProfile): Promise<void>;
156 > resetWorkspaces(): Promise<void>;
157 >
158 > cleanUp(): Promise<void>;
159 > cleanUpTransientProfiles(): Promise<void>;
160 > }
161 >
162 > export function reviveProfile(profile: UriDto<IUserDataProfile>, scheme: string): IUserDataProfile {
163 return {
164 id: profile.id,
185 };
186 }
188 > export function toUserDataProfile(id: string, name: string, location: URI, profilesCacheHome: URI, options?: IUserDataProfileOptions, defaultProfile?: IUserDataProfile): IUserDataProfile {
189 > const isAgentsWindowProfile = id === AGENTS_WINDOW_PROFILE_ID; userDataProfile.ts
190 > return {
191 > id,
192 > name,
193 > location,
194 > isDefault: false,
195 > icon: options?.icon,
196 > globalStorageHome: defaultProfile && options?.useDefaultFlags?.globalState ? defaultProfile.globalStorageHome : joinPath(location, 'globalStorage'),
197 > settingsResource: defaultProfile && options?.useDefaultFlags?.settings ? defaultProfile.settingsResource : joinPath(location, 'settings.json'),
198 > keybindingsResource: defaultProfile && options?.useDefaultFlags?.keybindings ? defaultProfile.keybindingsResource : joinPath(location, 'keybindings.json'),
199 > tasksResource: defaultProfile && options?.useDefaultFlags?.tasks ? defaultProfile.tasksResource : joinPath(location, 'tasks.json'),
200 > snippetsHome: defaultProfile && options?.useDefaultFlags?.snippets ? defaultProfile.snippetsHome : joinPath(location, 'snippets'),
201 > promptsHome: defaultProfile && options?.useDefaultFlags?.prompts ? defaultProfile.promptsHome : joinPath(location, 'prompts'),
202 > extensionsResource: defaultProfile && options?.useDefaultFlags?.extensions ? defaultProfile.extensionsResource : joinPath(location, 'extensions.json'),
203 > mcpResource: defaultProfile && options?.useDefaultFlags?.mcp ? defaultProfile.mcpResource : joinPath(location, 'mcp.json'),
204 > languageModelsResource: defaultProfile && options?.useDefaultFlags?.languageModels ? defaultProfile.languageModelsResource : joinPath(location, 'chatLanguageModels.json'),
205 > agentPluginsHome: defaultProfile ? defaultProfile.agentPluginsHome : joinPath(location, 'agent-plugins'),
206 > cacheHome: joinPath(profilesCacheHome, id),
207 > useDefaultFlags: options?.useDefaultFlags,
208 > isTransient: options?.transient,
209 > isInternal: isAgentsWindowProfile || options?.transient,
210 > isAgentsWindowProfile,
211 > workspaces: options?.workspaces,
212 > };
213 > }
215 > export type UserDataProfilesObject = {
216 > profiles: IUserDataProfile[];
217 > emptyWindows: Map<string, IUserDataProfile>;
218 > };
219 >
220 > export type StoredUserDataProfile = {
221 > name: string;
222 > location: URI;
223 > icon?: string;
224 > useDefaultFlags?: UseDefaultProfileFlags;
225 > };
226 >
227 > export type StoredProfileAssociations = {
228 > workspaces?: IStringDictionary<string>;
229 > emptyWindows?: IStringDictionary<string>;
230 > };
231 >
232 > const SYSTEM_PROFILES_HOME = 'builtin';
233 >
234 > export class UserDataProfilesService extends Disposable implements IUserDataProfilesService {
235 >
236 > readonly _serviceBrand: undefined;
237 >
238 > protected static readonly PROFILES_KEY = 'userDataProfiles';
239 > protected static readonly PROFILE_ASSOCIATIONS_KEY = 'profileAssociations';
240 >
241 > readonly profilesHome: URI;
242 > private readonly profilesCacheHome: URI;
243 >
244 > get defaultProfile(): IUserDataProfile { return this.profiles[0]; }
245 > get profiles(): IUserDataProfile[] { return [...this.profilesObject.profiles, ...this.transientProfilesObject.profiles]; }
246 >
247 > protected readonly _onDidChangeProfiles = this._register(new Emitter<DidChangeProfilesEvent>());
248 > readonly onDidChangeProfiles = this._onDidChangeProfiles.event;
249 >
250 > protected readonly _onWillCreateProfile = this._register(new Emitter<WillCreateProfileEvent>());
251 > readonly onWillCreateProfile = this._onWillCreateProfile.event;
252 >
253 > protected readonly _onWillRemoveProfile = this._register(new Emitter<WillRemoveProfileEvent>());
254 > readonly onWillRemoveProfile = this._onWillRemoveProfile.event;
255 >
256 > private readonly _onDidResetWorkspaces = this._register(new Emitter<void>());
257 > readonly onDidResetWorkspaces = this._onDidResetWorkspaces.event;
258 >
259 > private profileCreationPromises = new Map<string, Promise<IUserDataProfile>>();
260 >
261 > protected readonly transientProfilesObject: UserDataProfilesObject = {
262 > profiles: [],
263 > emptyWindows: new Map()
264 > };
265 >
266 > constructor(
267 > @IEnvironmentService protected environmentService: IEnvironmentService, userDataProfile.ts
268 > @IFileService protected fileService: IFileService,
269 > @IUriIdentityService protected uriIdentityService: IUriIdentityService,
270 > @ILogService protected logService: ILogService
271 > ) {
272 > super();
273 > this.profilesHome = joinPath(this.environmentService.userRoamingDataHome, 'profiles');
274 > this.profilesCacheHome = joinPath(this.environmentService.cacheHome, 'CachedProfilesData');
275 > }
277 > init(): void {
278 this._profilesObject = undefined;
279 }
281 > protected _profilesObject: UserDataProfilesObject | undefined;
282 > protected get profilesObject(): UserDataProfilesObject {
283 > if (!this._profilesObject) { userDataProfile.ts
284 > const defaultProfile = this.createDefaultProfile();
285 > const profiles: Array<Mutable<IUserDataProfile>> = [defaultProfile];
286 > try {
287 > for (const storedProfile of this.getStoredProfiles()) {
288 if (this.isInvalidProfile(storedProfile)) {
289 this.logService.warn('Skipping the invalid stored profile', storedProfile.location || storedProfile.name);
302 defaultProfile));
303 }
304 > } catch (error) { userDataProfile.ts
305 this.logService.error(error);
306 }
307 > const emptyWindows = new Map<string, IUserDataProfile>(); userDataProfile.ts
308 > if (profiles.length) {
309 > try {
310 > const profileAssociaitions = this.getStoredProfileAssociations();
311 > if (profileAssociaitions.workspaces) {
312 for (const [workspacePath, profileId] of Object.entries(profileAssociaitions.workspaces)) {
313 const workspace = URI.parse(workspacePath);
320 }
321 }
322 > if (profileAssociaitions.emptyWindows) { userDataProfile.ts
323 for (const [windowId, profileId] of Object.entries(profileAssociaitions.emptyWindows)) {
324 const profile = profiles.find(p => p.id === profileId);
328 }
329 }
330 > } catch (error) { userDataProfile.ts
331 this.logService.error(error);
332 }
334 > this._profilesObject = { profiles, emptyWindows };
335 > }
336 > return this._profilesObject;
337 > }
339 > private isInvalidProfile(storedProfile: StoredUserDataProfile): boolean {
340 if (!storedProfile.name) {
341 return true;
349 return false;
350 }
352 > protected createDefaultProfile() {
353 > const defaultProfile = toUserDataProfile('__default__profile__', localize('defaultProfile', "Default"), this.environmentService.userRoamingDataHome, this.profilesCacheHome); userDataProfile.ts
354 > return { ...defaultProfile, extensionsResource: this.getDefaultProfileExtensionsLocation() ?? defaultProfile.extensionsResource, isDefault: true };
355 > }
357 > async createTransientProfile(workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile> {
358 const namePrefix = `Temp`;
359 const nameRegEx = new RegExp(`${escapeRegExpCharacters(namePrefix)}\\s(\\d+)`);
367 return this.createProfile(hash(generateUuid()).toString(16), name, { transient: true }, workspaceIdentifier);
368 }
370 > async createNamedProfile(name: string, options?: IUserDataProfileOptions, workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile> {
371 return this.createProfile(hash(generateUuid()).toString(16), name, options, workspaceIdentifier);
372 }
374 > async createProfile(id: string, name: string, options?: IUserDataProfileOptions, workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile> {
375 const profile = await this.doCreateProfile(id, name, options, workspaceIdentifier);
376
377 return profile;
378 }
380 > private async doCreateProfile(id: string, name: string, options?: IUserDataProfileOptions, workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile> {
381 if (!isString(name) || !name) {
382 throw new Error('Name of the profile is mandatory and must be of type `string`');
428 return profileCreationPromise;
429 }
431 > async updateProfile(profile: IUserDataProfile, options: IUserDataProfileUpdateOptions): Promise<IUserDataProfile> {
432 if (profile.isAgentsWindowProfile) {
433 throw new Error('Cannot update agents window profile');
481 return updatedProfile;
482 }
484 > async removeProfile(profileToRemove: IUserDataProfile): Promise<void> {
485 if (profileToRemove.isDefault) {
486 throw new Error('Cannot remove default profile');
515 }
516 }
518 > async setProfileForWorkspace(workspaceIdentifier: IAnyWorkspaceIdentifier, profileToSet: IUserDataProfile): Promise<void> {
519 const profile = this.profiles.find(p => p.id === profileToSet.id);
520 if (!profile) {
534 }
535 }
537 > unsetWorkspace(workspaceIdentifier: IAnyWorkspaceIdentifier, transient: boolean = false): void {
538 const workspace = this.getWorkspace(workspaceIdentifier);
539 if (URI.isUri(workspace)) {
547 }
548 }
550 > async resetWorkspaces(): Promise<void> {
551 this.transientProfilesObject.emptyWindows.clear();
552 this.profilesObject.emptyWindows.clear();
557 this._onDidResetWorkspaces.fire();
558 }
560 > async cleanUp(): Promise<void> {
561 try {
562 if (await this.fileService.exists(this.profilesHome)) {
587 }
588 }
590 > async cleanUpTransientProfiles(): Promise<void> {
591 const unAssociatedTransientProfiles = this.transientProfilesObject.profiles.filter(p => !this.isProfileAssociatedToWorkspace(p));
592 await Promise.allSettled(unAssociatedTransientProfiles.map(p => this.removeProfile(p)));
593 }
595 > getProfileForWorkspace(workspaceIdentifier: IAnyWorkspaceIdentifier): IUserDataProfile | undefined {
596 const workspace = this.getWorkspace(workspaceIdentifier);
597
604 : (this.profilesObject.emptyWindows.get(workspace) ?? this.transientProfilesObject.emptyWindows.get(workspace));
605 }
607 > protected getWorkspace(workspaceIdentifier: IAnyWorkspaceIdentifier): URI | string {
608 if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
609 return workspaceIdentifier.uri;
614 return workspaceIdentifier.id;
615 }
617 > private isProfileAssociatedToWorkspace(profile: IUserDataProfile): boolean {
618 if (profile.workspaces?.length) {
619 return true;
627 return false;
628 }
630 > private updateProfiles(added: IUserDataProfile[], removed: IUserDataProfile[], updated: IUserDataProfile[], donotTrigger: boolean = false): void {
631 const allProfiles: Mutable<IUserDataProfile>[] = [...this.profiles, ...added];
632
679 }
680 }
682 > protected triggerProfilesChanges(added: IUserDataProfile[], removed: IUserDataProfile[], updated: IUserDataProfile[]) {
683 this._onDidChangeProfiles.fire({ added, removed, updated, all: this.profiles });
684 }
686 > private updateEmptyWindowAssociation(windowId: string, newProfile: IUserDataProfile | undefined, transient: boolean): void {
687 // Force transient if the new profile to associate is transient
688 transient = newProfile?.isTransient ? true : transient;
706 }
707 }
709 > private updateStoredProfiles(profiles: IUserDataProfile[]): void {
710 const storedProfiles: StoredUserDataProfile[] = [];
711 const workspaces: IStringDictionary<string> = {};
739 this._profilesObject = undefined;
740 }
742 > protected getStoredProfiles(): StoredUserDataProfile[] { return []; }
743 > protected saveStoredProfiles(storedProfiles: StoredUserDataProfile[]): void { throw new Error('not implemented'); }
744 >
745 > protected getStoredProfileAssociations(): StoredProfileAssociations { return {}; }
746 > protected saveStoredProfileAssociations(storedProfileAssociations: StoredProfileAssociations): void { throw new Error('not implemented'); }
747 > protected getDefaultProfileExtensionsLocation(): URI | undefined { return undefined; }
748 > }
749 >
750 > export class InMemoryUserDataProfilesService extends UserDataProfilesService {
751 > private storedProfiles: StoredUserDataProfile[] = []; userDataProfile.ts
752 > protected override getStoredProfiles(): StoredUserDataProfile[] { return this.storedProfiles; }
753 > protected override saveStoredProfiles(storedProfiles: StoredUserDataProfile[]): void { this.storedProfiles = storedProfiles; }
754 >
755 > private storedProfileAssociations: StoredProfileAssociations = {};
756 > protected override getStoredProfileAssociations(): StoredProfileAssociations { return this.storedProfileAssociations; } userDataProfile.ts
757 > protected override saveStoredProfileAssociations(storedProfileAssociations: StoredProfileAssociations): void { this.storedProfileAssociations = storedProfileAssociations; }
758 > }
src/vs/platform/userDataSync/test/common/userDataSyncClient.ts 308 covered LOC · 58 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSyncClient.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { bufferToStream, VSBuffer } from '../../../../base/common/buffer.js';
7 > import { CancellationToken } from '../../../../base/common/cancellation.js';
8 > import { IStringDictionary } from '../../../../base/common/collections.js';
9 > import { Emitter, Event } from '../../../../base/common/event.js';
10 > import { FormattingOptions } from '../../../../base/common/jsonFormatter.js';
11 > import { Disposable } from '../../../../base/common/lifecycle.js';
12 > import { Schemas } from '../../../../base/common/network.js';
13 > import { joinPath } from '../../../../base/common/resources.js';
14 > import { URI } from '../../../../base/common/uri.js';
15 > import { generateUuid } from '../../../../base/common/uuid.js';
16 > import { IHeaders, IRequestContext, IRequestOptions } from '../../../../base/parts/request/common/request.js';
17 > import { IConfigurationService } from '../../../configuration/common/configuration.js';
18 > import { ConfigurationService } from '../../../configuration/common/configurationService.js';
19 > import { IEnvironmentService } from '../../../environment/common/environment.js';
20 > import { GlobalExtensionEnablementService } from '../../../extensionManagement/common/extensionEnablementService.js';
21 > import { DidUninstallExtensionEvent, IExtensionGalleryService, IExtensionManagementService, IGlobalExtensionEnablementService, InstallExtensionResult } from '../../../extensionManagement/common/extensionManagement.js';
22 > import { IFileService } from '../../../files/common/files.js';
23 > import { FileService } from '../../../files/common/fileService.js';
24 > import { InMemoryFileSystemProvider } from '../../../files/common/inMemoryFilesystemProvider.js';
25 > import { TestInstantiationService } from '../../../instantiation/test/common/instantiationServiceMock.js';
26 > import { ILogService, NullLogService } from '../../../log/common/log.js';
27 > import product from '../../../product/common/product.js';
28 > import { IProductService } from '../../../product/common/productService.js';
29 > import { AuthInfo, Credentials, IRequestCompleteEvent, IRequestService } from '../../../request/common/request.js';
30 > import { InMemoryStorageService, IStorageService } from '../../../storage/common/storage.js';
31 > import { ITelemetryService } from '../../../telemetry/common/telemetry.js';
32 > import { NullTelemetryService } from '../../../telemetry/common/telemetryUtils.js';
33 > import { IUriIdentityService } from '../../../uriIdentity/common/uriIdentity.js';
34 > import { UriIdentityService } from '../../../uriIdentity/common/uriIdentityService.js';
35 > import { ExtensionStorageService, IExtensionStorageService } from '../../../extensionManagement/common/extensionStorage.js';
36 > import { IgnoredExtensionsManagementService, IIgnoredExtensionsManagementService } from '../../common/ignoredExtensions.js';
37 > import { ALL_SYNC_RESOURCES, getDefaultIgnoredSettings, IUserData, IUserDataSyncLocalStoreService, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncService, IUserDataSyncStoreManagementService, IUserDataSyncStoreService, IUserDataSyncUtilService, registerConfiguration, ServerResource, SyncResource, IUserDataSynchroniser, IUserDataResourceManifest, IUserDataCollectionManifest, USER_DATA_SYNC_SCHEME, IUserDataManifest } from '../../common/userDataSync.js';
38 > import { IUserDataSyncAccountService, UserDataSyncAccountService } from '../../common/userDataSyncAccount.js';
39 > import { UserDataSyncLocalStoreService } from '../../common/userDataSyncLocalStoreService.js';
40 > import { IUserDataSyncMachinesService, UserDataSyncMachinesService } from '../../common/userDataSyncMachines.js';
41 > import { UserDataSyncEnablementService } from '../../common/userDataSyncEnablementService.js';
42 > import { UserDataSyncService } from '../../common/userDataSyncService.js';
43 > import { UserDataSyncStoreManagementService, UserDataSyncStoreService } from '../../common/userDataSyncStoreService.js';
44 > import { InMemoryUserDataProfilesService, IUserDataProfile, IUserDataProfilesService } from '../../../userDataProfile/common/userDataProfile.js';
45 > import { NullPolicyService } from '../../../policy/common/policy.js';
46 > import { IUserDataProfileStorageService } from '../../../userDataProfile/common/userDataProfileStorageService.js';
47 > import { TestUserDataProfileStorageService } from '../../../userDataProfile/test/common/userDataProfileStorageService.test.js';
48 > import { IMeteredConnectionService } from '../../../meteredConnection/common/meteredConnection.js';
49 >
50 > export class UserDataSyncClient extends Disposable {
51 >
52 > readonly instantiationService: TestInstantiationService;
53 >
54 > constructor(readonly testServer: UserDataSyncTestServer = new UserDataSyncTestServer()) {
55 > super(); userDataSyncClient.ts
56 > this.instantiationService = this._register(new TestInstantiationService());
57 > }
59 > async setUp(empty: boolean = false): Promise<void> {
60 > this._register(registerConfiguration()); userDataSyncClient.ts
61 >
62 > const logService = this.instantiationService.stub(ILogService, new NullLogService());
63 >
64 > const userRoamingDataHome = URI.file('userdata').with({ scheme: Schemas.inMemory });
65 > const userDataSyncHome = joinPath(userRoamingDataHome, '.sync');
66 > const environmentService = this.instantiationService.stub(IEnvironmentService, {
67 > userDataSyncHome,
68 > userRoamingDataHome,
69 > cacheHome: joinPath(userRoamingDataHome, 'cache'),
70 > argvResource: joinPath(userRoamingDataHome, 'argv.json'),
71 > sync: 'on'
72 > });
73 >
74 > this.instantiationService.stub(IProductService, {
75 > _serviceBrand: undefined, ...product, ...{
76 > 'configurationSync.store': {
77 > url: this.testServer.url,
78 > stableUrl: this.testServer.url,
79 > insidersUrl: this.testServer.url,
80 > canSwitch: false,
81 > authenticationProviders: { 'test': { scopes: [] } }
82 > }
83 > }
84 > });
85 >
86 > const fileService = this._register(new FileService(logService));
87 > this._register(fileService.registerProvider(Schemas.inMemory, this._register(new InMemoryFileSystemProvider())));
88 > this._register(fileService.registerProvider(USER_DATA_SYNC_SCHEME, this._register(new InMemoryFileSystemProvider())));
89 > this.instantiationService.stub(IFileService, fileService);
90 >
91 > const uriIdentityService = this._register(this.instantiationService.createInstance(UriIdentityService));
92 > this.instantiationService.stub(IUriIdentityService, uriIdentityService);
93 >
94 > const userDataProfilesService = this._register(new InMemoryUserDataProfilesService(environmentService, fileService, uriIdentityService, logService));
95 > this.instantiationService.stub(IUserDataProfilesService, userDataProfilesService);
96 >
97 > const storageService = this._register(new TestStorageService(userDataProfilesService.defaultProfile));
98 > this.instantiationService.stub(IStorageService, this._register(storageService));
99 > this.instantiationService.stub(IUserDataProfileStorageService, this._register(new TestUserDataProfileStorageService(false, storageService)));
100 >
101 > const configurationService = this._register(new ConfigurationService(userDataProfilesService.defaultProfile.settingsResource, fileService, new NullPolicyService(), logService));
102 > await configurationService.initialize();
103 > this.instantiationService.stub(IConfigurationService, configurationService);
104 >
105 > this.instantiationService.stub(IMeteredConnectionService, { isConnectionMetered: false, onDidChangeIsConnectionMetered: new Emitter<boolean>().event });
106 >
107 > this.instantiationService.stub(IRequestService, this.testServer);
108 >
109 > this.instantiationService.stub(IUserDataSyncLogService, logService);
110 > this.instantiationService.stub(ITelemetryService, NullTelemetryService);
111 > this.instantiationService.stub(IUserDataSyncStoreManagementService, this._register(this.instantiationService.createInstance(UserDataSyncStoreManagementService)));
112 > this.instantiationService.stub(IUserDataSyncStoreService, this._register(this.instantiationService.createInstance(UserDataSyncStoreService)));
113 >
114 > const userDataSyncAccountService: IUserDataSyncAccountService = this._register(this.instantiationService.createInstance(UserDataSyncAccountService));
115 > await userDataSyncAccountService.updateAccount({ authenticationProviderId: 'authenticationProviderId', token: 'token' });
116 > this.instantiationService.stub(IUserDataSyncAccountService, userDataSyncAccountService);
117 >
118 > this.instantiationService.stub(IUserDataSyncMachinesService, this._register(this.instantiationService.createInstance(UserDataSyncMachinesService)));
119 > this.instantiationService.stub(IUserDataSyncLocalStoreService, this._register(this.instantiationService.createInstance(UserDataSyncLocalStoreService)));
120 > this.instantiationService.stub(IUserDataSyncUtilService, new TestUserDataSyncUtilService());
121 > this.instantiationService.stub(IUserDataSyncEnablementService, this._register(this.instantiationService.createInstance(UserDataSyncEnablementService)));
122 >
123 > this.instantiationService.stub(IExtensionManagementService, {
124 > async getInstalled() { return []; },
125 > onDidInstallExtensions: new Emitter<readonly InstallExtensionResult[]>().event,
126 > onDidUninstallExtension: new Emitter<DidUninstallExtensionEvent>().event,
127 > });
128 > this.instantiationService.stub(IGlobalExtensionEnablementService, this._register(this.instantiationService.createInstance(GlobalExtensionEnablementService)));
129 > this.instantiationService.stub(IExtensionStorageService, this._register(this.instantiationService.createInstance(ExtensionStorageService)));
130 > this.instantiationService.stub(IIgnoredExtensionsManagementService, this.instantiationService.createInstance(IgnoredExtensionsManagementService));
131 > this.instantiationService.stub(IExtensionGalleryService, {
132 > isEnabled() { return true; },
133 > async getCompatibleExtension() { return null; }
134 > });
135 >
136 > this.instantiationService.stub(IUserDataSyncService, this._register(this.instantiationService.createInstance(UserDataSyncService)));
137 >
138 > if (!empty) {
139 > await fileService.writeFile(userDataProfilesService.defaultProfile.settingsResource, VSBuffer.fromString(JSON.stringify({}))); userDataSyncClient.ts
140 > await fileService.writeFile(userDataProfilesService.defaultProfile.keybindingsResource, VSBuffer.fromString(JSON.stringify([])));
141 > await fileService.writeFile(joinPath(userDataProfilesService.defaultProfile.snippetsHome, 'c.json'), VSBuffer.fromString(`{}`));
142 > await fileService.writeFile(joinPath(userDataProfilesService.defaultProfile.promptsHome, 'c.prompt.md'), VSBuffer.fromString(' '));
143 > await fileService.writeFile(userDataProfilesService.defaultProfile.tasksResource, VSBuffer.fromString(`{}`));
144 > await fileService.writeFile(environmentService.argvResource, VSBuffer.fromString(JSON.stringify({ 'locale': 'en' })));
145 > }
146 > await configurationService.reloadConfiguration(); userDataSyncClient.ts
147 >
148 > // `prompts` resource is disabled by default, so enable it for tests
149 > this.instantiationService
150 > .get(IUserDataSyncEnablementService)
151 > .setResourceEnablement(SyncResource.Prompts, true);
152 > }
154 > async sync(): Promise<void> {
155 await (await this.instantiationService.get(IUserDataSyncService).createSyncTask(null)).run();
156 }
158 > read(resource: SyncResource, collection?: string): Promise<IUserData> {
159 return this.instantiationService.get(IUserDataSyncStoreService).readResource(resource, null, collection);
160 }
162 > async getLatestRef(resource: SyncResource): Promise<string | null> {
163 const manifest = await this._getResourceManifest();
164 return manifest?.[resource] ?? null;
165 }
167 > async _getResourceManifest(): Promise<IUserDataResourceManifest | null> {
168 const manifest = await this.instantiationService.get(IUserDataSyncStoreService).manifest(null);
169 return manifest?.latest ?? null;
170 }
172 > getSynchronizer(source: SyncResource): IUserDataSynchroniser {
173 return (this.instantiationService.get(IUserDataSyncService) as UserDataSyncService).getOrCreateActiveProfileSynchronizer(this.instantiationService.get(IUserDataProfilesService).defaultProfile, undefined).enabled.find(s => s.resource === source)!;
174 }
176 > }
177 >
178 > const ALL_SERVER_RESOURCES: ServerResource[] = [...ALL_SYNC_RESOURCES, 'machines'];
179 >
180 > export class UserDataSyncTestServer implements IRequestService {
181 >
182 > _serviceBrand: undefined;
183 >
184 > readonly onDidCompleteRequest = Event.None as Event<IRequestCompleteEvent>;
185 >
186 > readonly url: string = 'http://host:3000';
187 > private session: string | null = null;
188 > private readonly collections = new Map<string, Map<ServerResource, IUserData>>();
189 > private readonly data = new Map<ServerResource, IUserData>();
190 >
191 > private _requests: { url: string; type: string; headers?: IHeaders }[] = [];
192 > get requests(): { url: string; type: string; headers?: IHeaders }[] { return this._requests; }
193 >
194 > private _requestsWithAllHeaders: { url: string; type: string; headers?: IHeaders }[] = [];
195 > get requestsWithAllHeaders(): { url: string; type: string; headers?: IHeaders }[] { return this._requestsWithAllHeaders; }
196 >
197 > private _responses: { status: number }[] = [];
198 > get responses(): { status: number }[] { return this._responses; }
199 > reset(): void { this._requests = []; this._responses = []; this._requestsWithAllHeaders = []; }
200 >
201 > private manifestRef = 0;
202 > private collectionCounter = 0;
203 >
204 > constructor(private readonly rateLimit = Number.MAX_SAFE_INTEGER, private readonly retryAfter?: number) { }
205 >
206 > async resolveProxy(url: string): Promise<string | undefined> { return url; }
207 > async lookupAuthorization(authInfo: AuthInfo): Promise<Credentials | undefined> { return undefined; }
208 > async lookupKerberosAuthorization(url: string): Promise<string | undefined> { return undefined; }
209 > async loadCertificates(): Promise<string[]> { return []; }
210 >
211 > async request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext> {
212 > if (this._requests.length === this.rateLimit) { userDataSyncClient.ts
213 return this.toResponse(429, this.retryAfter ? { 'retry-after': `${this.retryAfter}` } : undefined);
214 }
215 > const headers: IHeaders = {}; userDataSyncClient.ts
216 > if (options.headers) {
217 > if (options.headers['If-None-Match']) {
218 headers['If-None-Match'] = options.headers['If-None-Match'];
219 }
220 > if (options.headers['If-Match']) { userDataSyncClient.ts
221 > headers['If-Match'] = options.headers['If-Match']; userDataSyncClient.ts
222 > }
224 > this._requests.push({ url: options.url!, type: options.type!, headers });
225 > this._requestsWithAllHeaders.push({ url: options.url!, type: options.type!, headers: options.headers });
226 > const requestContext = await this.doRequest(options);
227 > this._responses.push({ status: requestContext.res.statusCode! });
228 > return requestContext;
229 > }
231 > private async doRequest(options: IRequestOptions): Promise<IRequestContext> {
232 > const versionUrl = `${this.url}/v1/`; userDataSyncClient.ts
233 > const relativePath = options.url!.indexOf(versionUrl) === 0 ? options.url!.substring(versionUrl.length) : undefined;
234 > const segments = relativePath ? relativePath.split('/') : [];
235 > if (options.type === 'GET' && segments.length === 1 && segments[0] === 'manifest') {
236 > return this.getManifest(options.headers); userDataSyncClient.ts
237 > }
238 > if (options.type === 'GET' && segments.length === 3 && segments[0] === 'resource') { userDataSyncClient.ts
239 return this.getResourceData(undefined, segments[1], segments[2] === 'latest' ? undefined : segments[2], options.headers);
240 }
241 > if (options.type === 'POST' && segments.length === 2 && segments[0] === 'resource') { userDataSyncClient.ts
242 > return this.writeData(undefined, segments[1], options.data, options.headers); userDataSyncClient.ts
243 > }
244 > // resources in collection userDataSyncClient.ts
245 > if (options.type === 'GET' && segments.length === 5 && segments[0] === 'collection' && segments[2] === 'resource') { userDataSyncClient.ts
246 return this.getResourceData(segments[1], segments[3], segments[4] === 'latest' ? undefined : segments[4], options.headers);
247 }
248 > if (options.type === 'POST' && segments.length === 4 && segments[0] === 'collection' && segments[2] === 'resource') { userDataSyncClient.ts
249 return this.writeData(segments[1], segments[3], options.data, options.headers);
250 }
251 > if (options.type === 'DELETE' && segments.length === 2 && segments[0] === 'resource') { userDataSyncClient.ts
252 return this.deleteResourceData(undefined, segments[1]);
253 }
254 > if (options.type === 'DELETE' && segments.length === 1 && segments[0] === 'resource') { userDataSyncClient.ts
255 > return this.clear(options.headers); userDataSyncClient.ts
256 > }
257 > if (options.type === 'DELETE' && segments[0] === 'collection') { userDataSyncClient.ts
258 > return this.toResponse(204); userDataSyncClient.ts
259 > }
260 > if (options.type === 'POST' && segments.length === 1 && segments[0] === 'collection') { userDataSyncClient.ts
261 return this.createCollection();
262 }
263 return this.toResponse(501);
266 > private async getManifest(headers?: IHeaders): Promise<IRequestContext> {
267 > if (this.session) { userDataSyncClient.ts
268 const latest: Record<ServerResource, string> = Object.create({});
269 this.data.forEach((value, key) => latest[key] = value.ref);
283 return this.toResponse(200, { 'Content-Type': 'application/json', etag: `${this.manifestRef++}` }, JSON.stringify(manifest));
284 }
285 > return this.toResponse(204, { etag: `${this.manifestRef++}` }); userDataSyncClient.ts
286 > }
288 > private async getResourceData(collection: string | undefined, resource: string, ref?: string, headers: IHeaders = {}): Promise<IRequestContext> {
289 const collectionData = collection ? this.collections.get(collection) : this.data;
290 if (!collectionData) {
308 return this.toResponse(204);
309 }
311 > private async writeData(collection: string | undefined, resource: string, content: string = '', headers: IHeaders = {}): Promise<IRequestContext> {
312 > if (!this.session) { userDataSyncClient.ts
313 > this.session = generateUuid();
314 > }
315 > const collectionData = collection ? this.collections.get(collection) : this.data;
316 > if (!collectionData) {
317 return this.toResponse(501);
318 }
319 > const resourceKey = ALL_SERVER_RESOURCES.find(key => key === resource); userDataSyncClient.ts
320 > if (resourceKey) {
321 > const data = collectionData.get(resourceKey);
322 > if (headers['If-Match'] !== undefined && headers['If-Match'] !== (data ? data.ref : '0')) {
323 return this.toResponse(412);
324 }
325 > const ref = `${parseInt(data?.ref || '0') + 1}`; userDataSyncClient.ts
326 > collectionData.set(resourceKey, { ref, content });
327 > return this.toResponse(200, { etag: ref });
328 > }
329 return this.toResponse(204);
332 > private async deleteResourceData(collection: string | undefined, resource: string, headers: IHeaders = {}): Promise<IRequestContext> {
333 const collectionData = collection ? this.collections.get(collection) : this.data;
334 if (!collectionData) {
344 return this.toResponse(404);
345 }
347 > private async createCollection(): Promise<IRequestContext> {
348 const collectionId = `${++this.collectionCounter}`;
349 this.collections.set(collectionId, new Map());
350 return this.toResponse(200, {}, collectionId);
351 }
353 > async clear(headers?: IHeaders): Promise<IRequestContext> {
354 > this.collections.clear(); userDataSyncClient.ts
355 > this.data.clear();
356 > this.session = null;
357 > this.collectionCounter = 0;
358 > return this.toResponse(204);
359 > }
361 > private toResponse(statusCode: number, headers?: IHeaders, data?: string): IRequestContext {
362 > return { userDataSyncClient.ts
363 > res: {
364 > headers: headers || {},
365 > statusCode
366 > },
367 > stream: bufferToStream(VSBuffer.fromString(data || ''))
368 > };
369 > }
371 >
372 > export class TestUserDataSyncUtilService implements IUserDataSyncUtilService {
373 >
374 > _serviceBrand: undefined;
375 >
376 > async resolveDefaultCoreIgnoredSettings(): Promise<string[]> {
377 > return getDefaultIgnoredSettings(); userDataSyncClient.ts
378 > }
380 > async resolveUserBindings(userbindings: string[]): Promise<IStringDictionary<string>> {
381 const keys: IStringDictionary<string> = {};
382 for (const keybinding of userbindings) {
385 return keys;
386 }
388 > async resolveFormattingOptions(file?: URI): Promise<FormattingOptions> {
389 > return { eol: '\n', insertSpaces: false, tabSize: 4 }; userDataSyncClient.ts
390 > }
392 > }
393 >
394 > class TestStorageService extends InMemoryStorageService {
395 > constructor(private readonly profileStorageProfile: IUserDataProfile) {
396 > super(); userDataSyncClient.ts
397 > }
398 > override hasScope(profile: IUserDataProfile): boolean { userDataSyncClient.ts
399 > return this.profileStorageProfile.id === profile.id; userDataSyncClient.ts
400 > }
src/vs/base/common/resources.ts 304 covered LOC · 53 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- resources.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CharCode } from './charCode.js';
7 > import * as extpath from './extpath.js';
8 > import { Schemas } from './network.js';
9 > import * as paths from './path.js';
10 > import { isLinux, isWindows } from './platform.js';
11 > import { compare as strCompare, equalsIgnoreCase } from './strings.js';
12 > import { URI, uriToFsPath } from './uri.js';
13 >
14 > export function originalFSPath(uri: URI): string {
15 return uriToFsPath(uri, true);
16 }
18 > //#region IExtUri
19 >
20 > export interface IExtUri {
21 >
22 > // --- identity
23 >
24 > /**
25 > * Compares two uris.
26 > *
27 > * @param uri1 Uri
28 > * @param uri2 Uri
29 > * @param ignoreFragment Ignore the fragment (defaults to `false`)
30 > */
31 > compare(uri1: URI, uri2: URI, ignoreFragment?: boolean): number;
32 >
33 > /**
34 > * Tests whether two uris are equal
35 > *
36 > * @param uri1 Uri
37 > * @param uri2 Uri
38 > * @param ignoreFragment Ignore the fragment (defaults to `false`)
39 > */
40 > isEqual(uri1: URI | undefined, uri2: URI | undefined, ignoreFragment?: boolean): boolean;
41 >
42 > /**
43 > * Tests whether a `candidate` URI is a parent or equal of a given `base` URI.
44 > *
45 > * @param base A uri which is "longer" or at least same length as `parentCandidate`
46 > * @param parentCandidate A uri which is "shorter" or up to same length as `base`
47 > * @param ignoreFragment Ignore the fragment (defaults to `false`)
48 > */
49 > isEqualOrParent(base: URI, parentCandidate: URI, ignoreFragment?: boolean): boolean;
50 >
51 > /**
52 > * Creates a key from a resource URI to be used to resource comparison and for resource maps.
53 > * @see {@link ResourceMap}
54 > * @param uri Uri
55 > * @param ignoreFragment Ignore the fragment (defaults to `false`)
56 > */
57 > getComparisonKey(uri: URI, ignoreFragment?: boolean): string;
58 >
59 > /**
60 > * Whether the casing of the path-component of the uri should be ignored.
61 > */
62 > ignorePathCasing(uri: URI): boolean;
63 >
64 > // --- path math
65 >
66 > basenameOrAuthority(resource: URI): string;
67 >
68 > /**
69 > * Returns the basename of the path component of an uri.
70 > * @param resource
71 > */
72 > basename(resource: URI): string;
73 >
74 > /**
75 > * Returns the extension of the path component of an uri.
76 > * @param resource
77 > */
78 > extname(resource: URI): string;
79 > /**
80 > * Return a URI representing the directory of a URI path.
81 > *
82 > * @param resource The input URI.
83 > * @returns The URI representing the directory of the input URI.
84 > */
85 > dirname(resource: URI): URI;
86 > /**
87 > * Join a URI path with path fragments and normalizes the resulting path.
88 > *
89 > * @param resource The input URI.
90 > * @param pathFragment The path fragment to add to the URI path.
91 > * @returns The resulting URI.
92 > */
93 > joinPath(resource: URI, ...pathFragment: string[]): URI;
94 > /**
95 > * Normalizes the path part of a URI: Resolves `.` and `..` elements with directory names.
96 > *
97 > * @param resource The URI to normalize the path.
98 > * @returns The URI with the normalized path.
99 > */
100 > normalizePath(resource: URI): URI;
101 > /**
102 > *
103 > * @param from
104 > * @param to
105 > */
106 > relativePath(from: URI, to: URI): string | undefined;
107 > /**
108 > * Resolves an absolute or relative path against a base URI.
109 > * The path can be relative or absolute posix or a Windows path
110 > */
111 > resolvePath(base: URI, path: string): URI;
112 >
113 > // --- misc
114 >
115 > /**
116 > * Returns true if the URI path is absolute.
117 > */
118 > isAbsolutePath(resource: URI): boolean;
119 > /**
120 > * Tests whether the two authorities are the same
121 > */
122 > isEqualAuthority(a1: string, a2: string): boolean;
123 > /**
124 > * Returns true if the URI path has a trailing path separator
125 > */
126 > hasTrailingPathSeparator(resource: URI, sep?: string): boolean;
127 > /**
128 > * Removes a trailing path separator, if there's one.
129 > * Important: Doesn't remove the first slash, it would make the URI invalid
130 > */
131 > removeTrailingPathSeparator(resource: URI, sep?: string): URI;
132 > /**
133 > * Adds a trailing path separator to the URI if there isn't one already.
134 > * For example, c:\ would be unchanged, but c:\users would become c:\users\
135 > */
136 > addTrailingPathSeparator(resource: URI, sep?: string): URI;
137 > }
138 >
139 > export class ExtUri implements IExtUri {
140 >
141 > constructor(private _ignorePathCasing: (uri: URI) => boolean) { }
142 >
143 > compare(uri1: URI, uri2: URI, ignoreFragment: boolean = false): number {
144 if (uri1 === uri2) {
145 return 0;
147 return strCompare(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment));
148 }
149 > resources.ts
150 > isEqual(uri1: URI | undefined, uri2: URI | undefined, ignoreFragment: boolean = false): boolean {
151 > if (uri1 === uri2) { resources.ts
152 > return true; resources.ts
153 > }
154 > if (!uri1 || !uri2) { resources.ts
155 return false;
156 }
157 > return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment); resources.ts
158 > } resources.ts
159 > resources.ts
160 > getComparisonKey(uri: URI, ignoreFragment: boolean = false): string {
161 > return uri.with({ resources.ts
162 > path: this._ignorePathCasing(uri) ? uri.path.toLowerCase() : undefined,
163 > fragment: ignoreFragment ? null : undefined
164 > }).toString();
165 > }
166 > resources.ts
167 > ignorePathCasing(uri: URI): boolean {
168 return this._ignorePathCasing(uri);
169 }
170 > resources.ts
171 > isEqualOrParent(base: URI, parentCandidate: URI, ignoreFragment: boolean = false): boolean {
172 > if (base.scheme === parentCandidate.scheme) { resources.ts
173 > if (base.scheme === Schemas.file) { resources.ts
174 return extpath.isEqualOrParent(originalFSPath(base), originalFSPath(parentCandidate), this._ignorePathCasing(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
175 }
176 > if (isEqualAuthority(base.authority, parentCandidate.authority)) { resources.ts
177 > return extpath.isEqualOrParent(base.path, parentCandidate.path, this._ignorePathCasing(base), true) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment);
178 > }
179 > } resources.ts
180 > return false; resources.ts
181 > } resources.ts
182 > resources.ts
183 > // --- path math
184 >
185 > joinPath(resource: URI, ...pathFragment: string[]): URI {
186 > return URI.joinPath(resource, ...pathFragment); resources.ts
187 > }
188 > resources.ts
189 > basenameOrAuthority(resource: URI): string {
190 return basename(resource) || resource.authority;
191 }
192 > resources.ts
193 > basename(resource: URI, suffix?: string): string {
194 > return paths.posix.basename(resource.path, suffix); resources.ts
195 > }
196 > resources.ts
197 > extname(resource: URI): string {
198 > return paths.posix.extname(resource.path); resources.ts
199 > }
200 > resources.ts
201 > dirname(resource: URI): URI {
202 > if (resource.path.length === 0) { resources.ts
203 return resource;
204 }
205 > let dirname; resources.ts
206 > if (resource.scheme === Schemas.file) {
207 dirname = URI.file(paths.dirname(originalFSPath(resource))).path;
208 > } else { resources.ts
209 > dirname = paths.posix.dirname(resource.path); resources.ts
210 > if (resource.authority && dirname.length && dirname.charCodeAt(0) !== CharCode.Slash) {
211 console.error(`dirname("${resource.toString})) resulted in a relative path`);
212 dirname = '/'; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character
213 }
214 > } resources.ts
215 > return resource.with({ resources.ts
216 > path: dirname
217 > });
218 > }
219 > resources.ts
220 > normalizePath(resource: URI): URI {
221 if (!resource.path.length) {
222 return resource;
232 });
233 }
234 > resources.ts
235 > relativePath(from: URI, to: URI): string | undefined {
236 > if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) { resources.ts
237 return undefined;
238 }
239 > if (from.scheme === Schemas.file) { resources.ts
240 const relativePath = paths.relative(originalFSPath(from), originalFSPath(to));
241 return isWindows ? extpath.toSlashes(relativePath) : relativePath;
242 }
243 > let fromPath = from.path || '/'; resources.ts
244 > const toPath = to.path || '/'; resources.ts
245 > if (this._ignorePathCasing(from)) {
246 // make casing of fromPath match toPath
247 let i = 0;
255 fromPath = toPath.substr(0, i) + fromPath.substr(i);
256 }
257 > return paths.posix.relative(fromPath, toPath); resources.ts
258 > } resources.ts
259 > resources.ts
260 > resolvePath(base: URI, path: string): URI {
261 if (base.scheme === Schemas.file) {
262 const newURI = URI.file(paths.resolve(originalFSPath(base), path));
271 });
272 }
273 > resources.ts
274 > // --- misc
275 >
276 > isAbsolutePath(resource: URI): boolean {
277 > return !!resource.path && resource.path[0] === '/'; resources.ts
278 > }
279 > resources.ts
280 > isEqualAuthority(a1: string | undefined, a2: string | undefined) {
281 > return a1 === a2 || (a1 !== undefined && a2 !== undefined && equalsIgnoreCase(a1, a2)); resources.ts
282 > }
283 > resources.ts
284 > hasTrailingPathSeparator(resource: URI, sep: string = paths.sep): boolean {
285 if (resource.scheme === Schemas.file) {
286 const fsp = originalFSPath(resource);
291 }
292 }
293 > resources.ts
294 > removeTrailingPathSeparator(resource: URI, sep: string = paths.sep): URI {
295 // Make sure that the path isn't a drive letter. A trailing separator there is not removable.
296 if (hasTrailingPathSeparator(resource, sep)) {
299 return resource;
300 }
301 > resources.ts
302 > addTrailingPathSeparator(resource: URI, sep: string = paths.sep): URI {
303 let isRootSep: boolean = false;
304 if (resource.scheme === Schemas.file) {
315 return resource;
316 }
317 > } resources.ts
318 >
319 >
320 > /**
321 > * Unbiased utility that takes uris "as they are". This means it can be interchanged with
322 > * uri#toString() usages. The following is true
323 > * ```
324 > * assertEqual(aUri.toString() === bUri.toString(), exturi.isEqual(aUri, bUri))
325 > * ```
326 > */
327 > export const extUri = new ExtUri(() => false);
328 >
329 > /**
330 > * BIASED utility that _mostly_ ignored the case of urs paths. ONLY use this util if you
331 > * understand what you are doing.
332 > *
333 > * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged.
334 > *
335 > * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient
336 > * because those uris come from a "trustworthy source". When creating unknown uris it's always
337 > * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path
338 > * casing matters.
339 > */
340 > export const extUriBiasedIgnorePathCase = new ExtUri(uri => {
341 > // A file scheme resource is in the same platform as code, so ignore case for non linux platforms resources.ts
342 > // Resource can be from another platform. Lowering the case as an hack. Should come from File system provider
343 > return uri.scheme === Schemas.file ? !isLinux : true;
344 > });
345 > resources.ts
346 >
347 > /**
348 > * BIASED utility that always ignores the casing of uris paths. ONLY use this util if you
349 > * understand what you are doing.
350 > *
351 > * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged.
352 > *
353 > * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient
354 > * because those uris come from a "trustworthy source". When creating unknown uris it's always
355 > * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path
356 > * casing matters.
357 > */
358 > export const extUriIgnorePathCase = new ExtUri(_ => true);
359 >
360 > export const isEqual = extUri.isEqual.bind(extUri);
361 > export const isEqualOrParent = extUri.isEqualOrParent.bind(extUri);
362 > export const getComparisonKey = extUri.getComparisonKey.bind(extUri);
363 > export const basenameOrAuthority = extUri.basenameOrAuthority.bind(extUri);
364 > export const basename = extUri.basename.bind(extUri);
365 > export const extname = extUri.extname.bind(extUri);
366 > export const dirname = extUri.dirname.bind(extUri);
367 > export const joinPath = extUri.joinPath.bind(extUri);
368 > export const normalizePath = extUri.normalizePath.bind(extUri);
369 > export const relativePath = extUri.relativePath.bind(extUri);
370 > export const resolvePath = extUri.resolvePath.bind(extUri);
371 > export const isAbsolutePath = extUri.isAbsolutePath.bind(extUri);
372 > export const isEqualAuthority = extUri.isEqualAuthority.bind(extUri);
373 > export const hasTrailingPathSeparator = extUri.hasTrailingPathSeparator.bind(extUri);
374 > export const removeTrailingPathSeparator = extUri.removeTrailingPathSeparator.bind(extUri);
375 > export const addTrailingPathSeparator = extUri.addTrailingPathSeparator.bind(extUri);
376 >
377 > //#endregion
378 >
379 > export function distinctParents<T>(items: T[], resourceAccessor: (item: T) => URI): T[] {
380 const distinctParents: T[] = [];
381 for (let i = 0; i < items.length; i++) {
396 return distinctParents;
397 }
398 > resources.ts
399 > /**
400 > * Data URI related helpers.
401 > */
402 > export namespace DataUri {
403 >
404 > export const META_DATA_LABEL = 'label';
405 > export const META_DATA_DESCRIPTION = 'description';
406 > export const META_DATA_SIZE = 'size';
407 > export const META_DATA_MIME = 'mime';
408 >
409 > export function parseMetaData(dataUri: URI): Map<string, string> {
410 const metadata = new Map<string, string>();
411
429 return metadata;
430 }
431 > } resources.ts
432 >
433 > export function toLocalResource(resource: URI, authority: string | undefined, localScheme: string): URI {
434 if (authority) {
435 let path = resource.path;
src/vs/base/common/types.ts 299 covered LOC · 31 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- types.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { assert } from './assert.js';
7 >
8 > /**
9 > * @returns whether the provided parameter is a JavaScript String or not.
10 > */
11 > export function isString(str: unknown): str is string {
12 > return (typeof str === 'string'); types.ts
13 > }
14 > types.ts
15 > /**
16 > * @returns whether the provided parameter is a JavaScript Array and each element in the array is a string.
17 > */
18 > export function isStringArray(value: unknown): value is string[] {
19 return isArrayOf(value, isString);
20 }
21 > types.ts
22 > /**
23 > * @returns whether the provided parameter is a JavaScript Array and each element in the array satisfies the provided type guard.
24 > */
25 > export function isArrayOf<T>(value: unknown, check: (item: unknown) => item is T): value is T[] {
26 return Array.isArray(value) && value.every(check);
27 }
28 > types.ts
29 > /**
30 > * @returns whether the provided parameter is of type `object` but **not**
31 > * `null`, an `array`, a `regexp`, nor a `date`.
32 > */
33 > export function isObject(obj: unknown): obj is Object {
34 > // The method can't do a type cast since there are type (like strings) which types.ts
35 > // are subclasses of any put not positvely matched by the function. Hence type
36 > // narrowing results in wrong results.
37 > return typeof obj === 'object'
38 > && obj !== null types.ts
39 > && !Array.isArray(obj)
40 > && !(obj instanceof RegExp) types.ts
41 > && !(obj instanceof Date);
42 > } types.ts
43 > types.ts
44 > /**
45 > * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type
46 > */
47 > export function isTypedArray(obj: unknown): obj is Object {
48 const TypedArray = Object.getPrototypeOf(Uint8Array);
49 return typeof obj === 'object'
50 && obj instanceof TypedArray;
51 }
52 > types.ts
53 > /**
54 > * In **contrast** to just checking `typeof` this will return `false` for `NaN`.
55 > * @returns whether the provided parameter is a JavaScript Number or not.
56 > */
57 > export function isNumber(obj: unknown): obj is number {
58 return (typeof obj === 'number' && !isNaN(obj));
59 }
60 > types.ts
61 > /**
62 > * @returns whether the provided parameter is an Iterable, casting to the given generic
63 > */
64 > export function isIterable<T>(obj: unknown): obj is Iterable<T> {
65 // eslint-disable-next-line local/code-no-any-casts
66 return !!obj && typeof (obj as any)[Symbol.iterator] === 'function';
67 }
68 > types.ts
69 > /**
70 > * @returns whether the provided parameter is an Iterable, casting to the given generic
71 > */
72 > export function isAsyncIterable<T>(obj: unknown): obj is AsyncIterable<T> {
73 // eslint-disable-next-line local/code-no-any-casts
74 return !!obj && typeof (obj as any)[Symbol.asyncIterator] === 'function';
75 }
76 > types.ts
77 > /**
78 > * @returns whether the provided parameter is a JavaScript Boolean or not.
79 > */
80 > export function isBoolean(obj: unknown): obj is boolean {
81 return (obj === true || obj === false);
82 }
83 > types.ts
84 > /**
85 > * @returns whether the provided parameter is undefined.
86 > */
87 > export function isUndefined(obj: unknown): obj is undefined {
88 > return (typeof obj === 'undefined'); types.ts
89 > }
90 > types.ts
91 > /**
92 > * @returns whether the provided parameter is defined.
93 > */
94 > export function isDefined<T>(arg: T | null | undefined): arg is T {
95 return !isUndefinedOrNull(arg);
96 }
97 > types.ts
98 > /**
99 > * @returns whether the provided parameter is undefined or null.
100 > */
101 > export function isUndefinedOrNull(obj: unknown): obj is undefined | null {
102 > return (isUndefined(obj) || obj === null); types.ts
103 > }
104 > types.ts
105 >
106 > export function assertType(condition: unknown, type?: string): asserts condition {
107 if (!condition) {
108 throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type');
109 }
110 }
111 > types.ts
112 > /**
113 > * Asserts that the argument passed in is neither undefined nor null.
114 > *
115 > * @see {@link assertDefined} for a similar utility that leverages TS assertion functions to narrow down the type of `arg` to be non-nullable.
116 > */
117 > export function assertReturnsDefined<T>(arg: T | null | undefined): NonNullable<T> {
118 assert(
119 arg !== null && arg !== undefined,
123 return arg;
124 }
125 > types.ts
126 > /**
127 > * Asserts that a provided `value` is `defined` - not `null` or `undefined`,
128 > * throwing an error with the provided error or error message, while also
129 > * narrowing down the type of the `value` to be `NonNullable` using TS
130 > * assertion functions.
131 > *
132 > * @throws if the provided `value` is `null` or `undefined`.
133 > *
134 > * ## Examples
135 > *
136 > * ```typescript
137 > * // an assert with an error message
138 > * assertDefined('some value', 'String constant is not defined o_O.');
139 > *
140 > * // `throws!` the provided error
141 > * assertDefined(null, new Error('Should throw this error.'));
142 > *
143 > * // narrows down the type of `someValue` to be non-nullable
144 > * const someValue: string | undefined | null = blackbox();
145 > * assertDefined(someValue, 'Some value must be defined.');
146 > * console.log(someValue.length); // now type of `someValue` is `string`
147 > * ```
148 > *
149 > * @see {@link assertReturnsDefined} for a similar utility but without assertion.
150 > * @see {@link https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions typescript-3-7.html#assertion-functions}
151 > */
152 > export function assertDefined<T>(value: T, error: string | NonNullable<Error>): asserts value is NonNullable<T> {
153 if (value === null || value === undefined) {
154 const errorToThrow = typeof error === 'string' ? new Error(error) : error;
157 }
158 }
159 > types.ts
160 > /**
161 > * Asserts that each argument passed in is neither undefined nor null.
162 > */
163 > export function assertReturnsAllDefined<T1, T2>(t1: T1 | null | undefined, t2: T2 | null | undefined): [T1, T2];
164 > export function assertReturnsAllDefined<T1, T2, T3>(t1: T1 | null | undefined, t2: T2 | null | undefined, t3: T3 | null | undefined): [T1, T2, T3];
165 > export function assertReturnsAllDefined<T1, T2, T3, T4>(t1: T1 | null | undefined, t2: T2 | null | undefined, t3: T3 | null | undefined, t4: T4 | null | undefined): [T1, T2, T3, T4];
166 > export function assertReturnsAllDefined(...args: (unknown | null | undefined)[]): unknown[] {
167 const result = [];
168
179 return result;
180 }
181 > types.ts
182 > /**
183 > * Checks if the provided value is one of the vales in the provided list.
184 > *
185 > * ## Examples
186 > *
187 > * ```typescript
188 > * // note! item type is a `subset of string`
189 > * type TItem = ':' | '.' | '/';
190 > *
191 > * // note! item is type of `string` here
192 > * const item: string = ':';
193 > * // list of the items to check against
194 > * const list: TItem[] = [':', '.'];
195 > *
196 > * // ok
197 > * assert(
198 > * isOneOf(item, list),
199 > * 'Must succeed.',
200 > * );
201 > *
202 > * // `item` is of `TItem` type now
203 > * ```
204 > */
205 > export const isOneOf = <TType, TSubtype extends TType>(
206 value: TType,
207 validValues: readonly TSubtype[],
211 return validValues.includes(<TSubtype>value);
212 };
213 > types.ts
214 > /**
215 > * Compile-time type check of a variable.
216 > */
217 > export function typeCheck<T = never>(_thing: NoInfer<T>): void { }
218 >
219 > const hasOwnProperty = Object.prototype.hasOwnProperty;
220 >
221 > /**
222 > * @returns whether the provided parameter is an empty JavaScript Object or not.
223 > */
224 > export function isEmptyObject(obj: unknown): obj is object {
225 if (!isObject(obj)) {
226 return false;
235 return true;
236 }
237 > types.ts
238 > /**
239 > * @returns whether the provided parameter is a JavaScript Function or not.
240 > */
241 > export function isFunction(obj: unknown): obj is Function {
242 return (typeof obj === 'function');
243 }
244 > types.ts
245 > /**
246 > * @returns whether the provided parameters is are JavaScript Function or not.
247 > */
248 > export function areFunctions(...objects: unknown[]): boolean {
249 return objects.length > 0 && objects.every(isFunction);
250 }
251 > types.ts
252 > export type TypeConstraint = string | Function;
253 >
254 > export function validateConstraints(args: unknown[], constraints: Array<TypeConstraint | undefined>): void {
255 const len = Math.min(args.length, constraints.length);
256 for (let i = 0; i < len; i++) {
258 }
259 }
260 > types.ts
261 > export function validateConstraint(arg: unknown, constraint: TypeConstraint | undefined): void {
262
263 if (isString(constraint)) {
283 }
284 }
285 > types.ts
286 > /**
287 > * Helper type assertion that safely upcasts a type to a supertype.
288 > *
289 > * This can be used to make sure the argument correctly conforms to the subtype while still being able to pass it
290 > * to contexts that expects the supertype.
291 > */
292 > export function upcast<Base, Sub extends Base = Base>(x: Sub): Base {
293 return x;
294 }
295 > types.ts
296 > type AddFirstParameterToFunction<T, TargetFunctionsReturnType, FirstParameter> = T extends (...args: any[]) => TargetFunctionsReturnType ?
297 > // Function: add param to function
298 > (firstArg: FirstParameter, ...args: Parameters<T>) => ReturnType<T> :
299 >
300 > // Else: just leave as is
301 > T;
302 >
303 > /**
304 > * Allows to add a first parameter to functions of a type.
305 > */
306 > export type AddFirstParameterToFunctions<Target, TargetFunctionsReturnType, FirstParameter> = {
307 > // For every property
308 > [K in keyof Target]: AddFirstParameterToFunction<Target[K], TargetFunctionsReturnType, FirstParameter>;
309 > };
310 >
311 > /**
312 > * Given an object with all optional properties, requires at least one to be defined.
313 > * i.e. AtLeastOne<MyObject>;
314 > */
315 > export type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U];
316 >
317 > /**
318 > * Only picks the non-optional properties of a type.
319 > */
320 > export type OmitOptional<T> = { [K in keyof T as T[K] extends Required<T>[K] ? K : never]: T[K] };
321 >
322 > /**
323 > * A type that removed readonly-less from all properties of `T`
324 > */
325 > export type Mutable<T> = {
326 > -readonly [P in keyof T]: T[P]
327 > };
328 >
329 > /**
330 > * A type that adds readonly to all properties of T, recursively.
331 > */
332 > export type DeepImmutable<T> = T extends (infer U)[]
333 > ? ReadonlyArray<DeepImmutable<U>>
334 > : T extends ReadonlyArray<infer U>
335 > ? ReadonlyArray<DeepImmutable<U>>
336 > : T extends Map<infer K, infer V>
337 > ? ReadonlyMap<K, DeepImmutable<V>>
338 > : T extends Set<infer U>
339 > ? ReadonlySet<DeepImmutable<U>>
340 > : T extends object
341 > ? {
342 > readonly [K in keyof T]: DeepImmutable<T[K]>;
343 > }
344 > : T;
345 >
346 > /**
347 > * A single object or an array of the objects.
348 > */
349 > export type SingleOrMany<T> = T | T[];
350 >
351 > /**
352 > * Given a `type X = { foo?: string }` checking that an object `satisfies X`
353 > * will ensure each property was explicitly defined, ensuring no properties
354 > * are omitted or forgotten.
355 > */
356 > export type WithDefinedProps<T> = { [K in keyof Required<T>]: T[K] };
357 >
358 >
359 > /**
360 > * A type that recursively makes all properties of `T` required
361 > */
362 > export type DeepRequiredNonNullable<T> = {
363 > [P in keyof T]-?: T[P] extends object ? DeepRequiredNonNullable<T[P]> : Required<NonNullable<T[P]>>;
364 > };
365 >
366 >
367 > /**
368 > * Represents a type that is a partial version of a given type `T`, where all properties are optional and can be deeply nested.
369 > */
370 > export type DeepPartial<T> = {
371 > [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : Partial<T[P]>;
372 > };
373 >
374 > /**
375 > * Represents a type that is a partial version of a given type `T`, except a subset.
376 > */
377 > export type PartialExcept<T, K extends keyof T> = Partial<Omit<T, K>> & Pick<T, K>;
378 >
379 >
380 > type KeysOfUnionType<T> = T extends T ? keyof T : never;
381 > type FilterType<T, TTest> = T extends TTest ? T : never;
382 > type MakeOptionalAndTrue<T extends object> = { [K in keyof T]?: true };
383 >
384 > /**
385 > * Type guard that checks if an object has specific keys and narrows the type accordingly.
386 > *
387 > * @param x - The object to check
388 > * @param key - An object with boolean values indicating which keys to check for
389 > * @returns true if all specified keys exist in the object, false otherwise
390 > *
391 > * @example
392 > * ```typescript
393 > * type A = { a: string };
394 > * type B = { b: number };
395 > * const obj: A | B = getObject();
396 > *
397 > * if (hasKey(obj, { a: true })) {
398 > * // obj is now narrowed to type A
399 > * console.log(obj.a);
400 > * }
401 > * ```
402 > */
403 > export function hasKey<T extends object, TKeys extends MakeOptionalAndTrue<T>>(x: T, key: TKeys): x is FilterType<T, { [K in KeysOfUnionType<T> & keyof TKeys]: unknown }> {
404 for (const k in key) {
405 if (!(k in x)) {
src/vs/base/common/network.ts 292 covered LOC · 20 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- network.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as errors from './errors.js';
7 > import * as platform from './platform.js';
8 > import { equalsIgnoreCase, startsWithIgnoreCase } from './strings.js';
9 > import { URI } from './uri.js';
10 > import * as paths from './path.js';
11 >
12 > export namespace Schemas {
13 >
14 > /**
15 > * A schema that is used for models that exist in memory
16 > * only and that have no correspondence on a server or such.
17 > */
18 > export const inMemory = 'inmemory';
19 >
20 > /**
21 > * A schema that is used for setting files
22 > */
23 > export const vscode = 'vscode';
24 >
25 > /**
26 > * A schema that is used for internal private files
27 > */
28 > export const internal = 'private';
29 >
30 > /**
31 > * A walk-through document.
32 > */
33 > export const walkThrough = 'walkThrough';
34 >
35 > /**
36 > * An embedded code snippet.
37 > */
38 > export const walkThroughSnippet = 'walkThroughSnippet';
39 >
40 > export const http = 'http';
41 >
42 > export const https = 'https';
43 >
44 > export const file = 'file';
45 >
46 > export const mailto = 'mailto';
47 >
48 > export const untitled = 'untitled';
49 >
50 > export const data = 'data';
51 >
52 > export const command = 'command';
53 >
54 > export const vscodeRemote = 'vscode-remote';
55 >
56 > export const vscodeRemoteResource = 'vscode-remote-resource';
57 >
58 > export const vscodeManagedRemoteResource = 'vscode-managed-remote-resource';
59 >
60 > export const vscodeUserData = 'vscode-userdata';
61 >
62 > export const vscodeCustomEditor = 'vscode-custom-editor';
63 >
64 > export const vscodeNotebookCell = 'vscode-notebook-cell';
65 > export const vscodeNotebookCellMetadata = 'vscode-notebook-cell-metadata';
66 > export const vscodeNotebookCellMetadataDiff = 'vscode-notebook-cell-metadata-diff';
67 > export const vscodeNotebookCellOutput = 'vscode-notebook-cell-output';
68 > export const vscodeNotebookCellOutputDiff = 'vscode-notebook-cell-output-diff';
69 > export const vscodeNotebookMetadata = 'vscode-notebook-metadata';
70 > export const vscodeInteractiveInput = 'vscode-interactive-input';
71 >
72 > export const vscodeSettings = 'vscode-settings';
73 >
74 > export const vscodeWorkspaceTrust = 'vscode-workspace-trust';
75 >
76 > export const vscodeTerminal = 'vscode-terminal';
77 >
78 > /** Scheme used for the image carousel editor. */
79 > export const vscodeImageCarousel = 'vscode-image-carousel';
80 >
81 > /** Scheme used for code blocks in chat. */
82 > export const vscodeChatCodeBlock = 'vscode-chat-code-block';
83 >
84 > /** Scheme used for LHS of code compare (aka diff) blocks in chat. */
85 > export const vscodeChatCodeCompareBlock = 'vscode-chat-code-compare-block';
86 >
87 > /** Scheme used for the chat input editor. */
88 > export const vscodeChatEditor = 'vscode-chat-editor';
89 >
90 > /** Scheme used for the chat input part */
91 > export const vscodeChatInput = 'chatSessionInput';
92 >
93 > /** Scheme used for local chat session content */
94 > export const vscodeLocalChatSession = 'vscode-chat-session';
95 >
96 > /**
97 > * Scheme used internally for webviews that aren't linked to a resource (i.e. not custom editors)
98 > */
99 > export const webviewPanel = 'webview-panel';
100 >
101 > /**
102 > * Scheme used for loading the wrapper html and script in webviews.
103 > */
104 > export const vscodeWebview = 'vscode-webview';
105 >
106 > /**
107 > * Scheme used for integrated browser tabs using WebContentsView.
108 > */
109 > export const vscodeBrowser = 'vscode-browser';
110 >
111 > /**
112 > * Scheme used for extension pages
113 > */
114 > export const extension = 'extension';
115 >
116 > /**
117 > * Scheme used as a replacement of `file` scheme to load
118 > * files with our custom protocol handler (desktop only).
119 > */
120 > export const vscodeFileResource = 'vscode-file';
121 >
122 > /**
123 > * Scheme used for temporary resources
124 > */
125 > export const tmp = 'tmp';
126 >
127 > /**
128 > * Scheme used vs live share
129 > */
130 > export const vsls = 'vsls';
131 >
132 > /**
133 > * Scheme used for the Source Control commit input's text document
134 > */
135 > export const vscodeSourceControl = 'vscode-scm';
136 >
137 > /**
138 > * Scheme used for input box for creating comments.
139 > */
140 > export const commentsInput = 'comment';
141 >
142 > /**
143 > * Scheme used for special rendering of settings in the release notes
144 > */
145 > export const codeSetting = 'code-setting';
146 >
147 > /**
148 > * Scheme used for output panel resources
149 > */
150 > export const outputChannel = 'output';
151 >
152 > /**
153 > * Scheme used for the accessible view
154 > */
155 > export const accessibleView = 'accessible-view';
156 >
157 > /**
158 > * Used for snapshots of chat edits
159 > */
160 > export const chatEditingSnapshotScheme = 'chat-editing-snapshot-text-model';
161 > export const chatEditingModel = 'chat-editing-text-model';
162 >
163 > /**
164 > * Used for rendering multidiffs in copilot agent sessions
165 > */
166 > export const copilotPr = 'copilot-pr';
167 > }
168 >
169 > export function matchesScheme(target: URI | string, scheme: string): boolean {
170 if (URI.isUri(target)) {
171 return equalsIgnoreCase(target.scheme, scheme);
174 }
175 }
176 > network.ts
177 > export function matchesSomeScheme(target: URI | string, ...schemes: string[]): boolean {
178 return schemes.some(scheme => matchesScheme(target, scheme));
179 }
180 > network.ts
181 > export const connectionTokenCookieName = 'vscode-tkn';
182 > export const connectionTokenQueryName = 'tkn';
183 >
184 > class RemoteAuthoritiesImpl {
185 > private readonly _hosts: { [authority: string]: string | undefined } = Object.create(null);
186 > private readonly _ports: { [authority: string]: number | undefined } = Object.create(null);
187 > private readonly _connectionTokens: { [authority: string]: string | undefined } = Object.create(null);
188 > private _preferredWebSchema: 'http' | 'https' = 'http';
189 > private _delegate: ((uri: URI) => URI) | null = null;
190 > private _serverRootPath: string = '/';
191 >
192 > setPreferredWebSchema(schema: 'http' | 'https') {
193 this._preferredWebSchema = schema;
194 }
195 > network.ts
196 > setDelegate(delegate: (uri: URI) => URI): void {
197 this._delegate = delegate;
198 }
199 > network.ts
200 > setServerRootPath(product: { quality?: string; commit?: string }, serverBasePath: string | undefined): void {
201 this._serverRootPath = paths.posix.join(serverBasePath ?? '/', getServerProductSegment(product));
202 }
203 > network.ts
204 > getServerRootPath(): string {
205 return this._serverRootPath;
206 }
207 > network.ts
208 > private get _remoteResourcesPath(): string {
209 return paths.posix.join(this._serverRootPath, Schemas.vscodeRemoteResource);
210 }
211 > network.ts
212 > set(authority: string, host: string, port: number): void {
213 this._hosts[authority] = host;
214 this._ports[authority] = port;
215 }
216 > network.ts
217 > setConnectionToken(authority: string, connectionToken: string): void {
218 this._connectionTokens[authority] = connectionToken;
219 }
220 > network.ts
221 > getPreferredWebSchema(): 'http' | 'https' {
222 return this._preferredWebSchema;
223 }
224 > network.ts
225 > rewrite(uri: URI): URI {
226 if (this._delegate) {
227 try {
250 });
251 }
252 > } network.ts
253 >
254 > export const RemoteAuthorities = new RemoteAuthoritiesImpl();
255 >
256 > export function getServerProductSegment(product: { quality?: string; commit?: string }) {
257 return `${product.quality ?? 'oss'}-${product.commit ?? 'dev'}`;
258 }
259 > network.ts
260 > /**
261 > * A string pointing to a path inside the app. It should not begin with ./ or ../
262 > */
263 > export type AppResourcePath = (
264 > `a${string}` | `b${string}` | `c${string}` | `d${string}` | `e${string}` | `f${string}`
265 > | `g${string}` | `h${string}` | `i${string}` | `j${string}` | `k${string}` | `l${string}`
266 > | `m${string}` | `n${string}` | `o${string}` | `p${string}` | `q${string}` | `r${string}`
267 > | `s${string}` | `t${string}` | `u${string}` | `v${string}` | `w${string}` | `x${string}`
268 > | `y${string}` | `z${string}`
269 > );
270 >
271 > export const builtinExtensionsPath: AppResourcePath = 'vs/../../extensions';
272 > export const nodeModulesPath: AppResourcePath = 'vs/../../node_modules';
273 > export const nodeModulesAsarPath: AppResourcePath = 'vs/../../node_modules.asar';
274 > export const nodeModulesAsarUnpackedPath: AppResourcePath = 'vs/../../node_modules.asar.unpacked';
275 >
276 > export const VSCODE_AUTHORITY = 'vscode-app';
277 >
278 > class FileAccessImpl {
279 >
280 > private static readonly FALLBACK_AUTHORITY = VSCODE_AUTHORITY;
281 >
282 > /**
283 > * Returns a URI to use in contexts where the browser is responsible
284 > * for loading (e.g. fetch()) or when used within the DOM.
285 > *
286 > * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context.
287 > */
288 > asBrowserUri(resourcePath: AppResourcePath | ''): URI {
289 const uri = this.toUri(resourcePath);
290 return this.uriToBrowserUri(uri);
291 }
292 > network.ts
293 > /**
294 > * Returns a URI to use in contexts where the browser is responsible
295 > * for loading (e.g. fetch()) or when used within the DOM.
296 > *
297 > * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context.
298 > */
299 > uriToBrowserUri(uri: URI): URI {
300 // Handle remote URIs via `RemoteAuthorities`
301 if (uri.scheme === Schemas.vscodeRemote) {
328 return uri;
329 }
330 > network.ts
331 > /**
332 > * Returns the `file` URI to use in contexts where node.js
333 > * is responsible for loading.
334 > */
335 > asFileUri(resourcePath: AppResourcePath | ''): URI {
336 const uri = this.toUri(resourcePath);
337 return this.uriToFileUri(uri);
338 }
339 > network.ts
340 > /**
341 > * Returns the `file` URI to use in contexts where node.js
342 > * is responsible for loading.
343 > */
344 > uriToFileUri(uri: URI): URI {
345 // Only convert the URI if it is `vscode-file:` scheme
346 if (uri.scheme === Schemas.vscodeFileResource) {
358 return uri;
359 }
360 > network.ts
361 > private toUri(uriOrModule: URI | string): URI {
362 if (URI.isUri(uriOrModule)) {
363 return uriOrModule;
379 throw new Error('Cannot determine URI for module id!');
380 }
381 > } network.ts
382 >
383 > export const FileAccess = new FileAccessImpl();
384 >
385 > export const CacheControlheaders: Record<string, string> = Object.freeze({
386 > 'Cache-Control': 'no-cache, no-store'
387 > });
388 >
389 > export const DocumentPolicyheaders: Record<string, string> = Object.freeze({
390 > 'Document-Policy': 'include-js-call-stacks-in-crash-reports'
391 > });
392 >
393 > export namespace COI {
394 >
395 > const coiHeaders = new Map<'3' | '2' | '1' | string, Record<string, string>>([
396 > ['1', { 'Cross-Origin-Opener-Policy': 'same-origin' }],
397 > ['2', { 'Cross-Origin-Embedder-Policy': 'require-corp' }],
398 > ['3', { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp' }],
399 > ]);
400 >
401 > export const CoopAndCoep = Object.freeze(coiHeaders.get('3'));
402 >
403 > const coiSearchParamName = 'vscode-coi';
404 >
405 > /**
406 > * Extract desired headers from `vscode-coi` invocation
407 > */
408 > export function getHeadersFromQuery(url: string | URI | URL): Record<string, string> | undefined {
409 let params: URLSearchParams | undefined;
410 if (typeof url === 'string') {
421 return coiHeaders.get(value);
422 }
423 > network.ts
424 > /**
425 > * Add the `vscode-coi` query attribute based on wanting `COOP` and `COEP`. Will be a noop when `crossOriginIsolated`
426 > * isn't enabled the current context
427 > */
428 > export function addSearchParam(urlOrSearch: URLSearchParams | Record<string, string>, coop: boolean, coep: boolean): void {
429 if (!(globalThis as typeof globalThis & { crossOriginIsolated?: boolean }).crossOriginIsolated) {
430 // depends on the current context being COI
src/vs/platform/request/common/request.ts 289 covered LOC · 20 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- request.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { streamToBuffer } from '../../../base/common/buffer.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { getErrorMessage } from '../../../base/common/errors.js';
9 > import { Emitter, Event } from '../../../base/common/event.js';
10 > import { Disposable } from '../../../base/common/lifecycle.js';
11 > import { IHeaders, IRequestContext, IRequestOptions } from '../../../base/parts/request/common/request.js';
12 > import { localize } from '../../../nls.js';
13 > import { ConfigurationScope, Extensions, IConfigurationNode, IConfigurationRegistry } from '../../configuration/common/configurationRegistry.js';
14 > import { createDecorator } from '../../instantiation/common/instantiation.js';
15 > import { ILogService } from '../../log/common/log.js';
16 > import { Registry } from '../../registry/common/platform.js';
17 >
18 > export const IRequestService = createDecorator<IRequestService>('requestService');
19 >
20 > /**
21 > * Use as the {@link IRequestOptions.callSite} value to prevent
22 > * request telemetry from being emitted. This is needed for
23 > * callers such as the telemetry sender to avoid cyclical calls.
24 > */
25 > export const NO_FETCH_TELEMETRY = 'NO_FETCH_TELEMETRY';
26 >
27 > export interface IRequestCompleteEvent {
28 > readonly callSite: string;
29 > readonly latency: number;
30 > readonly statusCode: number | undefined;
31 > }
32 >
33 > export interface AuthInfo {
34 > isProxy: boolean;
35 > scheme: string;
36 > host: string;
37 > port: number;
38 > realm: string;
39 > attempt: number;
40 > }
41 >
42 > export interface Credentials {
43 > username: string;
44 > password: string;
45 > }
46 >
47 > export interface IRequestService {
48 > readonly _serviceBrand: undefined;
49 >
50 > /**
51 > * Fires when a request completes (successfully or with an error response).
52 > */
53 > readonly onDidCompleteRequest: Event<IRequestCompleteEvent>;
54 >
55 > request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext>;
56 >
57 > resolveProxy(url: string): Promise<string | undefined>;
58 > lookupAuthorization(authInfo: AuthInfo): Promise<Credentials | undefined>;
59 > lookupKerberosAuthorization(url: string): Promise<string | undefined>;
60 > loadCertificates(): Promise<string[]>;
61 > }
62 >
63 > class LoggableHeaders {
64 >
65 > private headers: IHeaders | undefined;
66 >
67 > constructor(private readonly original: IHeaders) { }
68 >
69 > toJSON(): any {
70 if (!this.headers) {
71 const headers = Object.create(null);
81 return this.headers;
82 }
83 > request.ts
84 > }
85 >
86 > export abstract class AbstractRequestService extends Disposable implements IRequestService {
87 >
88 > declare readonly _serviceBrand: undefined;
89 >
90 > private counter = 0;
91 >
92 > private readonly _onDidCompleteRequest = this._register(new Emitter<IRequestCompleteEvent>());
93 > readonly onDidCompleteRequest = this._onDidCompleteRequest.event;
94 >
95 > constructor(protected readonly logService: ILogService) {
96 super();
97 }
98 > request.ts
99 > protected async logAndRequest(options: IRequestOptions, request: () => Promise<IRequestContext>): Promise<IRequestContext> {
100 const prefix = `#${++this.counter}: ${options.url}`;
101 this.logService.trace(`${prefix} - begin`, options.type, new LoggableHeaders(options.headers ?? {}));
115 }
116 }
117 > request.ts
118 > abstract request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext>;
119 > abstract resolveProxy(url: string): Promise<string | undefined>;
120 > abstract lookupAuthorization(authInfo: AuthInfo): Promise<Credentials | undefined>;
121 > abstract lookupKerberosAuthorization(url: string): Promise<string | undefined>;
122 > abstract loadCertificates(): Promise<string[]>;
123 > }
124 >
125 > export function isSuccess(context: IRequestContext): boolean {
126 > return (context.res.statusCode && context.res.statusCode >= 200 && context.res.statusCode < 300) || context.res.statusCode === 1223; request.ts
127 > }
128 > request.ts
129 > export function isClientError(context: IRequestContext): boolean {
130 return !!context.res.statusCode && context.res.statusCode >= 400 && context.res.statusCode < 500;
131 }
132 > request.ts
133 > export function isServerError(context: IRequestContext): boolean {
134 return !!context.res.statusCode && context.res.statusCode >= 500 && context.res.statusCode < 600;
135 }
136 > request.ts
137 > /**
138 > * Reads a header value from an {@link IHeaders} map, tolerating array-shaped
139 > * values and case-insensitive lookups.
140 > */
141 > export function readHeader(headers: IHeaders | undefined, name: string): string | undefined {
142 if (!headers) {
143 return undefined;
149 return value;
150 }
151 > request.ts
152 > /**
153 > * Parses the `Retry-After` header as a number of seconds. Returns `undefined`
154 > * if absent or not a finite positive number. The HTTP-date form is not parsed.
155 > */
156 > export function retryAfterFromHeaders(headers: IHeaders | undefined): number | undefined {
157 const value = readHeader(headers, 'retry-after');
158 if (!value) {
162 return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
163 }
164 > request.ts
165 > export function hasNoContent(context: IRequestContext): boolean {
166 > return context.res.statusCode === 204; request.ts
167 > }
168 > request.ts
169 > export async function asText(context: IRequestContext): Promise<string | null> { request.ts
170 > if (hasNoContent(context)) {
171 > return null;
172 > }
173 const buffer = await streamToBuffer(context.stream);
174 return buffer.toString();
175 }
176 > request.ts
177 > export async function asTextOrError(context: IRequestContext): Promise<string | null> { request.ts
178 > if (!isSuccess(context)) {
179 throw new Error('Server returned ' + context.res.statusCode);
180 }
181 > return asText(context); request.ts
182 > }
183 > request.ts
184 export async function asJson<T = {}>(context: IRequestContext): Promise<T | null> {
185 if (!isSuccess(context)) {
198 }
199 }
200 > request.ts
201 > export function updateProxyConfigurationsScope(useHostProxy: boolean, useHostProxyDefault: boolean): void {
202 registerProxyConfigurations(useHostProxy, useHostProxyDefault);
203 }
204 > request.ts
205 > export const USER_LOCAL_AND_REMOTE_SETTINGS = [
206 > 'http.proxy',
207 > 'http.proxyStrictSSL',
208 > 'http.proxyKerberosServicePrincipal',
209 > 'http.noProxy',
210 > 'http.proxyAuthorization',
211 > 'http.proxySupport',
212 > 'http.systemCertificates',
213 > 'http.systemCertificatesNode',
214 > 'http.experimental.systemCertificatesV2',
215 > 'http.fetchAdditionalSupport',
216 > 'http.experimental.networkInterfaceCheckInterval',
217 > ];
218 >
219 > export const systemCertificatesNodeDefault = false;
220 >
221 > let proxyConfiguration: IConfigurationNode[] = [];
222 > let previousUseHostProxy: boolean | undefined = undefined;
223 > let previousUseHostProxyDefault: boolean | undefined = undefined;
224 > function registerProxyConfigurations(useHostProxy = true, useHostProxyDefault = true): void {
225 > if (previousUseHostProxy === useHostProxy && previousUseHostProxyDefault === useHostProxyDefault) {
226 return;
227 }
228 > request.ts
229 > previousUseHostProxy = useHostProxy;
230 > previousUseHostProxyDefault = useHostProxyDefault;
231 >
232 > const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
233 > const oldProxyConfiguration = proxyConfiguration;
234 > proxyConfiguration = [
235 > {
236 > id: 'http',
237 > order: 15,
238 > title: localize('httpConfigurationTitle', "HTTP"),
239 > type: 'object',
240 > scope: ConfigurationScope.MACHINE,
241 > properties: {
242 > 'http.useLocalProxyConfiguration': {
243 > type: 'boolean',
244 > default: useHostProxyDefault,
245 > markdownDescription: localize('useLocalProxy', "Controls whether in the remote extension host the local proxy configuration should be used. This setting only applies as a remote setting during [remote development](https://aka.ms/vscode-remote)."),
246 > restricted: true
247 > },
248 > }
249 > },
250 > {
251 > id: 'http',
252 > order: 15,
253 > title: localize('httpConfigurationTitle', "HTTP"),
254 > type: 'object',
255 > scope: ConfigurationScope.APPLICATION,
256 > properties: {
257 > 'http.electronFetch': {
258 > type: 'boolean',
259 > default: false,
260 > description: localize('electronFetch', "Controls whether use of Electron's fetch implementation instead of Node.js' should be enabled. All local extensions will get Electron's fetch implementation for the global fetch API."),
261 > restricted: true
262 > },
263 > }
264 > },
265 > {
266 > id: 'http',
267 > order: 15,
268 > title: localize('httpConfigurationTitle', "HTTP"),
269 > type: 'object',
270 > scope: useHostProxy ? ConfigurationScope.APPLICATION : ConfigurationScope.MACHINE,
271 > properties: {
272 > 'http.proxy': {
273 > type: 'string',
274 > pattern: '^(https?|socks|socks4a?|socks5h?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$',
275 > markdownDescription: localize('proxy', "The proxy setting to use. If not set, will be inherited from the `http_proxy` and `https_proxy` environment variables. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
276 > restricted: true
277 > },
278 > 'http.proxyStrictSSL': {
279 > type: 'boolean',
280 > default: true,
281 > markdownDescription: localize('strictSSL', "Controls whether the proxy server certificate should be verified against the list of supplied CAs. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
282 > restricted: true
283 > },
284 > 'http.proxyKerberosServicePrincipal': {
285 > type: 'string',
286 > markdownDescription: localize('proxyKerberosServicePrincipal', "Overrides the principal service name for Kerberos authentication with the HTTP proxy. A default based on the proxy hostname is used when this is not set. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
287 > restricted: true
288 > },
289 > 'http.noProxy': {
290 > type: 'array',
291 > items: { type: 'string' },
292 > markdownDescription: localize('noProxy', "Specifies domain names for which proxy settings should be ignored for HTTP/HTTPS requests. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
293 > restricted: true
294 > },
295 > 'http.proxyAuthorization': {
296 > type: ['null', 'string'],
297 > default: null,
298 > markdownDescription: localize('proxyAuthorization', "The value to send as the `Proxy-Authorization` header for every network request. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
299 > restricted: true
300 > },
301 > 'http.proxySupport': {
302 > type: 'string',
303 > enum: ['off', 'on', 'fallback', 'override'],
304 > enumDescriptions: [
305 > localize('proxySupportOff', "Disable proxy support for extensions."),
306 > localize('proxySupportOn', "Enable proxy support for extensions."),
307 > localize('proxySupportFallback', "Enable proxy support for extensions, fall back to request options, when no proxy found."),
308 > localize('proxySupportOverride', "Enable proxy support for extensions, override request options."),
309 > ],
310 > default: 'override',
311 > markdownDescription: localize('proxySupport', "Use the proxy support for extensions. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
312 > restricted: true
313 > },
314 > 'http.systemCertificates': {
315 > type: 'boolean',
316 > default: true,
317 > markdownDescription: localize('systemCertificates', "Controls whether CA certificates should be loaded from the OS. On Windows and macOS, a reload of the window is required after turning this off. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
318 > restricted: true
319 > },
320 > 'http.systemCertificatesNode': {
321 > type: 'boolean',
322 > tags: ['experimental'],
323 > default: systemCertificatesNodeDefault,
324 > markdownDescription: localize('systemCertificatesNode', "Controls whether system certificates should be loaded using Node.js built-in support. Reload the window after changing this setting. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
325 > restricted: true,
326 > experiment: {
327 > mode: 'auto'
328 > }
329 > },
330 > 'http.experimental.systemCertificatesV2': {
331 > type: 'boolean',
332 > tags: ['experimental'],
333 > default: false,
334 > markdownDescription: localize('systemCertificatesV2', "Controls whether experimental loading of CA certificates from the OS should be enabled. This uses a more general approach than the default implementation. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
335 > restricted: true
336 > },
337 > 'http.fetchAdditionalSupport': {
338 > type: 'boolean',
339 > default: true,
340 > markdownDescription: localize('fetchAdditionalSupport', "Controls whether Node.js' fetch implementation should be extended with additional support. Currently proxy support ({1}) and system certificates ({2}) are added when the corresponding settings are enabled. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`', '`#http.proxySupport#`', '`#http.systemCertificates#`'),
341 > restricted: true
342 > },
343 > 'http.webSocketAdditionalSupport': {
344 > type: 'boolean',
345 > default: true,
346 > markdownDescription: localize('webSocketAdditionalSupport', "Controls whether the built-in WebSocket implementation should be extended with additional support. Currently proxy support ({1}) and system certificates ({2}) are added when the corresponding settings are enabled. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`', '`#http.proxySupport#`', '`#http.systemCertificates#`'),
347 > restricted: true
348 > },
349 > 'http.experimental.networkInterfaceCheckInterval': {
350 > type: 'number',
351 > default: 300,
352 > minimum: -1,
353 > tags: ['experimental'],
354 > markdownDescription: localize('networkInterfaceCheckInterval', "Controls the interval in seconds for checking network interface changes to invalidate the proxy cache. Set to -1 to disable. When during [remote development](https://aka.ms/vscode-remote) the {0} setting is disabled this setting can be configured in the local and the remote settings separately.", '`#http.useLocalProxyConfiguration#`'),
355 > restricted: true,
356 > experiment: {
357 > mode: 'auto'
358 > }
359 > }
360 > }
361 > }
362 > ];
363 > configurationRegistry.updateConfigurations({ add: proxyConfiguration, remove: oldProxyConfiguration });
364 > }
365 >
366 > registerProxyConfigurations();
src/vs/platform/userDataSync/common/globalStateSync.ts 277 covered LOC · 50 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- globalStateSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer } from '../../../base/common/buffer.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { IStringDictionary } from '../../../base/common/collections.js';
9 > import { getErrorMessage } from '../../../base/common/errors.js';
10 > import { Event } from '../../../base/common/event.js';
11 > import { parse } from '../../../base/common/json.js';
12 > import { toFormattedString } from '../../../base/common/jsonFormatter.js';
13 > import { isWeb } from '../../../base/common/platform.js';
14 > import { URI } from '../../../base/common/uri.js';
15 > import { generateUuid } from '../../../base/common/uuid.js';
16 > import { IHeaders } from '../../../base/parts/request/common/request.js';
17 > import { IConfigurationService } from '../../configuration/common/configuration.js';
18 > import { IEnvironmentService } from '../../environment/common/environment.js';
19 > import { IFileService } from '../../files/common/files.js';
20 > import { ILogService } from '../../log/common/log.js';
21 > import { getServiceMachineId } from '../../externalServices/common/serviceMachineId.js';
22 > import { IStorageEntry, IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
23 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
24 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
25 > import { AbstractInitializer, AbstractSynchroniser, getSyncResourceLogLabel, IAcceptResult, IMergeResult, IResourcePreview, isSyncData } from './abstractSynchronizer.js';
26 > import { edit } from './content.js';
27 > import { merge } from './globalStateMerge.js';
28 > import { ALL_SYNC_RESOURCES, Change, createSyncHeaders, getEnablementKey, IGlobalState, IRemoteUserData, IStorageValue, ISyncData, IUserData, IUserDataSyncLocalStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource, SYNC_SERVICE_URL_TYPE, UserDataSyncError, UserDataSyncErrorCode, UserDataSyncStoreType, USER_DATA_SYNC_SCHEME } from './userDataSync.js';
29 > import { UserDataSyncStoreClient } from './userDataSyncStoreService.js';
30 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
31 > import { IUserDataProfileStorageService } from '../../userDataProfile/common/userDataProfileStorageService.js';
32 > import { IInstantiationService } from '../../instantiation/common/instantiation.js';
33 >
34 > const argvStoragePrefx = 'globalState.argv.';
35 > const argvProperties: string[] = ['locale'];
36 >
37 > type StorageKeys = { machine: string[]; user: string[]; unregistered: string[] };
38 >
39 > interface IGlobalStateResourceMergeResult extends IAcceptResult {
40 > readonly local: { added: IStringDictionary<IStorageValue>; removed: string[]; updated: IStringDictionary<IStorageValue> };
41 > readonly remote: { added: string[]; removed: string[]; updated: string[]; all: IStringDictionary<IStorageValue> | null };
42 > }
43 >
44 > interface IGlobalStateResourcePreview extends IResourcePreview {
45 > readonly localUserData: IGlobalState;
46 > readonly previewResult: IGlobalStateResourceMergeResult;
47 > readonly storageKeys: StorageKeys;
48 > }
49 >
50 > export function stringify(globalState: IGlobalState, format: boolean): string {
51 > const storageKeys = globalState.storage ? Object.keys(globalState.storage).sort() : []; globalStateSync.ts
52 > const storage: IStringDictionary<IStorageValue> = {};
53 > storageKeys.forEach(key => storage[key] = globalState.storage[key]);
54 > globalState.storage = storage;
55 > return format ? toFormattedString(globalState, {}) : JSON.stringify(globalState);
56 > }
58 > const GLOBAL_STATE_DATA_VERSION = 1;
59 >
60 > /**
61 > * Synchronises global state that includes
62 > * - Global storage with user scope
63 > * - Locale from argv properties
64 > *
65 > * Global storage is synced without checking version just like other resources (settings, keybindings).
66 > * If there is a change in format of the value of a storage key which requires migration then
67 > * Owner of that key should remove that key from user scope and replace that with new user scoped key.
68 > */
69 > export class GlobalStateSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
70 >
71 > protected readonly version: number = GLOBAL_STATE_DATA_VERSION;
72 > private readonly previewResource: URI = this.extUri.joinPath(this.syncPreviewFolder, 'globalState.json');
73 > private readonly baseResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' });
74 > private readonly localResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' });
75 > private readonly remoteResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' });
76 > private readonly acceptedResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' });
77 >
78 > private readonly localGlobalStateProvider: LocalGlobalStateProvider;
79 >
80 > constructor(
81 > profile: IUserDataProfile, globalStateSync.ts
82 > collection: string | undefined,
83 > @IUserDataProfileStorageService private readonly userDataProfileStorageService: IUserDataProfileStorageService,
84 > @IFileService fileService: IFileService,
85 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
86 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
87 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
88 > @IEnvironmentService environmentService: IEnvironmentService,
89 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
90 > @ITelemetryService telemetryService: ITelemetryService,
91 > @IConfigurationService configurationService: IConfigurationService,
92 > @IStorageService storageService: IStorageService,
93 > @IUriIdentityService uriIdentityService: IUriIdentityService,
94 > @IInstantiationService instantiationService: IInstantiationService,
95 > ) {
96 > super({ syncResource: SyncResource.GlobalState, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
97 > this.localGlobalStateProvider = instantiationService.createInstance(LocalGlobalStateProvider);
98 > this._register(fileService.watch(this.extUri.dirname(this.environmentService.argvResource)));
99 > this._register(
100 > Event.any(
101 > /* Locale change */
102 > Event.filter(fileService.onDidFilesChange, e => e.contains(this.environmentService.argvResource)),
103 > Event.filter(userDataProfileStorageService.onDidChange, e => {
104 /* StorageTarget has changed in profile storage */
105 if (e.targetChanges.some(profile => this.syncResource.profile.id === profile.id)) {
111 }
112 return false;
113 > }), globalStateSync.ts
114 > )((() => this.triggerLocalChange()))
115 > );
116 > }
118 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<IGlobalStateResourcePreview[]> {
119 > const remoteGlobalState: IGlobalState = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null; globalStateSync.ts
120 >
121 > // Use remote data as last sync data if last sync data does not exist and remote data is from same machine
122 > lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
123 > const lastSyncGlobalState: IGlobalState | null = lastSyncUserData && lastSyncUserData.syncData ? JSON.parse(lastSyncUserData.syncData.content) : null;
124 >
125 > const localGlobalState = await this.localGlobalStateProvider.getLocalGlobalState(this.syncResource.profile);
126 >
127 > if (remoteGlobalState) {
128 this.logService.trace(`${this.syncResourceLogLabel}: Merging remote ui state with local ui state...`);
129 > } else { globalStateSync.ts
130 > this.logService.trace(`${this.syncResourceLogLabel}: Remote ui state does not exist. Synchronizing ui state for the first time.`);
131 > }
132 >
133 > const storageKeys = await this.getStorageKeys(lastSyncGlobalState);
134 > const { local, remote } = merge(localGlobalState.storage, remoteGlobalState ? remoteGlobalState.storage : null, lastSyncGlobalState ? lastSyncGlobalState.storage : null, storageKeys, this.logService);
135 > const previewResult: IGlobalStateResourceMergeResult = {
136 > content: null,
137 > local,
138 > remote,
139 > localChange: Object.keys(local.added).length > 0 || Object.keys(local.updated).length > 0 || local.removed.length > 0 ? Change.Modified : Change.None,
140 > remoteChange: remote.all !== null ? Change.Modified : Change.None,
141 > };
142 >
143 > const localContent = stringify(localGlobalState, false);
144 > return [{
145 > baseResource: this.baseResource,
146 > baseContent: lastSyncGlobalState ? stringify(lastSyncGlobalState, false) : localContent,
147 > localResource: this.localResource,
148 > localContent,
149 > localUserData: localGlobalState,
150 > remoteResource: this.remoteResource,
151 > remoteContent: remoteGlobalState ? stringify(remoteGlobalState, false) : null,
152 > previewResource: this.previewResource,
153 > previewResult,
154 > localChange: previewResult.localChange,
155 > remoteChange: previewResult.remoteChange,
156 > acceptedResource: this.acceptedResource,
157 > storageKeys
158 > }];
159 > }
161 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
162 const lastSyncGlobalState: IGlobalState | null = lastSyncUserData.syncData ? JSON.parse(lastSyncUserData.syncData.content) : null;
163 if (lastSyncGlobalState === null) {
169 return remote.all !== null;
170 }
172 > protected async getMergeResult(resourcePreview: IGlobalStateResourcePreview, token: CancellationToken): Promise<IMergeResult> {
173 > return { ...resourcePreview.previewResult, hasConflicts: false }; globalStateSync.ts
174 > }
176 > protected async getAcceptResult(resourcePreview: IGlobalStateResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IGlobalStateResourceMergeResult> {
178 > /* Accept local resource */
179 > if (this.extUri.isEqual(resource, this.localResource)) {
180 return this.acceptLocal(resourcePreview);
181 }
183 > /* Accept remote resource */
184 > if (this.extUri.isEqual(resource, this.remoteResource)) {
185 return this.acceptRemote(resourcePreview);
186 }
188 > /* Accept preview resource */
189 > if (this.extUri.isEqual(resource, this.previewResource)) {
190 > return resourcePreview.previewResult;
191 > }
192
193 throw new Error(`Invalid Resource: ${resource.toString()}`);
196 > private async acceptLocal(resourcePreview: IGlobalStateResourcePreview): Promise<IGlobalStateResourceMergeResult> {
197 if (resourcePreview.remoteContent !== null) {
198 const remoteGlobalState: IGlobalState = JSON.parse(resourcePreview.remoteContent);
215 }
216 }
218 > private async acceptRemote(resourcePreview: IGlobalStateResourcePreview): Promise<IGlobalStateResourceMergeResult> {
219 if (resourcePreview.remoteContent !== null) {
220 const remoteGlobalState: IGlobalState = JSON.parse(resourcePreview.remoteContent);
237 }
238 }
240 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [IGlobalStateResourcePreview, IGlobalStateResourceMergeResult][], force: boolean): Promise<void> {
241 > const { localUserData } = resourcePreviews[0][0]; globalStateSync.ts
242 > const { local, remote, localChange, remoteChange } = resourcePreviews[0][1];
243 >
244 > if (localChange === Change.None && remoteChange === Change.None) {
245 this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing ui state.`);
246 }
248 > if (localChange !== Change.None) {
249 // update local
250 this.logService.trace(`${this.syncResourceLogLabel}: Updating local ui state...`);
253 this.logService.info(`${this.syncResourceLogLabel}: Updated local ui state`);
254 }
256 > if (remoteChange !== Change.None) {
257 > // update remote globalStateSync.ts
258 > this.logService.trace(`${this.syncResourceLogLabel}: Updating remote ui state...`);
259 > const content = JSON.stringify({ storage: remote.all });
260 > remoteUserData = await this.updateRemoteUserData(content, force ? null : remoteUserData.ref);
261 > this.logService.info(`${this.syncResourceLogLabel}: Updated remote ui state.${remote.added.length ? ` Added: ${remote.added}.` : ''}${remote.updated.length ? ` Updated: ${remote.updated}.` : ''}${remote.removed.length ? ` Removed: ${remote.removed}.` : ''}`);
262 > }
264 > if (lastSyncUserData?.ref !== remoteUserData.ref) {
265 > // update last sync
266 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized ui state...`);
267 > await this.updateLastSyncUserData(remoteUserData);
268 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized ui state`);
269 > }
270 > }
272 > async resolveContent(uri: URI): Promise<string | null> {
273 if (this.extUri.isEqual(this.remoteResource, uri)
274 || this.extUri.isEqual(this.baseResource, uri)
281 return null;
282 }
284 > async hasLocalData(): Promise<boolean> {
285 try {
286 const { storage } = await this.localGlobalStateProvider.getLocalGlobalState(this.syncResource.profile);
293 return false;
294 }
296 > private async getStorageKeys(lastSyncGlobalState: IGlobalState | null): Promise<StorageKeys> {
297 > const storageData = await this.userDataProfileStorageService.readStorageData(this.syncResource.profile); globalStateSync.ts
298 > const user: string[] = [], machine: string[] = [];
299 > for (const [key, value] of storageData) {
300 if (value.target === StorageTarget.USER) {
301 user.push(key);
304 }
305 }
306 > const registered = [...user, ...machine]; globalStateSync.ts
307 > const unregistered = lastSyncGlobalState?.storage ? Object.keys(lastSyncGlobalState.storage).filter(key => !key.startsWith(argvStoragePrefx) && !registered.includes(key) && storageData.get(key) !== undefined) : [];
308 >
309 > if (!isWeb) {
310 > // Following keys are synced only in web. Do not sync these keys in other platforms
311 > const keysSyncedOnlyInWeb = [...ALL_SYNC_RESOURCES.map(resource => getEnablementKey(resource)), SYNC_SERVICE_URL_TYPE];
312 > unregistered.push(...keysSyncedOnlyInWeb);
313 > machine.push(...keysSyncedOnlyInWeb);
314 > }
315 >
316 > return { user, machine, unregistered };
317 > }
319 >
320 > export class LocalGlobalStateProvider {
321 > constructor(
322 > @IFileService private readonly fileService: IFileService, globalStateSync.ts
323 > @IEnvironmentService private readonly environmentService: IEnvironmentService,
324 > @IUserDataProfileStorageService private readonly userDataProfileStorageService: IUserDataProfileStorageService,
325 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService
326 > ) { }
328 > async getLocalGlobalState(profile: IUserDataProfile): Promise<IGlobalState> {
329 > const storage: IStringDictionary<IStorageValue> = {}; globalStateSync.ts
330 > if (profile.isDefault) {
331 > const argvContent: string = await this.getLocalArgvContent();
332 > const argvValue: IStringDictionary<any> = parse(argvContent);
333 > for (const argvProperty of argvProperties) {
334 > if (argvValue[argvProperty] !== undefined) {
335 > storage[`${argvStoragePrefx}${argvProperty}`] = { version: 1, value: argvValue[argvProperty] }; globalStateSync.ts
336 > }
338 > }
339 > const storageData = await this.userDataProfileStorageService.readStorageData(profile);
340 > for (const [key, value] of storageData) {
341 if (value.value && value.target === StorageTarget.USER) {
342 storage[key] = { version: 1, value: value.value, scope: value.scope };
343 }
344 }
345 > return { storage }; globalStateSync.ts
346 > }
348 > private async getLocalArgvContent(): Promise<string> {
349 > try { globalStateSync.ts
350 > this.logService.debug('GlobalStateSync#getLocalArgvContent', this.environmentService.argvResource);
351 > const content = await this.fileService.readFile(this.environmentService.argvResource);
352 > this.logService.debug('GlobalStateSync#getLocalArgvContent - Resolved', this.environmentService.argvResource); globalStateSync.ts
353 > return content.value.toString();
354 > } catch (error) { globalStateSync.ts
355 this.logService.debug(getErrorMessage(error));
356 }
357 return '{}';
360 > async writeLocalGlobalState({ added, removed, updated }: { added: IStringDictionary<IStorageValue>; updated: IStringDictionary<IStorageValue>; removed: string[] }, profile: IUserDataProfile): Promise<void> {
361 const syncResourceLogLabel = getSyncResourceLogLabel(SyncResource.GlobalState, profile);
362 const argv: IStringDictionary<any> = {};
415 }
416 }
418 >
419 > export class GlobalStateInitializer extends AbstractInitializer {
420 >
421 > constructor(
422 @IStorageService storageService: IStorageService,
423 @IFileService fileService: IFileService,
429 super(SyncResource.GlobalState, userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
430 }
432 > protected async doInitialize(remoteUserData: IRemoteUserData): Promise<void> {
433 const remoteGlobalState: IGlobalState = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null;
434 if (!remoteGlobalState) {
475 }
476 }
478 > }
479 >
480 > export class UserDataSyncStoreTypeSynchronizer {
481 >
482 > constructor(
483 private readonly userDataSyncStoreClient: UserDataSyncStoreClient,
484 @IStorageService private readonly storageService: IStorageService,
488 ) {
489 }
491 > getSyncStoreType(userData: IUserData): UserDataSyncStoreType | undefined {
492 const remoteGlobalState = this.parseGlobalState(userData);
493 return remoteGlobalState?.storage[SYNC_SERVICE_URL_TYPE]?.value as UserDataSyncStoreType;
494 }
496 > async sync(userDataSyncStoreType: UserDataSyncStoreType): Promise<void> {
497 const syncHeaders = createSyncHeaders(generateUuid());
498 try {
509 }
510 }
512 > private async doSync(userDataSyncStoreType: UserDataSyncStoreType, syncHeaders: IHeaders): Promise<void> {
513 // Read the global state from remote
514 const globalStateUserData = await this.userDataSyncStoreClient.readResource(SyncResource.GlobalState, null, undefined, syncHeaders);
523 await this.userDataSyncStoreClient.writeResource(SyncResource.GlobalState, JSON.stringify(syncDataToUpdate), globalStateUserData.ref, undefined, syncHeaders);
524 }
526 > private parseGlobalState({ content }: IUserData): IGlobalState | null {
527 if (!content) {
528 return null;
src/vs/platform/userDataSync/common/extensionsSync.ts 273 covered LOC · 44 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensionsSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Promises } from '../../../base/common/async.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { IStringDictionary } from '../../../base/common/collections.js';
9 > import { getErrorMessage } from '../../../base/common/errors.js';
10 > import { Event } from '../../../base/common/event.js';
11 > import { toFormattedString } from '../../../base/common/jsonFormatter.js';
12 > import { DisposableStore } from '../../../base/common/lifecycle.js';
13 > import { compare } from '../../../base/common/strings.js';
14 > import { URI } from '../../../base/common/uri.js';
15 > import { IConfigurationService } from '../../configuration/common/configuration.js';
16 > import { IEnvironmentService } from '../../environment/common/environment.js';
17 > import { GlobalExtensionEnablementService } from '../../extensionManagement/common/extensionEnablementService.js';
18 > import { IExtensionGalleryService, IExtensionManagementService, IGlobalExtensionEnablementService, ILocalExtension, ExtensionManagementError, ExtensionManagementErrorCode, IGalleryExtension, DISABLED_EXTENSIONS_STORAGE_PATH, EXTENSION_INSTALL_SKIP_WALKTHROUGH_CONTEXT, EXTENSION_INSTALL_SOURCE_CONTEXT, InstallExtensionInfo, ExtensionInstallSource, EXTENSION_INSTALL_SKIP_PUBLISHER_TRUST_CONTEXT } from '../../extensionManagement/common/extensionManagement.js';
19 > import { areSameExtensions } from '../../extensionManagement/common/extensionManagementUtil.js';
20 > import { ExtensionStorageService, IExtensionStorageService } from '../../extensionManagement/common/extensionStorage.js';
21 > import { ExtensionType, IExtensionIdentifier, isApplicationScopedExtension } from '../../extensions/common/extensions.js';
22 > import { IFileService } from '../../files/common/files.js';
23 > import { IInstantiationService } from '../../instantiation/common/instantiation.js';
24 > import { ServiceCollection } from '../../instantiation/common/serviceCollection.js';
25 > import { ILogService } from '../../log/common/log.js';
26 > import { IStorageService } from '../../storage/common/storage.js';
27 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
28 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
29 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
30 > import { AbstractInitializer, AbstractSynchroniser, getSyncResourceLogLabel, IAcceptResult, IMergeResult, IResourcePreview } from './abstractSynchronizer.js';
31 > import { IMergeResult as IExtensionMergeResult, merge } from './extensionsMerge.js';
32 > import { IIgnoredExtensionsManagementService } from './ignoredExtensions.js';
33 > import { Change, IRemoteUserData, ISyncData, ISyncExtension, IUserDataSyncLocalStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource, USER_DATA_SYNC_SCHEME, ILocalSyncExtension } from './userDataSync.js';
34 > import { IUserDataProfileStorageService } from '../../userDataProfile/common/userDataProfileStorageService.js';
35 > import { IProductService } from '../../product/common/productService.js';
36 >
37 > type IExtensionResourceMergeResult = IAcceptResult & IExtensionMergeResult;
38 >
39 > interface IExtensionResourcePreview extends IResourcePreview {
40 > readonly localExtensions: ILocalSyncExtension[];
41 > readonly remoteExtensions: ISyncExtension[] | null;
42 > readonly skippedExtensions: ISyncExtension[];
43 > readonly builtinExtensions: IExtensionIdentifier[] | null;
44 > readonly previewResult: IExtensionResourceMergeResult;
45 > }
46 >
47 > interface ILastSyncUserData extends IRemoteUserData {
48 > skippedExtensions: ISyncExtension[] | undefined;
49 > builtinExtensions: IExtensionIdentifier[] | undefined;
50 > }
51 >
52 async function parseAndMigrateExtensions(syncData: ISyncData, extensionManagementService: IExtensionManagementService): Promise<ISyncExtension[]> {
53 const extensions = JSON.parse(syncData.content);
77 return extensions;
78 }
80 > export function parseExtensions(syncData: ISyncData): ISyncExtension[] {
81 return JSON.parse(syncData.content);
82 }
84 > export function stringify(extensions: ISyncExtension[], format: boolean): string {
85 > extensions.sort((e1, e2) => { extensionsSync.ts
86 if (!e1.identifier.uuid && e2.identifier.uuid) {
87 return -1;
91 }
92 return compare(e1.identifier.id, e2.identifier.id);
94 > return format ? toFormattedString(extensions, {}) : JSON.stringify(extensions);
95 > }
97 > export class ExtensionsSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
98 >
99 > /*
100 > Version 3 - Introduce installed property to skip installing built in extensions
101 > protected readonly version: number = 3;
102 > */
103 > /* Version 4: Change settings from `sync.${setting}` to `settingsSync.{setting}` */
104 > /* Version 5: Introduce extension state */
105 > /* Version 6: Added isApplicationScoped property */
106 > protected readonly version: number = 6;
107 >
108 > private readonly previewResource: URI = this.extUri.joinPath(this.syncPreviewFolder, 'extensions.json');
109 > private readonly baseResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' });
110 > private readonly localResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' });
111 > private readonly remoteResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' });
112 > private readonly acceptedResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' });
113 >
114 > private readonly localExtensionsProvider: LocalExtensionsProvider;
115 >
116 > constructor(
117 > // profileLocation changes for default profile extensionsSync.ts
118 > profile: IUserDataProfile,
119 > collection: string | undefined,
120 > @IEnvironmentService environmentService: IEnvironmentService,
121 > @IFileService fileService: IFileService,
122 > @IStorageService storageService: IStorageService,
123 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
124 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
125 > @IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
126 > @IIgnoredExtensionsManagementService private readonly ignoredExtensionsManagementService: IIgnoredExtensionsManagementService,
127 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
128 > @IConfigurationService configurationService: IConfigurationService,
129 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
130 > @ITelemetryService telemetryService: ITelemetryService,
131 > @IExtensionStorageService extensionStorageService: IExtensionStorageService,
132 > @IUriIdentityService uriIdentityService: IUriIdentityService,
133 > @IUserDataProfileStorageService userDataProfileStorageService: IUserDataProfileStorageService,
134 > @IInstantiationService private readonly instantiationService: IInstantiationService,
135 > ) {
136 > super({ syncResource: SyncResource.Extensions, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
137 > this.localExtensionsProvider = this.instantiationService.createInstance(LocalExtensionsProvider);
138 > this._register(
139 > Event.any<any>(
140 > Event.filter(this.extensionManagementService.onDidInstallExtensions, (e => e.some(({ local }) => !!local))),
141 > Event.filter(this.extensionManagementService.onDidUninstallExtension, (e => !e.error)),
142 > Event.filter(userDataProfileStorageService.onDidChange, e => e.valueChanges.some(({ profile, changes }) => this.syncResource.profile.id === profile.id && changes.some(change => change.key === DISABLED_EXTENSIONS_STORAGE_PATH))),
143 > extensionStorageService.onDidChangeExtensionStorageToSync)(() => this.triggerLocalChange()));
144 > }
146 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: ILastSyncUserData | null): Promise<IExtensionResourcePreview[]> {
147 > const remoteExtensions = remoteUserData.syncData ? await parseAndMigrateExtensions(remoteUserData.syncData, this.extensionManagementService) : null; extensionsSync.ts
148 > const skippedExtensions = lastSyncUserData?.skippedExtensions ?? [];
149 > const builtinExtensions = lastSyncUserData?.builtinExtensions ?? null;
150 > const lastSyncExtensions = lastSyncUserData?.syncData ? await parseAndMigrateExtensions(lastSyncUserData.syncData, this.extensionManagementService) : null;
151 >
152 > const { localExtensions, ignoredExtensions } = await this.localExtensionsProvider.getLocalExtensions(this.syncResource.profile);
153 >
154 > if (remoteExtensions) {
155 this.logService.trace(`${this.syncResourceLogLabel}: Merging remote extensions with local extensions...`);
156 > } else { extensionsSync.ts
157 > this.logService.trace(`${this.syncResourceLogLabel}: Remote extensions does not exist. Synchronizing extensions for the first time.`);
158 > }
159 >
160 > const { local, remote } = merge(localExtensions, remoteExtensions, lastSyncExtensions, skippedExtensions, ignoredExtensions, builtinExtensions);
161 > const previewResult: IExtensionResourceMergeResult = {
162 > local, remote,
163 > content: this.getPreviewContent(localExtensions, local.added, local.updated, local.removed),
164 > localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? Change.Modified : Change.None,
165 > remoteChange: remote !== null ? Change.Modified : Change.None,
166 > };
167 >
168 > const localContent = this.stringify(localExtensions, false);
169 > return [{
170 > skippedExtensions,
171 > builtinExtensions,
172 > baseResource: this.baseResource,
173 > baseContent: lastSyncExtensions ? this.stringify(lastSyncExtensions, false) : localContent,
174 > localResource: this.localResource,
175 > localContent,
176 > localExtensions,
177 > remoteResource: this.remoteResource,
178 > remoteExtensions,
179 > remoteContent: remoteExtensions ? this.stringify(remoteExtensions, false) : null,
180 > previewResource: this.previewResource,
181 > previewResult,
182 > localChange: previewResult.localChange,
183 > remoteChange: previewResult.remoteChange,
184 > acceptedResource: this.acceptedResource,
185 > }];
186 > }
188 > protected async hasRemoteChanged(lastSyncUserData: ILastSyncUserData): Promise<boolean> {
189 const lastSyncExtensions: ISyncExtension[] | null = lastSyncUserData.syncData ? await parseAndMigrateExtensions(lastSyncUserData.syncData, this.extensionManagementService) : null;
190 const { localExtensions, ignoredExtensions } = await this.localExtensionsProvider.getLocalExtensions(this.syncResource.profile);
192 return remote !== null;
193 }
195 > private getPreviewContent(localExtensions: ISyncExtension[], added: ISyncExtension[], updated: ISyncExtension[], removed: IExtensionIdentifier[]): string {
196 > const preview: ISyncExtension[] = [...added, ...updated]; extensionsSync.ts
197 >
198 > const idsOrUUIDs: Set<string> = new Set<string>();
199 > const addIdentifier = (identifier: IExtensionIdentifier) => {
200 idsOrUUIDs.add(identifier.id.toLowerCase());
201 if (identifier.uuid) {
203 }
204 };
205 > preview.forEach(({ identifier }) => addIdentifier(identifier)); extensionsSync.ts
206 > removed.forEach(addIdentifier);
207 >
208 > for (const localExtension of localExtensions) {
209 if (idsOrUUIDs.has(localExtension.identifier.id.toLowerCase()) || (localExtension.identifier.uuid && idsOrUUIDs.has(localExtension.identifier.uuid))) {
210 // skip
213 preview.push(localExtension);
214 }
216 > return this.stringify(preview, false);
217 > }
219 > protected async getMergeResult(resourcePreview: IExtensionResourcePreview, token: CancellationToken): Promise<IMergeResult> {
220 return { ...resourcePreview.previewResult, hasConflicts: false };
221 }
223 > protected async getAcceptResult(resourcePreview: IExtensionResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IExtensionResourceMergeResult> {
224
225 /* Accept local resource */
240 throw new Error(`Invalid Resource: ${resource.toString()}`);
241 }
243 > private async acceptLocal(resourcePreview: IExtensionResourcePreview): Promise<IExtensionResourceMergeResult> {
244 const installedExtensions = await this.extensionManagementService.getInstalled(undefined, this.syncResource.profile.extensionsResource);
245 const ignoredExtensions = this.ignoredExtensionsManagementService.getIgnoredExtensions(installedExtensions);
255 };
256 }
258 > private async acceptRemote(resourcePreview: IExtensionResourcePreview): Promise<IExtensionResourceMergeResult> {
259 const installedExtensions = await this.extensionManagementService.getInstalled(undefined, this.syncResource.profile.extensionsResource);
260 const ignoredExtensions = this.ignoredExtensionsManagementService.getIgnoredExtensions(installedExtensions);
280 }
281 }
283 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [IExtensionResourcePreview, IExtensionResourceMergeResult][], force: boolean): Promise<void> {
284 > let { skippedExtensions, builtinExtensions, localExtensions } = resourcePreviews[0][0]; extensionsSync.ts
285 > const { local, remote, localChange, remoteChange } = resourcePreviews[0][1];
286 >
287 > if (localChange === Change.None && remoteChange === Change.None) {
288 > this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing extensions.`);
289 > }
290 >
291 > if (localChange !== Change.None) {
292 await this.backupLocal(JSON.stringify(localExtensions));
293 skippedExtensions = await this.localExtensionsProvider.updateLocalExtensions(local.added, local.removed, local.updated, skippedExtensions, this.syncResource.profile);
294 }
296 > if (remote) {
297 // update remote
298 this.logService.trace(`${this.syncResourceLogLabel}: Updating remote extensions...`);
301 this.logService.info(`${this.syncResourceLogLabel}: Updated remote extensions.${remote.added.length ? ` Added: ${JSON.stringify(remote.added.map(e => e.identifier.id))}.` : ''}${remote.updated.length ? ` Updated: ${JSON.stringify(remote.updated.map(e => e.identifier.id))}.` : ''}${remote.removed.length ? ` Removed: ${JSON.stringify(remote.removed.map(e => e.identifier.id))}.` : ''}`);
302 }
304 > if (lastSyncUserData?.ref !== remoteUserData.ref) {
305 > // update last sync
306 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized extensions...`);
307 > builtinExtensions = this.computeBuiltinExtensions(localExtensions, builtinExtensions);
308 > await this.updateLastSyncUserData(remoteUserData, { skippedExtensions, builtinExtensions });
309 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized extensions.${skippedExtensions.length ? ` Skipped: ${JSON.stringify(skippedExtensions.map(e => e.identifier.id))}.` : ''}`);
310 > }
311 > }
313 > private computeBuiltinExtensions(localExtensions: ILocalSyncExtension[], previousBuiltinExtensions: IExtensionIdentifier[] | null): IExtensionIdentifier[] {
314 > const localExtensionsSet = new Set<string>(); extensionsSync.ts
315 > const builtinExtensions: IExtensionIdentifier[] = [];
316 > for (const localExtension of localExtensions) {
317 localExtensionsSet.add(localExtension.identifier.id.toLowerCase());
318 if (!localExtension.installed) {
320 }
321 }
322 > if (previousBuiltinExtensions) { extensionsSync.ts
323 for (const builtinExtension of previousBuiltinExtensions) {
324 // Add previous builtin extension if it does not exist in local extensions
328 }
329 }
330 > return builtinExtensions; extensionsSync.ts
331 > }
333 > async resolveContent(uri: URI): Promise<string | null> {
334 if (this.extUri.isEqual(this.remoteResource, uri)
335 || this.extUri.isEqual(this.baseResource, uri)
342 return null;
343 }
345 > private stringify(extensions: ISyncExtension[], format: boolean): string {
346 > return stringify(extensions, format); extensionsSync.ts
347 > }
349 > async hasLocalData(): Promise<boolean> {
350 try {
351 const { localExtensions } = await this.localExtensionsProvider.getLocalExtensions(this.syncResource.profile);
358 return false;
359 }
361 > }
362 >
363 > export class LocalExtensionsProvider {
364 >
365 > constructor(
366 > @IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService, extensionsSync.ts
367 > @IUserDataProfileStorageService private readonly userDataProfileStorageService: IUserDataProfileStorageService,
368 > @IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService,
369 > @IIgnoredExtensionsManagementService private readonly ignoredExtensionsManagementService: IIgnoredExtensionsManagementService,
370 > @IInstantiationService private readonly instantiationService: IInstantiationService,
371 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
372 > @IProductService private readonly productService: IProductService,
373 > ) { }
375 > async getLocalExtensions(profile: IUserDataProfile): Promise<{ localExtensions: ILocalSyncExtension[]; ignoredExtensions: string[] }> {
376 > const installedExtensions = await this.extensionManagementService.getInstalled(undefined, profile.extensionsResource); extensionsSync.ts
377 > const ignoredExtensions = this.ignoredExtensionsManagementService.getIgnoredExtensions(installedExtensions);
378 > const localExtensions = await this.withProfileScopedServices(profile, async (extensionEnablementService, extensionStorageService) => {
379 > const disabledExtensions = extensionEnablementService.getDisabledExtensions();
380 > return installedExtensions
381 > .map(extension => {
382 const { identifier, isBuiltin, manifest, preRelease, pinned, isApplicationScoped } = extension;
383 const syncExtension: ILocalSyncExtension = { identifier, preRelease, version: manifest.version, pinned: !!pinned };
409 }
410 return syncExtension;
411 > }); extensionsSync.ts
412 > });
413 > return { localExtensions, ignoredExtensions };
414 > }
416 > async updateLocalExtensions(added: ISyncExtension[], removed: IExtensionIdentifier[], updated: ISyncExtension[], skippedExtensions: ISyncExtension[], profile: IUserDataProfile): Promise<ISyncExtension[]> {
417 const syncResourceLogLabel = getSyncResourceLogLabel(SyncResource.Extensions, profile);
418 const extensionsToInstall: InstallExtensionInfo[] = [];
562 return newSkippedExtensions;
563 }
565 > private updateExtensionState(state: IStringDictionary<any>, extension: ILocalExtension | IGalleryExtension, version: string | undefined, extensionStorageService: IExtensionStorageService): void {
566 const extensionState = extensionStorageService.getExtensionState(extension, true) || {};
567 const keys = version ? extensionStorageService.getKeysForSync({ id: extension.identifier.id, version }) : undefined;
573 extensionStorageService.setExtensionState(extension, extensionState, true);
574 }
576 > private async withProfileScopedServices<T>(profile: IUserDataProfile, fn: (extensionEnablementService: IGlobalExtensionEnablementService, extensionStorageService: IExtensionStorageService) => Promise<T>): Promise<T> {
577 > return this.userDataProfileStorageService.withProfileScopedStorageService(profile, extensionsSync.ts
578 > async storageService => {
579 > const disposables = new DisposableStore();
580 > const instantiationService = disposables.add(this.instantiationService.createChild(new ServiceCollection([IStorageService, storageService])));
581 > const extensionEnablementService = disposables.add(instantiationService.createInstance(GlobalExtensionEnablementService));
582 > const extensionStorageService = disposables.add(instantiationService.createInstance(ExtensionStorageService));
583 > try {
584 > return await fn(extensionEnablementService, extensionStorageService);
585 > } finally {
586 > disposables.dispose();
587 > }
588 > });
589 > }
591 > }
592 >
593 > export interface IExtensionsInitializerPreviewResult {
594 > readonly installedExtensions: ILocalExtension[];
595 > readonly disabledExtensions: IExtensionIdentifier[];
596 > readonly newExtensions: (IExtensionIdentifier & { preRelease: boolean })[];
597 > readonly remoteExtensions: ISyncExtension[];
598 > }
599 >
600 > export abstract class AbstractExtensionsInitializer extends AbstractInitializer {
601 >
602 > constructor(
603 @IExtensionManagementService protected readonly extensionManagementService: IExtensionManagementService,
604 @IIgnoredExtensionsManagementService private readonly ignoredExtensionsManagementService: IIgnoredExtensionsManagementService,
612 super(SyncResource.Extensions, userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
613 }
615 > protected async parseExtensions(remoteUserData: IRemoteUserData): Promise<ISyncExtension[] | null> {
616 return remoteUserData.syncData ? await parseAndMigrateExtensions(remoteUserData.syncData, this.extensionManagementService) : null;
617 }
619 > protected generatePreview(remoteExtensions: ISyncExtension[], localExtensions: ILocalExtension[]): IExtensionsInitializerPreviewResult {
620 const installedExtensions: ILocalExtension[] = [];
621 const newExtensions: (IExtensionIdentifier & { preRelease: boolean })[] = [];
642 return { installedExtensions, newExtensions, disabledExtensions, remoteExtensions };
643 }
645 > }
src/vs/platform/userDataSync/common/promptsSync/promptsSync.ts 267 covered LOC · 54 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- promptsSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { URI } from '../../../../base/common/uri.js';
7 > import { Event } from '../../../../base/common/event.js';
8 > import { VSBuffer } from '../../../../base/common/buffer.js';
9 > import { deepClone } from '../../../../base/common/objects.js';
10 > import { IStorageService } from '../../../storage/common/storage.js';
11 > import { ITelemetryService } from '../../../telemetry/common/telemetry.js';
12 > import { IStringDictionary } from '../../../../base/common/collections.js';
13 > import { CancellationToken } from '../../../../base/common/cancellation.js';
14 > import { IUriIdentityService } from '../../../uriIdentity/common/uriIdentity.js';
15 > import { IEnvironmentService } from '../../../environment/common/environment.js';
16 >
17 > import { IUserDataProfile } from '../../../userDataProfile/common/userDataProfile.js';
18 > import { IConfigurationService } from '../../../configuration/common/configuration.js';
19 > import { areSame, IMergeResult as IPromptsMergeResult, merge } from './promptsMerge.js';
20 > import { AbstractSynchroniser, IAcceptResult, IFileResourcePreview, IMergeResult } from '../abstractSynchronizer.js';
21 > import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStat } from '../../../files/common/files.js';
22 > import { Change, IRemoteUserData, ISyncData, IUserDataSyncLocalStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource, USER_DATA_SYNC_SCHEME } from '../userDataSync.js';
23 >
24 > interface IPromptsResourcePreview extends IFileResourcePreview {
25 > previewResult: IMergeResult;
26 > }
27 >
28 > interface IPromptsAcceptedResourcePreview extends IFileResourcePreview {
29 > acceptResult: IAcceptResult;
30 > }
31 >
32 > export function parsePrompts(syncData: ISyncData): IStringDictionary<string> {
33 return JSON.parse(syncData.content);
34 }
36 > /**
37 > * Synchronizer class for the "user" prompt files.
38 > * Adopted from {@link SnippetsSynchroniser}.
39 > */
40 > export class PromptsSynchronizer extends AbstractSynchroniser implements IUserDataSynchroniser {
41 >
42 > protected readonly version: number = 1;
43 > private readonly promptsFolder: URI;
44 >
45 > constructor(
46 > profile: IUserDataProfile, promptsSync.ts
47 > collection: string | undefined,
48 > @IEnvironmentService environmentService: IEnvironmentService,
49 > @IFileService fileService: IFileService,
50 > @IStorageService storageService: IStorageService,
51 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
52 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
53 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
54 > @IConfigurationService configurationService: IConfigurationService,
55 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
56 > @ITelemetryService telemetryService: ITelemetryService,
57 > @IUriIdentityService uriIdentityService: IUriIdentityService,
58 > ) {
59 > const syncResource = { syncResource: SyncResource.Prompts, profile };
60 > super(
61 > syncResource,
62 > collection,
63 > fileService,
64 > environmentService,
65 > storageService,
66 > userDataSyncStoreService,
67 > userDataSyncLocalStoreService,
68 > userDataSyncEnablementService,
69 > telemetryService,
70 > logService,
71 > configurationService,
72 > uriIdentityService,
73 > );
74 >
75 > this.promptsFolder = profile.promptsHome;
76 > this._register(this.fileService.watch(environmentService.userRoamingDataHome));
77 > this._register(this.fileService.watch(this.promptsFolder));
78 > this._register(Event.filter(this.fileService.onDidFilesChange, e => e.affects(this.promptsFolder))(() => this.triggerLocalChange()));
79 > }
81 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<IPromptsResourcePreview[]> {
82 > const local = await this.getPromptsFileContents(); promptsSync.ts
83 > const localPrompts = this.toPromptContents(local);
84 > const remotePrompts: IStringDictionary<string> | null = remoteUserData.syncData ? this.parsePrompts(remoteUserData.syncData) : null;
85 >
86 > // Use remote data as last sync data if last sync data does not exist and remote data is from same machine
87 > lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
88 > const lastSyncPrompts: IStringDictionary<string> | null = lastSyncUserData && lastSyncUserData.syncData ? this.parsePrompts(lastSyncUserData.syncData) : null;
89 >
90 > if (remotePrompts) {
91 this.logService.trace(`${this.syncResourceLogLabel}: Merging remote prompts with local prompts...`);
92 > } else { promptsSync.ts
93 > this.logService.trace(`${this.syncResourceLogLabel}: Remote prompts does not exist. Synchronizing prompts for the first time.`);
94 > }
95 >
96 > const mergeResult = merge(localPrompts, remotePrompts, lastSyncPrompts);
97 > return this.getResourcePreviews(mergeResult, local, remotePrompts || {}, lastSyncPrompts || {});
98 > }
100 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
101 const lastSync: IStringDictionary<string> | null = lastSyncUserData.syncData ? this.parsePrompts(lastSyncUserData.syncData) : null;
102 if (lastSync === null) {
108 return Object.keys(mergeResult.remote.added).length > 0 || Object.keys(mergeResult.remote.updated).length > 0 || mergeResult.remote.removed.length > 0 || mergeResult.conflicts.length > 0;
109 }
111 > protected async getMergeResult(resourcePreview: IPromptsResourcePreview, token: CancellationToken): Promise<IMergeResult> {
112 > return resourcePreview.previewResult; promptsSync.ts
113 > }
115 > protected async getAcceptResult(resourcePreview: IPromptsResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
117 > /* Accept local resource */
118 > if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }))) {
119 return {
120 content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
125 };
126 }
128 > /* Accept remote resource */
129 > if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }))) {
130 return {
131 content: resourcePreview.remoteContent,
136 };
137 }
139 > /* Accept preview resource */
140 > if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder)) {
141 > if (content === undefined) {
142 > return {
143 > content: resourcePreview.previewResult.content,
144 > localChange: resourcePreview.previewResult.localChange,
145 > remoteChange: resourcePreview.previewResult.remoteChange,
146 > };
147 > } else {
148 return {
149 content,
156 };
157 }
158 > } promptsSync.ts
159
160 throw new Error(`Invalid Resource: ${resource.toString()}`);
161 > } promptsSync.ts
163 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [IPromptsResourcePreview, IAcceptResult][], force: boolean): Promise<void> {
164 > const accptedResourcePreviews: IPromptsAcceptedResourcePreview[] = resourcePreviews.map(([resourcePreview, acceptResult]) => ({ ...resourcePreview, acceptResult })); promptsSync.ts
165 > if (accptedResourcePreviews.every(({ localChange, remoteChange }) => localChange === Change.None && remoteChange === Change.None)) {
166 this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing prompts.`);
167 }
169 > if (accptedResourcePreviews.some(({ localChange }) => localChange !== Change.None)) {
170 // back up all prompts
171 await this.updateLocalBackup(accptedResourcePreviews);
172 await this.updateLocalPrompts(accptedResourcePreviews, force);
173 }
175 > if (accptedResourcePreviews.some(({ remoteChange }) => remoteChange !== Change.None)) {
176 > remoteUserData = await this.updateRemotePrompts(accptedResourcePreviews, remoteUserData, force); promptsSync.ts
177 > }
179 > if (lastSyncUserData?.ref !== remoteUserData.ref) {
180 > // update last sync
181 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized prompts...`);
182 > await this.updateLastSyncUserData(remoteUserData);
183 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized prompts`);
184 > }
185 >
186 > for (const { previewResource } of accptedResourcePreviews) {
187 > // Delete the preview promptsSync.ts
188 > try {
189 > await this.fileService.del(previewResource);
190 > } catch (e) { /* ignore */ }
191 > }
193 > }
195 > private getResourcePreviews(
196 > mergeResult: IPromptsMergeResult, promptsSync.ts
197 > localFileContent: IStringDictionary<IFileContent>,
198 > remote: IStringDictionary<string>,
199 > base: IStringDictionary<string>,
200 > ): IPromptsResourcePreview[] {
201 > const resourcePreviews: Map<string, IPromptsResourcePreview> = new Map<string, IPromptsResourcePreview>();
202 >
203 > /* Prompts added remotely -> add locally */
204 > for (const key of Object.keys(mergeResult.local.added)) {
205 const previewResult: IMergeResult = {
206 content: mergeResult.local.added[key],
224 });
225 }
227 > /* Prompts updated remotely -> update locally */
228 > for (const key of Object.keys(mergeResult.local.updated)) {
229 const previewResult: IMergeResult = {
230 content: mergeResult.local.updated[key],
249 });
250 }
252 > /* Prompts removed remotely -> remove locally */
253 > for (const key of mergeResult.local.removed) {
254 const previewResult: IMergeResult = {
255 content: null,
274 });
275 }
277 > /* Prompts added locally -> add remotely */
278 > for (const key of Object.keys(mergeResult.remote.added)) {
279 > const previewResult: IMergeResult = { promptsSync.ts
280 > content: mergeResult.remote.added[key],
281 > hasConflicts: false,
282 > localChange: Change.None,
283 > remoteChange: Change.Added,
284 > };
285 > const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
286 > resourcePreviews.set(key, {
287 > baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
288 > baseContent: base[key] ?? null,
289 > localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
290 > fileContent: localFileContent[key],
291 > localContent,
292 > remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
293 > remoteContent: null,
294 > previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
295 > previewResult,
296 > localChange: previewResult.localChange,
297 > remoteChange: previewResult.remoteChange,
298 > acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
299 > });
300 > }
302 > /* Prompts updated locally -> update remotely */
303 > for (const key of Object.keys(mergeResult.remote.updated)) {
304 const previewResult: IMergeResult = {
305 content: mergeResult.remote.updated[key],
324 });
325 }
327 > /* Prompts removed locally -> remove remotely */
328 > for (const key of mergeResult.remote.removed) {
329 const previewResult: IMergeResult = {
330 content: null,
348 });
349 }
351 > /* Prompts with conflicts */
352 > for (const key of mergeResult.conflicts) {
353 const previewResult: IMergeResult = {
354 content: base[key] ?? null,
373 });
374 }
376 > /* Unmodified Prompts */
377 > for (const key of Object.keys(localFileContent)) {
378 > if (!resourcePreviews.has(key)) { promptsSync.ts
379 const previewResult: IMergeResult = {
380 content: localFileContent[key] ? localFileContent[key].value.toString() : null,
399 });
400 }
401 > } promptsSync.ts
403 > return [...resourcePreviews.values()];
404 > }
406 > override async resolveContent(uri: URI): Promise<string | null> {
407 if (this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }))
408 || this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }))
413 return null;
414 }
416 > async hasLocalData(): Promise<boolean> {
417 try {
418 const local = await this.getPromptsFileContents();
425 return false;
426 }
428 > private async updateLocalBackup(resourcePreviews: IFileResourcePreview[]): Promise<void> {
429 const local: IStringDictionary<IFileContent> = {};
430 for (const resourcePreview of resourcePreviews) {
435 await this.backupLocal(JSON.stringify(this.toPromptContents(local)));
436 }
438 > private async updateLocalPrompts(resourcePreviews: IPromptsAcceptedResourcePreview[], force: boolean): Promise<void> {
439 for (const { fileContent, acceptResult, localResource, remoteResource, localChange } of resourcePreviews) {
440 if (localChange !== Change.None) {
465 }
466 }
468 > private async updateRemotePrompts(resourcePreviews: IPromptsAcceptedResourcePreview[], remoteUserData: IRemoteUserData, forcePush: boolean): Promise<IRemoteUserData> {
469 > const currentPrompts: IStringDictionary<string> = remoteUserData.syncData ? this.parsePrompts(remoteUserData.syncData) : {}; promptsSync.ts
470 > const newPrompts: IStringDictionary<string> = deepClone(currentPrompts);
471 >
472 > for (const { acceptResult, localResource, remoteResource, remoteChange } of resourcePreviews) {
473 > if (remoteChange !== Change.None) {
474 > const key = localResource ? this.extUri.basename(localResource) : this.extUri.basename(remoteResource);
475 > if (remoteChange === Change.Deleted) {
476 delete newPrompts[key];
477 > } else { promptsSync.ts
478 > newPrompts[key] = acceptResult.content!;
479 > }
480 > }
481 > }
482 >
483 > if (!areSame(currentPrompts, newPrompts)) {
484 > // update remote
485 > this.logService.trace(`${this.syncResourceLogLabel}: Updating remote prompts...`);
486 > remoteUserData = await this.updateRemoteUserData(JSON.stringify(newPrompts), forcePush ? null : remoteUserData.ref);
487 > this.logService.info(`${this.syncResourceLogLabel}: Updated remote prompts`);
488 > }
489 > return remoteUserData;
490 > }
492 > private parsePrompts(syncData: ISyncData): IStringDictionary<string> {
493 return parsePrompts(syncData);
494 }
496 > private toPromptContents(fileContents: IStringDictionary<IFileContent>): IStringDictionary<string> {
497 > const prompts: IStringDictionary<string> = {}; promptsSync.ts
498 > for (const key of Object.keys(fileContents)) {
499 > prompts[key] = fileContents[key].value.toString(); promptsSync.ts
500 > }
501 > return prompts; promptsSync.ts
502 > }
504 > private async getPromptsFileContents(): Promise<IStringDictionary<IFileContent>> {
505 > const prompts: IStringDictionary<IFileContent> = {}; promptsSync.ts
506 > let stat: IFileStat;
507 > try {
508 > stat = await this.fileService.resolve(this.promptsFolder);
509 > } catch (e) {
510 // No prompts
511 if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
515 }
516 }
517 > for (const entry of stat.children || []) { promptsSync.ts
518 > const resource = entry.resource; promptsSync.ts
519 > const path = resource.path;
520 > if (['.prompt.md', '.instructions.md', '.chatmode.md', '.agent.md'].some(ext => path.endsWith(ext))) {
521 > const key = this.extUri.relativePath(this.promptsFolder, resource)!;
522 > const content = await this.fileService.readFile(resource);
523 > prompts[key] = content;
524 > }
525 > }
526 >
527 > return prompts;
528 > } promptsSync.ts
529 > } promptsSync.ts
src/vs/platform/userDataSync/common/settingsSync.ts 258 covered LOC · 49 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- settingsSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { distinct } from '../../../base/common/arrays.js';
7 > import { VSBuffer } from '../../../base/common/buffer.js';
8 > import { CancellationToken } from '../../../base/common/cancellation.js';
9 > import { Event } from '../../../base/common/event.js';
10 > import { URI } from '../../../base/common/uri.js';
11 > import { localize } from '../../../nls.js';
12 > import { ConfigurationTarget, IConfigurationService } from '../../configuration/common/configuration.js';
13 > import { ConfigurationModelParser } from '../../configuration/common/configurationModels.js';
14 > import { IEnvironmentService } from '../../environment/common/environment.js';
15 > import { IExtensionManagementService } from '../../extensionManagement/common/extensionManagement.js';
16 > import { ExtensionType } from '../../extensions/common/extensions.js';
17 > import { FileOperationError, FileOperationResult, IFileService } from '../../files/common/files.js';
18 > import { IStorageService } from '../../storage/common/storage.js';
19 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
20 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
21 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
22 > import { AbstractInitializer, AbstractJsonFileSynchroniser, IAcceptResult, IFileResourcePreview, IMergeResult } from './abstractSynchronizer.js';
23 > import { getIgnoredSettings, isEmpty, merge, updateIgnoredSettings } from './settingsMerge.js';
24 > import { Change, IRemoteUserData, IUserDataSyncLocalStoreService, IUserDataSyncConfiguration, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, IUserDataSyncUtilService, SyncResource, UserDataSyncError, UserDataSyncErrorCode, USER_DATA_SYNC_CONFIGURATION_SCOPE, USER_DATA_SYNC_SCHEME, getIgnoredSettingsForExtension, IUserData } from './userDataSync.js';
25 >
26 > interface ISettingsResourcePreview extends IFileResourcePreview {
27 > previewResult: IMergeResult;
28 > }
29 >
30 > export interface ISettingsSyncContent {
31 > settings: string;
32 > }
33 >
34 function isSettingsSyncContent(thing: any): thing is ISettingsSyncContent {
35 return thing
37 && Object.keys(thing).length === 1;
38 }
40 > export function parseSettingsSyncContent(syncContent: string): ISettingsSyncContent {
41 const parsed = <ISettingsSyncContent>JSON.parse(syncContent);
42 return isSettingsSyncContent(parsed) ? parsed : /* migrate */ { settings: syncContent };
43 }
45 > export class SettingsSynchroniser extends AbstractJsonFileSynchroniser implements IUserDataSynchroniser {
46 >
47 > /* Version 2: Change settings from `sync.${setting}` to `settingsSync.{setting}` */
48 > protected readonly version: number = 2;
49 > readonly previewResource: URI = this.extUri.joinPath(this.syncPreviewFolder, 'settings.json');
50 > readonly baseResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' });
51 > readonly localResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' });
52 > readonly remoteResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' });
53 > readonly acceptedResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' });
54 >
55 > constructor(
56 > private readonly profile: IUserDataProfile, settingsSync.ts
57 > collection: string | undefined,
58 > @IFileService fileService: IFileService,
59 > @IEnvironmentService environmentService: IEnvironmentService,
60 > @IStorageService storageService: IStorageService,
61 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
62 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
63 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
64 > @IUserDataSyncUtilService userDataSyncUtilService: IUserDataSyncUtilService,
65 > @IConfigurationService configurationService: IConfigurationService,
66 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
67 > @ITelemetryService telemetryService: ITelemetryService,
68 > @IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
69 > @IUriIdentityService uriIdentityService: IUriIdentityService,
70 > ) {
71 > super(profile.settingsResource, { syncResource: SyncResource.Settings, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, userDataSyncUtilService, configurationService, uriIdentityService);
72 > }
73 >
74 > async getRemoteUserDataSyncConfiguration(refOrLatestData: string | IUserData | null): Promise<IUserDataSyncConfiguration> {
75 const lastSyncUserData = await this.getLastSyncUserData();
76 const remoteUserData = await this.getLatestRemoteUserData(refOrLatestData, lastSyncUserData);
82 return parser.configurationModel.getValue(USER_DATA_SYNC_CONFIGURATION_SCOPE) || {};
83 }
85 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<ISettingsResourcePreview[]> {
86 > const fileContent = await this.getLocalFileContent(); settingsSync.ts
87 > const formattingOptions = await this.getFormattingOptions();
88 > const remoteSettingsSyncContent = this.getSettingsSyncContent(remoteUserData);
89 >
90 > // Use remote data as last sync data if last sync data does not exist and remote data is from same machine
91 > lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
92 > const lastSettingsSyncContent: ISettingsSyncContent | null = lastSyncUserData ? this.getSettingsSyncContent(lastSyncUserData) : null;
93 > const ignoredSettings = await this.getIgnoredSettings();
94 >
95 > let mergedContent: string | null = null;
96 > let hasLocalChanged: boolean = false;
97 > let hasRemoteChanged: boolean = false;
98 > let hasConflicts: boolean = false;
99 >
100 > if (remoteSettingsSyncContent) {
101 let localContent: string = fileContent ? fileContent.value.toString().trim() : '{}';
102 localContent = localContent || '{}';
109 hasConflicts = result.hasConflicts;
110 }
112 > // First time syncing to remote
113 > else if (fileContent) {
114 > this.logService.trace(`${this.syncResourceLogLabel}: Remote settings does not exist. Synchronizing settings for the first time.`); settingsSync.ts
115 > mergedContent = fileContent.value.toString().trim() || '{}';
116 > this.validateContent(mergedContent);
117 > hasRemoteChanged = true;
118 > }
120 > const localContent = fileContent ? fileContent.value.toString() : null; settingsSync.ts
121 > const baseContent = lastSettingsSyncContent?.settings ?? null;
122 >
123 > const previewResult = {
124 > content: hasConflicts ? baseContent : mergedContent,
125 > localChange: hasLocalChanged ? Change.Modified : Change.None,
126 > remoteChange: hasRemoteChanged ? Change.Modified : Change.None,
127 > hasConflicts
128 > };
129 >
130 > return [{
131 > fileContent,
132 >
133 > baseResource: this.baseResource,
134 > baseContent,
135 >
136 > localResource: this.localResource,
137 > localContent,
138 > localChange: previewResult.localChange,
139 >
140 > remoteResource: this.remoteResource,
141 > remoteContent: remoteSettingsSyncContent ? remoteSettingsSyncContent.settings : null,
142 > remoteChange: previewResult.remoteChange,
143 >
144 > previewResource: this.previewResource,
145 > previewResult,
146 > acceptedResource: this.acceptedResource,
147 > }];
148 > }
150 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
151 const lastSettingsSyncContent: ISettingsSyncContent | null = this.getSettingsSyncContent(lastSyncUserData);
152 if (lastSettingsSyncContent === null) {
161 return result.remoteContent !== null;
162 }
164 > protected async getMergeResult(resourcePreview: ISettingsResourcePreview, token: CancellationToken): Promise<IMergeResult> {
165 > const formatUtils = await this.getFormattingOptions(); settingsSync.ts
166 > const ignoredSettings = await this.getIgnoredSettings();
167 > return {
168 > ...resourcePreview.previewResult,
169 >
170 > // remove ignored settings from the preview content
171 > content: resourcePreview.previewResult.content ? updateIgnoredSettings(resourcePreview.previewResult.content, '{}', ignoredSettings, formatUtils) : null
172 > };
173 > }
175 > protected async getAcceptResult(resourcePreview: ISettingsResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
177 > const formattingOptions = await this.getFormattingOptions();
178 > const ignoredSettings = await this.getIgnoredSettings();
179 >
180 > /* Accept local resource */
181 > if (this.extUri.isEqual(resource, this.localResource)) {
182 return {
183 /* Remove ignored settings */
187 };
188 }
190 > /* Accept remote resource */
191 > if (this.extUri.isEqual(resource, this.remoteResource)) {
192 return {
193 /* Update ignored settings from local file content */
197 };
198 }
200 > /* Accept preview resource */
201 > if (this.extUri.isEqual(resource, this.previewResource)) {
202 > if (content === undefined) {
203 > return {
204 > content: resourcePreview.previewResult.content,
205 > localChange: resourcePreview.previewResult.localChange,
206 > remoteChange: resourcePreview.previewResult.remoteChange,
207 > };
208 > } else {
209 return {
210 /* Add ignored settings from local file content */
214 };
215 }
216 > } settingsSync.ts
217
218 throw new Error(`Invalid Resource: ${resource.toString()}`);
219 > } settingsSync.ts
221 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [ISettingsResourcePreview, IAcceptResult][], force: boolean): Promise<void> {
222 > const { fileContent } = resourcePreviews[0][0]; settingsSync.ts
223 > let { content, localChange, remoteChange } = resourcePreviews[0][1];
224 >
225 > if (localChange === Change.None && remoteChange === Change.None) {
226 this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing settings.`);
227 }
229 > content = content ? content.trim() : '{}';
230 > content = content || '{}';
231 > this.validateContent(content);
232 >
233 > if (localChange !== Change.None) {
234 this.logService.trace(`${this.syncResourceLogLabel}: Updating local settings...`);
235 if (fileContent) {
240 this.logService.info(`${this.syncResourceLogLabel}: Updated local settings`);
241 }
243 > if (remoteChange !== Change.None) {
244 > const formatUtils = await this.getFormattingOptions(); settingsSync.ts
245 > // Update ignored settings from remote
246 > const remoteSettingsSyncContent = this.getSettingsSyncContent(remoteUserData);
247 > const ignoredSettings = await this.getIgnoredSettings(content);
248 > content = updateIgnoredSettings(content, remoteSettingsSyncContent ? remoteSettingsSyncContent.settings : '{}', ignoredSettings, formatUtils);
249 > this.logService.trace(`${this.syncResourceLogLabel}: Updating remote settings...`);
250 > remoteUserData = await this.updateRemoteUserData(JSON.stringify(this.toSettingsSyncContent(content)), force ? null : remoteUserData.ref);
251 > this.logService.info(`${this.syncResourceLogLabel}: Updated remote settings`);
252 > }
254 > // Delete the preview
255 > try {
256 > await this.fileService.del(this.previewResource);
257 > } catch (e) { /* ignore */ }
258 >
259 > if (lastSyncUserData?.ref !== remoteUserData.ref) {
260 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized settings...`);
261 > await this.updateLastSyncUserData(remoteUserData);
262 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized settings`);
263 > }
264 >
265 > }
267 > async hasLocalData(): Promise<boolean> {
268 try {
269 const localFileContent = await this.getLocalFileContent();
278 return false;
279 }
281 > async resolveContent(uri: URI): Promise<string | null> {
282 if (this.extUri.isEqual(this.remoteResource, uri)
283 || this.extUri.isEqual(this.localResource, uri)
289 return null;
290 }
292 > protected override async resolvePreviewContent(resource: URI): Promise<string | null> {
293 let content = await super.resolvePreviewContent(resource);
294 if (content) {
300 return content;
301 }
303 > private getSettingsSyncContent(remoteUserData: IRemoteUserData): ISettingsSyncContent | null {
304 > return remoteUserData.syncData ? this.parseSettingsSyncContent(remoteUserData.syncData.content) : null; settingsSync.ts
305 > }
307 > private parseSettingsSyncContent(syncContent: string): ISettingsSyncContent | null {
308 try {
309 return parseSettingsSyncContent(syncContent);
313 return null;
314 }
316 > private toSettingsSyncContent(settings: string): ISettingsSyncContent {
317 > return { settings }; settingsSync.ts
318 > }
320 > private coreIgnoredSettings: Promise<string[]> | undefined = undefined;
321 > private systemExtensionsIgnoredSettings: Promise<string[]> | undefined = undefined;
322 > private userExtensionsIgnoredSettings: Promise<string[]> | undefined = undefined;
323 > private async getIgnoredSettings(content?: string): Promise<string[]> { settingsSync.ts
324 > if (!this.coreIgnoredSettings) { settingsSync.ts
325 > this.coreIgnoredSettings = this.userDataSyncUtilService.resolveDefaultCoreIgnoredSettings();
326 > }
327 > if (!this.systemExtensionsIgnoredSettings) {
328 > this.systemExtensionsIgnoredSettings = this.getIgnoredSettingForSystemExtensions();
329 > }
330 > if (!this.userExtensionsIgnoredSettings) {
331 > this.userExtensionsIgnoredSettings = this.getIgnoredSettingForUserExtensions();
332 > const disposable = this._register(Event.any<any>(
333 > Event.filter(this.extensionManagementService.onDidInstallExtensions, (e => e.some(({ local }) => !!local))),
334 > Event.filter(this.extensionManagementService.onDidUninstallExtension, (e => !e.error)))(() => {
335 disposable.dispose();
336 this.userExtensionsIgnoredSettings = undefined;
337 > })); settingsSync.ts
338 > }
339 > const defaultIgnoredSettings = (await Promise.all([this.coreIgnoredSettings, this.systemExtensionsIgnoredSettings, this.userExtensionsIgnoredSettings])).flat();
340 > return getIgnoredSettings(defaultIgnoredSettings, this.configurationService, content);
341 > }
343 > private async getIgnoredSettingForSystemExtensions(): Promise<string[]> {
344 > const systemExtensions = await this.extensionManagementService.getInstalled(ExtensionType.System); settingsSync.ts
345 > return distinct(systemExtensions.map(e => getIgnoredSettingsForExtension(e.manifest)).flat());
346 > }
348 > private async getIgnoredSettingForUserExtensions(): Promise<string[]> {
349 > const userExtensions = await this.extensionManagementService.getInstalled(ExtensionType.User, this.profile.extensionsResource); settingsSync.ts
350 > return distinct(userExtensions.map(e => getIgnoredSettingsForExtension(e.manifest)).flat());
351 > }
353 > private validateContent(content: string): void {
354 > if (this.hasErrors(content, false)) { settingsSync.ts
355 throw new UserDataSyncError(localize('errorInvalidSettings', "Unable to sync settings as there are errors/warning in settings file."), UserDataSyncErrorCode.LocalInvalidContent, this.resource);
356 }
357 > } settingsSync.ts
359 > }
360 >
361 > export class SettingsInitializer extends AbstractInitializer {
362 >
363 > constructor(
364 @IFileService fileService: IFileService,
365 @IUserDataProfilesService userDataProfilesService: IUserDataProfilesService,
371 super(SyncResource.Settings, userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
372 }
374 > protected async doInitialize(remoteUserData: IRemoteUserData): Promise<void> {
375 const settingsSyncContent = remoteUserData.syncData ? this.parseSettingsSyncContent(remoteUserData.syncData.content) : null;
376 if (!settingsSyncContent) {
389 await this.updateLastSyncUserData(remoteUserData);
390 }
392 > private async isEmpty(): Promise<boolean> {
393 try {
394 const fileContent = await this.fileService.readFile(this.userDataProfilesService.defaultProfile.settingsResource);
398 }
399 }
401 > private parseSettingsSyncContent(syncContent: string): ISettingsSyncContent | null {
402 try {
403 return parseSettingsSyncContent(syncContent);
src/vs/platform/configuration/common/configuration.ts 254 covered LOC · 34 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- configuration.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { assertNever } from '../../../base/common/assert.js';
7 > import { IStringDictionary } from '../../../base/common/collections.js';
8 > import { Event } from '../../../base/common/event.js';
9 > import * as types from '../../../base/common/types.js';
10 > import { URI, UriComponents } from '../../../base/common/uri.js';
11 > import { createDecorator } from '../../instantiation/common/instantiation.js';
12 > import { IWorkspaceFolder } from '../../workspace/common/workspace.js';
13 >
14 > export const IConfigurationService = createDecorator<IConfigurationService>('configurationService');
15 >
16 > export function isConfigurationOverrides(obj: unknown): obj is IConfigurationOverrides {
17 > const thing = obj as IConfigurationOverrides; configuration.ts
18 > return thing
19 > && typeof thing === 'object' configuration.ts
20 && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === 'string')
21 && (!thing.resource || thing.resource instanceof URI);
24 > export interface IConfigurationOverrides {
25 > overrideIdentifier?: string | null;
26 > resource?: URI | null;
27 > }
28 >
29 > export function isConfigurationUpdateOverrides(obj: unknown): obj is IConfigurationUpdateOverrides {
30 const thing = obj as IConfigurationUpdateOverrides | IConfigurationOverrides;
31 return thing
35 && (!thing.resource || thing.resource instanceof URI);
36 }
38 > export type IConfigurationUpdateOverrides = Omit<IConfigurationOverrides, 'overrideIdentifier'> & { overrideIdentifiers?: string[] | null };
39 >
40 > export const enum ConfigurationTarget {
41 > APPLICATION = 1,
42 > USER,
43 > USER_LOCAL,
44 > USER_REMOTE,
45 > WORKSPACE,
46 > WORKSPACE_FOLDER,
47 > DEFAULT,
48 > MEMORY
49 > }
50 > export function ConfigurationTargetToString(configurationTarget: ConfigurationTarget) {
51 switch (configurationTarget) {
52 case ConfigurationTarget.APPLICATION: return 'APPLICATION';
60 }
61 }
63 > export interface IConfigurationChange {
64 > keys: string[];
65 > overrides: [string, string[]][];
66 > }
67 >
68 > export interface IConfigurationChangeEvent {
69 >
70 > readonly source: ConfigurationTarget;
71 > readonly affectedKeys: ReadonlySet<string>;
72 > readonly change: IConfigurationChange;
73 >
74 > affectsConfiguration(configuration: string, overrides?: IConfigurationOverrides): boolean;
75 > }
76 >
77 > export interface IInspectValue<T> {
78 > readonly value?: T;
79 > readonly override?: T;
80 > readonly overrides?: { readonly identifiers: string[]; readonly value: T }[];
81 > }
82 >
83 > export interface IConfigurationValue<T> {
84 >
85 > readonly defaultValue?: T;
86 > readonly applicationValue?: T;
87 > readonly userValue?: T;
88 > readonly userLocalValue?: T;
89 > readonly userRemoteValue?: T;
90 > readonly workspaceValue?: T;
91 > readonly workspaceFolderValue?: T;
92 > readonly memoryValue?: T;
93 > readonly policyValue?: T;
94 > readonly value?: T;
95 >
96 > readonly default?: IInspectValue<T>;
97 > readonly application?: IInspectValue<T>;
98 > readonly user?: IInspectValue<T>;
99 > readonly userLocal?: IInspectValue<T>;
100 > readonly userRemote?: IInspectValue<T>;
101 > readonly workspace?: IInspectValue<T>;
102 > readonly workspaceFolder?: IInspectValue<T>;
103 > readonly memory?: IInspectValue<T>;
104 > readonly policy?: { value?: T };
105 >
106 > readonly overrideIdentifiers?: string[];
107 > }
108 >
109 > export function getConfigValueInTarget<T>(configValue: IConfigurationValue<T>, scope: ConfigurationTarget): T | undefined {
110 switch (scope) {
111 case ConfigurationTarget.APPLICATION:
129 }
130 }
132 > export function isConfigured<T>(configValue: IConfigurationValue<T>): configValue is IConfigurationValue<T> & { value: T } {
133 return configValue.applicationValue !== undefined ||
134 configValue.userValue !== undefined ||
138 configValue.workspaceFolderValue !== undefined;
139 }
141 > export interface IConfigurationUpdateOptions {
142 > /**
143 > * If `true`, do not notifies the error to user by showing the message box. Default is `false`.
144 > */
145 > donotNotifyError?: boolean;
146 > /**
147 > * How to handle dirty file when updating the configuration.
148 > */
149 > handleDirtyFile?: 'save' | 'revert';
150 > }
151 >
152 > export interface IConfigurationService {
153 > readonly _serviceBrand: undefined;
154 >
155 > readonly onDidChangeConfiguration: Event<IConfigurationChangeEvent>;
156 >
157 > getConfigurationData(): IConfigurationData | null;
158 >
159 > /**
160 > * Fetches the value of the section for the given overrides.
161 > * Value can be of native type or an object keyed off the section name.
162 > *
163 > * @param section - Section of the configuration. Can be `null` or `undefined`.
164 > * @param overrides - Overrides that has to be applied while fetching
165 > *
166 > */
167 > getValue<T>(): T;
168 > getValue<T>(section: string): T;
169 > getValue<T>(overrides: IConfigurationOverrides): T;
170 > getValue<T>(section: string, overrides: IConfigurationOverrides): T;
171 >
172 > /**
173 > * Update a configuration value.
174 > *
175 > * Use `target` to update the configuration in a specific `ConfigurationTarget`.
176 > *
177 > * Use `overrides` to update the configuration for a resource or for override identifiers or both.
178 > *
179 > * Passing a resource through overrides will update the configuration in the workspace folder containing that resource.
180 > *
181 > * *Note 1:* Updating configuration to a default value will remove the configuration from the requested target. If not target is passed, it will be removed from all writeable targets.
182 > *
183 > * *Note 2:* Use `undefined` value to remove the configuration from the given target. If not target is passed, it will be removed from all writeable targets.
184 > *
185 > * Use `donotNotifyError` and set it to `true` to surpresss errors.
186 > *
187 > * @param key setting to be updated
188 > * @param value The new value
189 > */
190 > updateValue(key: string, value: unknown): Promise<void>;
191 > updateValue(key: string, value: unknown, target: ConfigurationTarget): Promise<void>;
192 > updateValue(key: string, value: unknown, overrides: IConfigurationOverrides | IConfigurationUpdateOverrides): Promise<void>;
193 > updateValue(key: string, value: unknown, overrides: IConfigurationOverrides | IConfigurationUpdateOverrides, target: ConfigurationTarget, options?: IConfigurationUpdateOptions): Promise<void>;
194 >
195 > inspect<T>(key: string, overrides?: IConfigurationOverrides): IConfigurationValue<Readonly<T>>;
196 >
197 > reloadConfiguration(target?: ConfigurationTarget | IWorkspaceFolder): Promise<void>;
198 >
199 > keys(): {
200 > default: string[];
201 > policy: string[];
202 > user: string[];
203 > workspace: string[];
204 > workspaceFolder: string[];
205 > memory?: string[];
206 > };
207 > }
208 >
209 > export interface IConfigurationModel {
210 > contents: IStringDictionary<unknown>;
211 > keys: string[];
212 > overrides: IOverrides[];
213 > raw?: ReadonlyArray<IStringDictionary<unknown>> | IStringDictionary<unknown>;
214 > }
215 >
216 > export interface IOverrides {
217 > keys: string[];
218 > contents: IStringDictionary<unknown>;
219 > identifiers: string[];
220 > }
221 >
222 > export interface IConfigurationData {
223 > defaults: IConfigurationModel;
224 > policy: IConfigurationModel;
225 > application: IConfigurationModel;
226 > userLocal: IConfigurationModel;
227 > userRemote: IConfigurationModel;
228 > workspace: IConfigurationModel;
229 > folders: [UriComponents, IConfigurationModel][];
230 > }
231 >
232 > export interface IConfigurationCompareResult {
233 > added: string[];
234 > removed: string[];
235 > updated: string[];
236 > overrides: [string, string[]][];
237 > }
238 >
239 > export function toValuesTree(properties: IStringDictionary<unknown>, conflictReporter: (message: string) => void): IStringDictionary<unknown> {
240 > const root = Object.create(null); configuration.ts
241 >
242 > for (const key in properties) {
243 addToValueTree(root, key, properties[key], conflictReporter);
244 }
246 > return root;
247 > }
249 > export function addToValueTree(settingsTreeRoot: IStringDictionary<unknown>, key: string, value: unknown, conflictReporter: (message: string) => void): void {
250 > const segments = key.split('.'); configuration.ts
251 > const last = segments.pop()!;
252 >
253 > let curr: IStringDictionary<unknown> = settingsTreeRoot;
254 > for (let i = 0; i < segments.length; i++) {
255 > const s = segments[i]; configuration.ts
256 > let obj = curr[s];
257 > switch (typeof obj) {
258 > case 'undefined':
259 > obj = curr[s] = Object.create(null); configuration.ts
260 > break;
261 > case 'object': configuration.ts
262 > if (obj === null) { configuration.ts
263 conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is null`);
264 return;
265 }
266 > break; configuration.ts
267 > default: configuration.ts
268 conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join('.')} is ${JSON.stringify(obj)}`);
269 return;
271 > curr = obj as IStringDictionary<unknown>; configuration.ts
272 > }
274 > if (typeof curr === 'object' && curr !== null) {
275 > try {
276 > (curr as IStringDictionary<unknown>)[last] = value; // workaround https://github.com/microsoft/vscode/issues/13606
277 > } catch (e) {
278 conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
279 }
280 > } else { configuration.ts
281 conflictReporter(`Ignoring ${key} as ${segments.join('.')} is ${JSON.stringify(curr)}`);
282 }
285 > export function removeFromValueTree(valueTree: IStringDictionary<unknown>, key: string): void {
286 const segments = key.split('.');
287 doRemoveFromValueTree(valueTree, segments);
288 }
290 function doRemoveFromValueTree(valueTree: IStringDictionary<unknown> | unknown, segments: string[]): void {
291 if (!valueTree) {
311 }
312 }
314 > /**
315 > * A helper function to get the configuration value with a specific settings path (e.g. config.some.setting)
316 > */
317 > export function getConfigurationValue<T>(config: IStringDictionary<unknown>, settingPath: string): T | undefined;
318 > export function getConfigurationValue<T>(config: IStringDictionary<unknown>, settingPath: string, defaultValue: T): T;
319 > export function getConfigurationValue<T>(config: IStringDictionary<unknown>, settingPath: string, defaultValue?: T): T | undefined {
320 > function accessSetting(config: IStringDictionary<unknown>, path: string[]): unknown { configuration.ts
321 > let current: unknown = config;
322 > for (const component of path) {
323 > if (typeof current !== 'object' || current === null) {
324 > return undefined; configuration.ts
325 > }
326 > current = (current as IStringDictionary<unknown>)[component]; configuration.ts
327 > }
328 > return current as T; configuration.ts
330 >
331 > const path = settingPath.split('.');
332 > const result = accessSetting(config, path);
333 >
334 > return typeof result === 'undefined' ? defaultValue : result as T;
335 > }
337 > export function merge(base: IStringDictionary<unknown>, add: IStringDictionary<unknown>, overwrite: boolean): void {
338 Object.keys(add).forEach(key => {
339 if (key !== '__proto__') {
350 });
351 }
353 > export function getLanguageTagSettingPlainKey(settingKey: string) {
354 return settingKey
355 .replace(/^\[/, '')
src/vs/platform/userDataSync/common/snippetsSync.ts 251 covered LOC · 57 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- snippetsSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer } from '../../../base/common/buffer.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { IStringDictionary } from '../../../base/common/collections.js';
9 > import { Event } from '../../../base/common/event.js';
10 > import { deepClone } from '../../../base/common/objects.js';
11 > import { URI } from '../../../base/common/uri.js';
12 > import { IConfigurationService } from '../../configuration/common/configuration.js';
13 > import { IEnvironmentService } from '../../environment/common/environment.js';
14 > import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStat } from '../../files/common/files.js';
15 > import { IStorageService } from '../../storage/common/storage.js';
16 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
17 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
18 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
19 > import { AbstractInitializer, AbstractSynchroniser, IAcceptResult, IFileResourcePreview, IMergeResult } from './abstractSynchronizer.js';
20 > import { areSame, IMergeResult as ISnippetsMergeResult, merge } from './snippetsMerge.js';
21 > import { Change, IRemoteUserData, ISyncData, IUserDataSyncLocalStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource, USER_DATA_SYNC_SCHEME } from './userDataSync.js';
22 >
23 > interface ISnippetsResourcePreview extends IFileResourcePreview {
24 > previewResult: IMergeResult;
25 > }
26 >
27 > interface ISnippetsAcceptedResourcePreview extends IFileResourcePreview {
28 > acceptResult: IAcceptResult;
29 > }
30 >
31 > export function parseSnippets(syncData: ISyncData): IStringDictionary<string> {
32 return JSON.parse(syncData.content);
33 }
35 > export class SnippetsSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
36 >
37 > protected readonly version: number = 1;
38 > private readonly snippetsFolder: URI;
39 >
40 > constructor(
41 > profile: IUserDataProfile, snippetsSync.ts
42 > collection: string | undefined,
43 > @IEnvironmentService environmentService: IEnvironmentService,
44 > @IFileService fileService: IFileService,
45 > @IStorageService storageService: IStorageService,
46 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
47 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
48 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
49 > @IConfigurationService configurationService: IConfigurationService,
50 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
51 > @ITelemetryService telemetryService: ITelemetryService,
52 > @IUriIdentityService uriIdentityService: IUriIdentityService,
53 > ) {
54 > super({ syncResource: SyncResource.Snippets, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
55 > this.snippetsFolder = profile.snippetsHome;
56 > this._register(this.fileService.watch(environmentService.userRoamingDataHome));
57 > this._register(this.fileService.watch(this.snippetsFolder));
58 > this._register(Event.filter(this.fileService.onDidFilesChange, e => e.affects(this.snippetsFolder))(() => this.triggerLocalChange()));
59 > }
61 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<ISnippetsResourcePreview[]> {
62 > const local = await this.getSnippetsFileContents(); snippetsSync.ts
63 > const localSnippets = this.toSnippetsContents(local);
64 > const remoteSnippets: IStringDictionary<string> | null = remoteUserData.syncData ? this.parseSnippets(remoteUserData.syncData) : null;
65 >
66 > // Use remote data as last sync data if last sync data does not exist and remote data is from same machine
67 > lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
68 > const lastSyncSnippets: IStringDictionary<string> | null = lastSyncUserData && lastSyncUserData.syncData ? this.parseSnippets(lastSyncUserData.syncData) : null;
69 >
70 > if (remoteSnippets) {
71 this.logService.trace(`${this.syncResourceLogLabel}: Merging remote snippets with local snippets...`);
72 > } else { snippetsSync.ts
73 > this.logService.trace(`${this.syncResourceLogLabel}: Remote snippets does not exist. Synchronizing snippets for the first time.`);
74 > }
75 >
76 > const mergeResult = merge(localSnippets, remoteSnippets, lastSyncSnippets);
77 > return this.getResourcePreviews(mergeResult, local, remoteSnippets || {}, lastSyncSnippets || {});
78 > }
80 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
81 const lastSyncSnippets: IStringDictionary<string> | null = lastSyncUserData.syncData ? this.parseSnippets(lastSyncUserData.syncData) : null;
82 if (lastSyncSnippets === null) {
88 return Object.keys(mergeResult.remote.added).length > 0 || Object.keys(mergeResult.remote.updated).length > 0 || mergeResult.remote.removed.length > 0 || mergeResult.conflicts.length > 0;
89 }
91 > protected async getMergeResult(resourcePreview: ISnippetsResourcePreview, token: CancellationToken): Promise<IMergeResult> {
92 > return resourcePreview.previewResult; snippetsSync.ts
93 > }
95 > protected async getAcceptResult(resourcePreview: ISnippetsResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
97 > /* Accept local resource */
98 > if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }))) {
99 return {
100 content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
105 };
106 }
108 > /* Accept remote resource */
109 > if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }))) {
110 return {
111 content: resourcePreview.remoteContent,
116 };
117 }
119 > /* Accept preview resource */
120 > if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder)) {
121 > if (content === undefined) {
122 > return {
123 > content: resourcePreview.previewResult.content,
124 > localChange: resourcePreview.previewResult.localChange,
125 > remoteChange: resourcePreview.previewResult.remoteChange,
126 > };
127 > } else {
128 return {
129 content,
136 };
137 }
138 > } snippetsSync.ts
139
140 throw new Error(`Invalid Resource: ${resource.toString()}`);
141 > } snippetsSync.ts
143 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [ISnippetsResourcePreview, IAcceptResult][], force: boolean): Promise<void> {
144 > const accptedResourcePreviews: ISnippetsAcceptedResourcePreview[] = resourcePreviews.map(([resourcePreview, acceptResult]) => ({ ...resourcePreview, acceptResult })); snippetsSync.ts
145 > if (accptedResourcePreviews.every(({ localChange, remoteChange }) => localChange === Change.None && remoteChange === Change.None)) {
146 this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing snippets.`);
147 }
149 > if (accptedResourcePreviews.some(({ localChange }) => localChange !== Change.None)) {
150 // back up all snippets
151 await this.updateLocalBackup(accptedResourcePreviews);
152 await this.updateLocalSnippets(accptedResourcePreviews, force);
153 }
155 > if (accptedResourcePreviews.some(({ remoteChange }) => remoteChange !== Change.None)) {
156 > remoteUserData = await this.updateRemoteSnippets(accptedResourcePreviews, remoteUserData, force); snippetsSync.ts
157 > }
159 > if (lastSyncUserData?.ref !== remoteUserData.ref) {
160 > // update last sync
161 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized snippets...`);
162 > await this.updateLastSyncUserData(remoteUserData);
163 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized snippets`);
164 > }
165 >
166 > for (const { previewResource } of accptedResourcePreviews) {
167 > // Delete the preview snippetsSync.ts
168 > try {
169 > await this.fileService.del(previewResource);
170 > } catch (e) { /* ignore */ }
171 > }
173 > }
175 > private getResourcePreviews(snippetsMergeResult: ISnippetsMergeResult, localFileContent: IStringDictionary<IFileContent>, remoteSnippets: IStringDictionary<string>, baseSnippets: IStringDictionary<string>): ISnippetsResourcePreview[] {
176 > const resourcePreviews: Map<string, ISnippetsResourcePreview> = new Map<string, ISnippetsResourcePreview>(); snippetsSync.ts
177 >
178 > /* Snippets added remotely -> add locally */
179 > for (const key of Object.keys(snippetsMergeResult.local.added)) {
180 const previewResult: IMergeResult = {
181 content: snippetsMergeResult.local.added[key],
199 });
200 }
202 > /* Snippets updated remotely -> update locally */
203 > for (const key of Object.keys(snippetsMergeResult.local.updated)) {
204 const previewResult: IMergeResult = {
205 content: snippetsMergeResult.local.updated[key],
224 });
225 }
227 > /* Snippets removed remotely -> remove locally */
228 > for (const key of snippetsMergeResult.local.removed) {
229 const previewResult: IMergeResult = {
230 content: null,
249 });
250 }
252 > /* Snippets added locally -> add remotely */
253 > for (const key of Object.keys(snippetsMergeResult.remote.added)) {
254 > const previewResult: IMergeResult = { snippetsSync.ts
255 > content: snippetsMergeResult.remote.added[key],
256 > hasConflicts: false,
257 > localChange: Change.None,
258 > remoteChange: Change.Added,
259 > };
260 > const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
261 > resourcePreviews.set(key, {
262 > baseResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' }),
263 > baseContent: baseSnippets[key] ?? null,
264 > localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }),
265 > fileContent: localFileContent[key],
266 > localContent,
267 > remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }),
268 > remoteContent: null,
269 > previewResource: this.extUri.joinPath(this.syncPreviewFolder, key),
270 > previewResult,
271 > localChange: previewResult.localChange,
272 > remoteChange: previewResult.remoteChange,
273 > acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' })
274 > });
275 > }
277 > /* Snippets updated locally -> update remotely */
278 > for (const key of Object.keys(snippetsMergeResult.remote.updated)) {
279 const previewResult: IMergeResult = {
280 content: snippetsMergeResult.remote.updated[key],
299 });
300 }
302 > /* Snippets removed locally -> remove remotely */
303 > for (const key of snippetsMergeResult.remote.removed) {
304 const previewResult: IMergeResult = {
305 content: null,
323 });
324 }
326 > /* Snippets with conflicts */
327 > for (const key of snippetsMergeResult.conflicts) {
328 const previewResult: IMergeResult = {
329 content: baseSnippets[key] ?? null,
348 });
349 }
351 > /* Unmodified Snippets */
352 > for (const key of Object.keys(localFileContent)) {
353 > if (!resourcePreviews.has(key)) { snippetsSync.ts
354 const previewResult: IMergeResult = {
355 content: localFileContent[key] ? localFileContent[key].value.toString() : null,
374 });
375 }
376 > } snippetsSync.ts
378 > return [...resourcePreviews.values()];
379 > }
381 > override async resolveContent(uri: URI): Promise<string | null> {
382 if (this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }))
383 || this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }))
388 return null;
389 }
391 > async hasLocalData(): Promise<boolean> {
392 try {
393 const localSnippets = await this.getSnippetsFileContents();
400 return false;
401 }
403 > private async updateLocalBackup(resourcePreviews: IFileResourcePreview[]): Promise<void> {
404 const local: IStringDictionary<IFileContent> = {};
405 for (const resourcePreview of resourcePreviews) {
410 await this.backupLocal(JSON.stringify(this.toSnippetsContents(local)));
411 }
413 > private async updateLocalSnippets(resourcePreviews: ISnippetsAcceptedResourcePreview[], force: boolean): Promise<void> {
414 for (const { fileContent, acceptResult, localResource, remoteResource, localChange } of resourcePreviews) {
415 if (localChange !== Change.None) {
440 }
441 }
443 > private async updateRemoteSnippets(resourcePreviews: ISnippetsAcceptedResourcePreview[], remoteUserData: IRemoteUserData, forcePush: boolean): Promise<IRemoteUserData> {
444 > const currentSnippets: IStringDictionary<string> = remoteUserData.syncData ? this.parseSnippets(remoteUserData.syncData) : {}; snippetsSync.ts
445 > const newSnippets: IStringDictionary<string> = deepClone(currentSnippets);
446 >
447 > for (const { acceptResult, localResource, remoteResource, remoteChange } of resourcePreviews) {
448 > if (remoteChange !== Change.None) {
449 > const key = localResource ? this.extUri.basename(localResource) : this.extUri.basename(remoteResource);
450 > if (remoteChange === Change.Deleted) {
451 delete newSnippets[key];
452 > } else { snippetsSync.ts
453 > newSnippets[key] = acceptResult.content!;
454 > }
455 > }
456 > }
457 >
458 > if (!areSame(currentSnippets, newSnippets)) {
459 > // update remote
460 > this.logService.trace(`${this.syncResourceLogLabel}: Updating remote snippets...`);
461 > remoteUserData = await this.updateRemoteUserData(JSON.stringify(newSnippets), forcePush ? null : remoteUserData.ref);
462 > this.logService.info(`${this.syncResourceLogLabel}: Updated remote snippets`);
463 > }
464 > return remoteUserData;
465 > }
467 > private parseSnippets(syncData: ISyncData): IStringDictionary<string> {
468 return parseSnippets(syncData);
469 }
471 > private toSnippetsContents(snippetsFileContents: IStringDictionary<IFileContent>): IStringDictionary<string> {
472 > const snippets: IStringDictionary<string> = {}; snippetsSync.ts
473 > for (const key of Object.keys(snippetsFileContents)) {
474 > snippets[key] = snippetsFileContents[key].value.toString(); snippetsSync.ts
475 > }
476 > return snippets; snippetsSync.ts
477 > }
479 > private async getSnippetsFileContents(): Promise<IStringDictionary<IFileContent>> {
480 > const snippets: IStringDictionary<IFileContent> = {}; snippetsSync.ts
481 > let stat: IFileStat;
482 > try {
483 > stat = await this.fileService.resolve(this.snippetsFolder);
484 > } catch (e) {
485 // No snippets
486 if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
490 }
491 }
492 > for (const entry of stat.children || []) { snippetsSync.ts
493 > const resource = entry.resource; snippetsSync.ts
494 > const extension = this.extUri.extname(resource);
495 > if (extension === '.json' || extension === '.code-snippets') {
496 > const key = this.extUri.relativePath(this.snippetsFolder, resource)!;
497 > const content = await this.fileService.readFile(resource);
498 > snippets[key] = content;
499 > }
500 > }
501 > return snippets;
502 > } snippetsSync.ts
503 > } snippetsSync.ts
504 >
505 > export class SnippetsInitializer extends AbstractInitializer {
506 >
507 > constructor(
508 @IFileService fileService: IFileService,
509 @IUserDataProfilesService userDataProfilesService: IUserDataProfilesService,
515 super(SyncResource.Snippets, userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
516 }
518 > protected async doInitialize(remoteUserData: IRemoteUserData): Promise<void> {
519 const remoteSnippets: IStringDictionary<string> | null = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null;
520 if (!remoteSnippets) {
540 await this.updateLastSyncUserData(remoteUserData);
541 }
543 > private async isEmpty(): Promise<boolean> {
544 try {
545 const stat = await this.fileService.resolve(this.userDataProfilesService.defaultProfile.snippetsHome);
src/vs/platform/files/common/inMemoryFilesystemProvider.ts 237 covered LOC · 60 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- inMemoryFilesystemProvider.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer } from '../../../base/common/buffer.js';
7 > import { Emitter, Event } from '../../../base/common/event.js';
8 > import { Disposable, IDisposable } from '../../../base/common/lifecycle.js';
9 > import * as resources from '../../../base/common/resources.js';
10 > import { ReadableStreamEvents, newWriteableStream } from '../../../base/common/stream.js';
11 > import { URI } from '../../../base/common/uri.js';
12 > import { FileChangeType, IFileDeleteOptions, IFileOverwriteOptions, FileSystemProviderCapabilities, FileSystemProviderErrorCode, FileType, IFileWriteOptions, IFileChange, IFileSystemProviderWithFileReadWriteCapability, IStat, IWatchOptions, createFileSystemProviderError, IFileSystemProviderWithOpenReadWriteCloseCapability, IFileOpenOptions, IFileSystemProviderWithFileAtomicDeleteCapability, IFileSystemProviderWithFileAtomicReadCapability, IFileSystemProviderWithFileAtomicWriteCapability, IFileSystemProviderWithFileReadStreamCapability, isFileOpenForWriteOptions } from './files.js';
13 >
14 > class File implements IStat {
15 >
16 > readonly type: FileType.File;
17 > readonly ctime: number;
18 > mtime: number;
19 > size: number;
20 >
21 > name: string;
22 > data?: Uint8Array;
23 >
24 > constructor(name: string) {
25 > this.type = FileType.File; inMemoryFilesystemProvider.ts
26 > this.ctime = Date.now();
27 > this.mtime = Date.now();
28 > this.size = 0;
29 > this.name = name;
30 > }
32 >
33 > class Directory implements IStat {
34 >
35 > readonly type: FileType.Directory;
36 > readonly ctime: number;
37 > mtime: number;
38 > size: number;
39 >
40 > name: string;
41 > readonly entries: Map<string, File | Directory>;
42 >
43 > constructor(name: string) {
44 > this.type = FileType.Directory; inMemoryFilesystemProvider.ts
45 > this.ctime = Date.now();
46 > this.mtime = Date.now();
47 > this.size = 0;
48 > this.name = name;
49 > this.entries = new Map();
50 > }
52 >
53 > type Entry = File | Directory;
54 >
55 > export class InMemoryFileSystemProvider extends Disposable implements
56 > IFileSystemProviderWithFileReadWriteCapability,
57 > IFileSystemProviderWithOpenReadWriteCloseCapability,
58 > IFileSystemProviderWithFileReadStreamCapability,
59 > IFileSystemProviderWithFileAtomicReadCapability,
60 > IFileSystemProviderWithFileAtomicWriteCapability,
61 > IFileSystemProviderWithFileAtomicDeleteCapability {
63 > private memoryFdCounter = 0;
64 > private readonly fdMemory = new Map<number, { file: File; resource: URI; append: boolean; write: boolean }>();
65 > private _onDidChangeCapabilities = this._register(new Emitter<void>());
66 > readonly onDidChangeCapabilities = this._onDidChangeCapabilities.event;
67 >
68 > private _capabilities = FileSystemProviderCapabilities.FileReadWrite | FileSystemProviderCapabilities.FileOpenReadWriteClose | FileSystemProviderCapabilities.FileAppend | FileSystemProviderCapabilities.PathCaseSensitive;
69 > get capabilities(): FileSystemProviderCapabilities { return this._capabilities; }
70 >
71 > setReadOnly(readonly: boolean) {
72 const isReadonly = !!(this._capabilities & FileSystemProviderCapabilities.Readonly);
73 if (readonly !== isReadonly) {
76 }
77 }
79 > root = new Directory('');
80 >
81 > // --- manage file metadata
82 >
83 > async stat(resource: URI): Promise<IStat> {
84 > return this._lookup(resource, false); inMemoryFilesystemProvider.ts
85 > }
87 > async readdir(resource: URI): Promise<[string, FileType][]> {
88 > const entry = this._lookupAsDirectory(resource, false); inMemoryFilesystemProvider.ts
89 > const result: [string, FileType][] = [];
90 > entry.entries.forEach((child, name) => result.push([name, child.type]));
91 > return result;
92 > }
94 > // --- manage file contents
95 >
96 > async readFile(resource: URI): Promise<Uint8Array> {
97 > const data = this._lookupAsFile(resource, false).data; inMemoryFilesystemProvider.ts
98 > if (data) {
99 > return data; inMemoryFilesystemProvider.ts
100 > }
101 throw createFileSystemProviderError('file not found', FileSystemProviderErrorCode.FileNotFound);
104 > readFileStream(resource: URI): ReadableStreamEvents<Uint8Array> {
105 const data = this._lookupAsFile(resource, false).data;
106
110 return stream;
111 }
113 > async writeFile(resource: URI, content: Uint8Array, opts: IFileWriteOptions): Promise<void> {
114 > const basename = resources.basename(resource); inMemoryFilesystemProvider.ts
115 > const parent = this._lookupParentDirectory(resource);
116 > let entry = parent.entries.get(basename);
117 > if (entry instanceof Directory) {
118 throw createFileSystemProviderError('file is directory', FileSystemProviderErrorCode.FileIsADirectory);
119 }
120 > if (!entry && !opts.create) { inMemoryFilesystemProvider.ts
121 throw createFileSystemProviderError('file not found', FileSystemProviderErrorCode.FileNotFound);
122 }
123 > if (entry && opts.create && !opts.overwrite) { inMemoryFilesystemProvider.ts
124 throw createFileSystemProviderError('file exists already', FileSystemProviderErrorCode.FileExists);
125 }
126 > if (!entry) { inMemoryFilesystemProvider.ts
127 > entry = new File(basename);
128 > parent.entries.set(basename, entry);
129 > this._fireSoon({ type: FileChangeType.ADDED, resource });
130 > }
131 > entry.mtime = Date.now();
132 >
133 > if (opts.append) {
134 entry.size += content.byteLength;
135 const oldData = entry.data ?? new Uint8Array(0);
138 newData.set(content, oldData.byteLength);
139 entry.data = newData;
141 > entry.size = content.byteLength; inMemoryFilesystemProvider.ts
142 > entry.data = content;
143 > }
145 > this._fireSoon({ type: FileChangeType.UPDATED, resource });
146 > }
148 > // file open/read/write/close
149 > open(resource: URI, opts: IFileOpenOptions): Promise<number> {
150 let file = this._lookup(resource, true);
151 const write = isFileOpenForWriteOptions(opts);
175 return Promise.resolve(fd);
176 }
178 > close(fd: number): Promise<void> {
179 const fdData = this.fdMemory.get(fd);
180 if (fdData?.write) {
187 return Promise.resolve();
188 }
190 > read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
191 const fdData = this.fdMemory.get(fd);
192 if (!fdData) {
202 return Promise.resolve(toWrite.byteLength);
203 }
205 > write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> {
206 const fdData = this.fdMemory.get(fd);
207 if (!fdData) {
226 return Promise.resolve(toWrite.byteLength);
227 }
229 > // --- manage files/folders
230 >
231 > async rename(from: URI, to: URI, opts: IFileOverwriteOptions): Promise<void> {
232 if (!opts.overwrite && this._lookup(to, true)) {
233 throw createFileSystemProviderError('file exists already', FileSystemProviderErrorCode.FileExists);
249 );
250 }
252 > async delete(resource: URI, opts: IFileDeleteOptions): Promise<void> {
253 > const dirname = resources.dirname(resource); inMemoryFilesystemProvider.ts
254 > const basename = resources.basename(resource);
255 > const parent = this._lookupAsDirectory(dirname, false);
256 > if (parent.entries.delete(basename)) {
257 > parent.mtime = Date.now();
258 > parent.size -= 1;
259 > this._fireSoon({ type: FileChangeType.UPDATED, resource: dirname }, { resource, type: FileChangeType.DELETED });
260 > }
261 > }
263 > async mkdir(resource: URI): Promise<void> {
264 > if (this._lookup(resource, true)) { inMemoryFilesystemProvider.ts
265 throw createFileSystemProviderError('file exists already', FileSystemProviderErrorCode.FileExists);
266 }
268 > const basename = resources.basename(resource);
269 > const dirname = resources.dirname(resource);
270 > const parent = this._lookupAsDirectory(dirname, false);
271 >
272 > const entry = new Directory(basename);
273 > parent.entries.set(entry.name, entry);
274 > parent.mtime = Date.now();
275 > parent.size += 1;
276 > this._fireSoon({ type: FileChangeType.UPDATED, resource: dirname }, { type: FileChangeType.ADDED, resource });
277 > }
279 > // --- lookup
280 >
281 > private _lookup(uri: URI, silent: false): Entry;
282 > private _lookup(uri: URI, silent: boolean): Entry | undefined;
283 > private _lookup(uri: URI, silent: boolean): Entry | undefined {
284 > const parts = uri.path.split('/'); inMemoryFilesystemProvider.ts
285 > let entry: Entry = this.root;
286 > for (const part of parts) {
287 > if (!part) {
288 > continue;
289 > }
290 > let child: Entry | undefined;
291 > if (entry instanceof Directory) {
292 > child = entry.entries.get(part);
293 > }
294 > if (!child) {
295 > if (!silent) {
296 > throw createFileSystemProviderError('file not found', FileSystemProviderErrorCode.FileNotFound);
297 > } else {
298 > return undefined; inMemoryFilesystemProvider.ts
299 > }
301 > entry = child; inMemoryFilesystemProvider.ts
302 > }
303 > return entry;
306 > private _lookupAsDirectory(uri: URI, silent: boolean): Directory {
307 > const entry = this._lookup(uri, silent); inMemoryFilesystemProvider.ts
308 > if (entry instanceof Directory) {
309 > return entry;
310 > }
311 throw createFileSystemProviderError('file not a directory', FileSystemProviderErrorCode.FileNotADirectory);
314 > private _lookupAsFile(uri: URI, silent: boolean): File {
315 > const entry = this._lookup(uri, silent); inMemoryFilesystemProvider.ts
316 > if (entry instanceof File) {
317 > return entry; inMemoryFilesystemProvider.ts
318 > }
319 throw createFileSystemProviderError('file is a directory', FileSystemProviderErrorCode.FileIsADirectory);
322 > private _lookupParentDirectory(uri: URI): Directory {
323 > const dirname = resources.dirname(uri); inMemoryFilesystemProvider.ts
324 > return this._lookupAsDirectory(dirname, false);
325 > }
327 > // --- manage file events
328 >
329 > private readonly _onDidChangeFile = this._register(new Emitter<readonly IFileChange[]>());
330 > readonly onDidChangeFile: Event<readonly IFileChange[]> = this._onDidChangeFile.event;
331 >
332 > private _bufferedChanges: IFileChange[] = [];
333 > private _fireSoonHandle?: Timeout; inMemoryFilesystemProvider.ts
334 >
335 > watch(resource: URI, opts: IWatchOptions): IDisposable {
336 > // ignore, fires for all changes... inMemoryFilesystemProvider.ts
337 > return Disposable.None;
338 > }
340 > private _fireSoon(...changes: IFileChange[]): void {
341 > this._bufferedChanges.push(...changes); inMemoryFilesystemProvider.ts
342 >
343 > if (this._fireSoonHandle) {
344 > clearTimeout(this._fireSoonHandle); inMemoryFilesystemProvider.ts
345 > }
347 > this._fireSoonHandle = setTimeout(() => {
348 > this._onDidChangeFile.fire(this._bufferedChanges); inMemoryFilesystemProvider.ts
349 > this._bufferedChanges.length = 0;
351 > }
353 > override dispose(): void {
354 > super.dispose(); inMemoryFilesystemProvider.ts
355 >
356 > this.fdMemory.clear();
357 > }
src/vs/platform/userDataSync/common/keybindingsSync.ts 227 covered LOC · 45 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- keybindingsSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { isNonEmptyArray } from '../../../base/common/arrays.js';
7 > import { VSBuffer } from '../../../base/common/buffer.js';
8 > import { CancellationToken } from '../../../base/common/cancellation.js';
9 > import { Event } from '../../../base/common/event.js';
10 > import { parse } from '../../../base/common/json.js';
11 > import { OperatingSystem, OS } from '../../../base/common/platform.js';
12 > import { isUndefined } from '../../../base/common/types.js';
13 > import { URI } from '../../../base/common/uri.js';
14 > import { localize } from '../../../nls.js';
15 > import { IConfigurationService } from '../../configuration/common/configuration.js';
16 > import { IEnvironmentService } from '../../environment/common/environment.js';
17 > import { FileOperationError, FileOperationResult, IFileService } from '../../files/common/files.js';
18 > import { ILogService } from '../../log/common/log.js';
19 > import { IStorageService } from '../../storage/common/storage.js';
20 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
21 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
22 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
23 > import { AbstractInitializer, AbstractJsonFileSynchroniser, IAcceptResult, IFileResourcePreview, IMergeResult } from './abstractSynchronizer.js';
24 > import { merge } from './keybindingsMerge.js';
25 > import { Change, IRemoteUserData, IUserDataSyncLocalStoreService, IUserDataSyncConfiguration, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, IUserDataSyncUtilService, SyncResource, UserDataSyncError, UserDataSyncErrorCode, USER_DATA_SYNC_SCHEME, CONFIG_SYNC_KEYBINDINGS_PER_PLATFORM } from './userDataSync.js';
26 >
27 > interface ISyncContent {
28 > mac?: string;
29 > linux?: string;
30 > windows?: string;
31 > all?: string;
32 > }
33 >
34 > interface IKeybindingsResourcePreview extends IFileResourcePreview {
35 > previewResult: IMergeResult;
36 > }
37 >
38 > interface ILastSyncUserData extends IRemoteUserData {
39 > platformSpecific?: boolean;
40 > }
41 >
42 > export function getKeybindingsContentFromSyncContent(syncContent: string, platformSpecific: boolean, logService: ILogService): string | null {
43 try {
44 const parsed = <ISyncContent>JSON.parse(syncContent);
59 }
60 }
62 > export class KeybindingsSynchroniser extends AbstractJsonFileSynchroniser implements IUserDataSynchroniser {
63 >
64 > /* Version 2: Change settings from `sync.${setting}` to `settingsSync.{setting}` */
65 > protected readonly version: number = 2;
66 > private readonly previewResource: URI = this.extUri.joinPath(this.syncPreviewFolder, 'keybindings.json');
67 > private readonly baseResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' });
68 > private readonly localResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' });
69 > private readonly remoteResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' });
70 > private readonly acceptedResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' });
71 >
72 > constructor(
73 > profile: IUserDataProfile, keybindingsSync.ts
74 > collection: string | undefined,
75 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
76 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
77 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
78 > @IConfigurationService configurationService: IConfigurationService,
79 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
80 > @IFileService fileService: IFileService,
81 > @IEnvironmentService environmentService: IEnvironmentService,
82 > @IStorageService storageService: IStorageService,
83 > @IUserDataSyncUtilService userDataSyncUtilService: IUserDataSyncUtilService,
84 > @ITelemetryService telemetryService: ITelemetryService,
85 > @IUriIdentityService uriIdentityService: IUriIdentityService,
86 > ) {
87 > super(profile.keybindingsResource, { syncResource: SyncResource.Keybindings, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, userDataSyncUtilService, configurationService, uriIdentityService);
88 > this._register(Event.filter(configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('settingsSync.keybindingsPerPlatform'))(() => this.triggerLocalChange()));
89 > }
91 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: ILastSyncUserData | null, isRemoteDataFromCurrentMachine: boolean, userDataSyncConfiguration: IUserDataSyncConfiguration): Promise<IKeybindingsResourcePreview[]> {
92 > const remoteContent = remoteUserData.syncData ? getKeybindingsContentFromSyncContent(remoteUserData.syncData.content, userDataSyncConfiguration.keybindingsPerPlatform ?? this.syncKeybindingsPerPlatform(), this.logService) : null; keybindingsSync.ts
93 >
94 > // Use remote data as last sync data if last sync data does not exist and remote data is from same machine
95 > lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
96 > const lastSyncContent: string | null = lastSyncUserData ? this.getKeybindingsContentFromLastSyncUserData(lastSyncUserData) : null;
97 >
98 > // Get file content last to get the latest
99 > const fileContent = await this.getLocalFileContent();
100 > const formattingOptions = await this.getFormattingOptions();
101 >
102 > let mergedContent: string | null = null;
103 > let hasLocalChanged: boolean = false;
104 > let hasRemoteChanged: boolean = false;
105 > let hasConflicts: boolean = false;
106 >
107 > if (remoteContent) {
108 let localContent: string = fileContent ? fileContent.value.toString() : '[]';
109 localContent = localContent || '[]';
127 }
128 }
130 > // First time syncing to remote
131 > else if (fileContent) {
132 > this.logService.trace(`${this.syncResourceLogLabel}: Remote keybindings does not exist. Synchronizing keybindings for the first time.`); keybindingsSync.ts
133 > mergedContent = fileContent.value.toString();
134 > hasRemoteChanged = true;
135 > }
137 > const previewResult: IMergeResult = {
138 > content: hasConflicts ? lastSyncContent : mergedContent,
139 > localChange: hasLocalChanged ? fileContent ? Change.Modified : Change.Added : Change.None,
140 > remoteChange: hasRemoteChanged ? Change.Modified : Change.None,
141 > hasConflicts
142 > };
143 >
144 > const localContent = fileContent ? fileContent.value.toString() : null;
145 > return [{
146 > fileContent,
147 >
148 > baseResource: this.baseResource,
149 > baseContent: lastSyncContent,
150 >
151 > localResource: this.localResource,
152 > localContent,
153 > localChange: previewResult.localChange,
154 >
155 > remoteResource: this.remoteResource,
156 > remoteContent,
157 > remoteChange: previewResult.remoteChange,
158 >
159 > previewResource: this.previewResource,
160 > previewResult,
161 > acceptedResource: this.acceptedResource,
162 > }];
163 >
164 > }
166 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
167 const lastSyncContent = this.getKeybindingsContentFromLastSyncUserData(lastSyncUserData);
168 if (lastSyncContent === null) {
176 return result.hasConflicts || result.mergeContent !== lastSyncContent;
177 }
179 > protected async getMergeResult(resourcePreview: IKeybindingsResourcePreview, token: CancellationToken): Promise<IMergeResult> {
180 > return resourcePreview.previewResult; keybindingsSync.ts
181 > }
183 > protected async getAcceptResult(resourcePreview: IKeybindingsResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
185 > /* Accept local resource */
186 > if (this.extUri.isEqual(resource, this.localResource)) {
187 return {
188 content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
191 };
192 }
194 > /* Accept remote resource */
195 > if (this.extUri.isEqual(resource, this.remoteResource)) {
196 return {
197 content: resourcePreview.remoteContent,
200 };
201 }
203 > /* Accept preview resource */
204 > if (this.extUri.isEqual(resource, this.previewResource)) {
205 > if (content === undefined) {
206 > return {
207 > content: resourcePreview.previewResult.content,
208 > localChange: resourcePreview.previewResult.localChange,
209 > remoteChange: resourcePreview.previewResult.remoteChange,
210 > };
211 > } else {
212 return {
213 content,
216 };
217 }
219
220 throw new Error(`Invalid Resource: ${resource.toString()}`);
223 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [IKeybindingsResourcePreview, IAcceptResult][], force: boolean): Promise<void> {
224 > const { fileContent } = resourcePreviews[0][0]; keybindingsSync.ts
225 > let { content, localChange, remoteChange } = resourcePreviews[0][1];
226 >
227 > if (localChange === Change.None && remoteChange === Change.None) {
228 this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing keybindings.`);
229 }
231 > if (content !== null) {
232 > content = content.trim(); keybindingsSync.ts
233 > content = content || '[]';
234 > if (this.hasErrors(content, true)) {
235 throw new UserDataSyncError(localize('errorInvalidSettings', "Unable to sync keybindings because the content in the file is not valid. Please open the file and correct it."), UserDataSyncErrorCode.LocalInvalidContent, this.resource);
236 }
239 > if (localChange !== Change.None) {
240 this.logService.trace(`${this.syncResourceLogLabel}: Updating local keybindings...`);
241 if (fileContent) {
245 this.logService.info(`${this.syncResourceLogLabel}: Updated local keybindings`);
246 }
248 > if (remoteChange !== Change.None) {
249 > this.logService.trace(`${this.syncResourceLogLabel}: Updating remote keybindings...`); keybindingsSync.ts
250 > const remoteContents = this.toSyncContent(content || '[]', remoteUserData.syncData?.content);
251 > remoteUserData = await this.updateRemoteUserData(remoteContents, force ? null : remoteUserData.ref);
252 > this.logService.info(`${this.syncResourceLogLabel}: Updated remote keybindings`);
253 > }
255 > // Delete the preview
256 > try {
257 > await this.fileService.del(this.previewResource);
258 > } catch (e) { /* ignore */ }
259 >
260 > if (lastSyncUserData?.ref !== remoteUserData.ref) { keybindingsSync.ts
261 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized keybindings...`); keybindingsSync.ts
262 > await this.updateLastSyncUserData(remoteUserData, { platformSpecific: this.syncKeybindingsPerPlatform() });
263 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized keybindings`);
264 > }
266 > }
268 > async hasLocalData(): Promise<boolean> {
269 try {
270 const localFileContent = await this.getLocalFileContent();
282 return false;
283 }
285 > async resolveContent(uri: URI): Promise<string | null> {
286 if (this.extUri.isEqual(this.remoteResource, uri)
287 || this.extUri.isEqual(this.baseResource, uri)
293 return null;
294 }
296 > private getKeybindingsContentFromLastSyncUserData(lastSyncUserData: ILastSyncUserData): string | null {
297 if (!lastSyncUserData.syncData) {
298 return null;
306 return getKeybindingsContentFromSyncContent(lastSyncUserData.syncData.content, this.syncKeybindingsPerPlatform(), this.logService);
307 }
309 > private toSyncContent(keybindingsContent: string, syncContent?: string): string {
310 > let parsed: ISyncContent = {}; keybindingsSync.ts
311 > try {
312 > parsed = JSON.parse(syncContent || '{}');
313 > } catch (e) {
314 this.logService.error(e);
315 }
316 > if (this.syncKeybindingsPerPlatform()) { keybindingsSync.ts
317 > delete parsed.all;
318 > } else {
319 parsed.all = keybindingsContent;
320 }
321 > switch (OS) { keybindingsSync.ts
322 > case OperatingSystem.Macintosh:
323 parsed.mac = keybindingsContent;
324 break;
325 > case OperatingSystem.Linux: keybindingsSync.ts
326 > parsed.linux = keybindingsContent;
327 > break;
328 > case OperatingSystem.Windows:
329 parsed.windows = keybindingsContent;
330 break;
332 > return JSON.stringify(parsed);
333 > }
335 > private syncKeybindingsPerPlatform(): boolean {
336 > return !!this.configurationService.getValue(CONFIG_SYNC_KEYBINDINGS_PER_PLATFORM); keybindingsSync.ts
337 > }
339 > }
340 >
341 > export class KeybindingsInitializer extends AbstractInitializer {
342 >
343 > constructor(
344 @IFileService fileService: IFileService,
345 @IUserDataProfilesService userDataProfilesService: IUserDataProfilesService,
351 super(SyncResource.Keybindings, userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
352 }
354 > protected async doInitialize(remoteUserData: IRemoteUserData): Promise<void> {
355 const keybindingsContent = remoteUserData.syncData ? this.getKeybindingsContentFromSyncContent(remoteUserData.syncData.content) : null;
356 if (!keybindingsContent) {
369 await this.updateLastSyncUserData(remoteUserData);
370 }
372 > private async isEmpty(): Promise<boolean> {
373 try {
374 const fileContent = await this.fileService.readFile(this.userDataProfilesService.defaultProfile.settingsResource);
379 }
380 }
382 > private getKeybindingsContentFromSyncContent(syncContent: string): string | null {
383 try {
384 return getKeybindingsContentFromSyncContent(syncContent, true, this.logService);
src/vs/nls.ts 224 covered LOC · 19 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- nls.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export function getNLSMessages(): string[] {
7 return globalThis._VSCODE_NLS_MESSAGES;
8 }
9 > nls.ts
10 > export function getNLSLanguage(): string | undefined {
11 > return globalThis._VSCODE_NLS_LANGUAGE;
12 > }
13 >
14 > declare const document: { location?: { hash?: string } } | undefined;
15 > const isPseudo = getNLSLanguage() === 'pseudo' || (typeof document !== 'undefined' && document.location && typeof document.location.hash === 'string' && document.location.hash.indexOf('pseudo=true') >= 0);
16 >
17 > export interface ILocalizeInfo {
18 > key: string;
19 > comment: string[];
20 > }
21 >
22 > export interface ILocalizedString {
23 > original: string;
24 > value: string;
25 > }
26 >
27 > function _format(message: string, args: (string | number | boolean | undefined | null)[]): string { nls.ts
28 > let result: string;
29 >
30 > if (args.length === 0) {
31 > result = message; nls.ts
32 > } else { nls.ts
33 > result = message.replace(/\{(\d+)\}/g, (match, rest) => { nls.ts
34 > const index = rest[0];
35 > const arg = args[index];
36 > let result = match;
37 > if (typeof arg === 'string') {
38 > result = arg; nls.ts
39 > } else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) { nls.ts
40 result = String(arg);
41 }
42 > return result; nls.ts
43 > });
44 > }
45 > nls.ts
46 > if (isPseudo) {
47 // FF3B and FF3D is the Unicode zenkaku representation for [ and ]
48 result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D';
49 }
50 > nls.ts
51 > return result;
52 > }
53 > nls.ts
54 > /**
55 > * Marks a string to be localized. Returns the localized string.
56 > *
57 > * @param info The {@linkcode ILocalizeInfo} which describes the id and comments associated with the localized string.
58 > * @param message The string to localize
59 > * @param args The arguments to the string
60 > *
61 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
62 > * @example `localize({ key: 'sayHello', comment: ['Welcomes user'] }, 'hello {0}', name)`
63 > *
64 > * @returns string The localized string.
65 > */
66 > export function localize(info: ILocalizeInfo, message: string, ...args: (string | number | boolean | undefined | null)[]): string;
67 >
68 > /**
69 > * Marks a string to be localized. Returns the localized string.
70 > *
71 > * @param key The key to use for localizing the string
72 > * @param message The string to localize
73 > * @param args The arguments to the string
74 > *
75 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
76 > * @example For example, `localize('sayHello', 'hello {0}', name)`
77 > *
78 > * @returns string The localized string.
79 > */
80 > export function localize(key: string, message: string, ...args: (string | number | boolean | undefined | null)[]): string;
81 >
82 > /**
83 > * @skipMangle
84 > */
85 > export function localize(data: ILocalizeInfo | string /* | number when built */, message: string /* | null when built */, ...args: (string | number | boolean | undefined | null)[]): string {
86 > if (typeof data === 'number') { nls.ts
87 return _format(lookupMessage(data, message), args);
88 }
89 > return _format(message, args); nls.ts
90 > }
91 > nls.ts
92 > /**
93 > * Only used when built: Looks up the message in the global NLS table.
94 > * This table is being made available as a global through bootstrapping
95 > * depending on the target context.
96 > */
97 function lookupMessage(index: number, fallback: string | null): string {
98 const message = getNLSMessages()?.[index];
105 return message;
106 }
107 > nls.ts
108 > /**
109 > * Marks a string to be localized. Returns an {@linkcode ILocalizedString}
110 > * which contains the localized string and the original string.
111 > *
112 > * @param info The {@linkcode ILocalizeInfo} which describes the id and comments associated with the localized string.
113 > * @param message The string to localize
114 > * @param args The arguments to the string
115 > *
116 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
117 > * @example `localize2({ key: 'sayHello', comment: ['Welcomes user'] }, 'hello {0}', name)`
118 > *
119 > * @returns ILocalizedString which contains the localized string and the original string.
120 > */
121 > export function localize2(info: ILocalizeInfo, message: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString;
122 >
123 > /**
124 > * Marks a string to be localized. Returns an {@linkcode ILocalizedString}
125 > * which contains the localized string and the original string.
126 > *
127 > * @param key The key to use for localizing the string
128 > * @param message The string to localize
129 > * @param args The arguments to the string
130 > *
131 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
132 > * @example `localize('sayHello', 'hello {0}', name)`
133 > *
134 > * @returns ILocalizedString which contains the localized string and the original string.
135 > */
136 > export function localize2(key: string, message: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString;
137 >
138 > /**
139 > * @skipMangle
140 > */
141 > export function localize2(data: ILocalizeInfo | string /* | number when built */, originalMessage: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString {
142 > let message: string; nls.ts
143 > if (typeof data === 'number') {
144 message = lookupMessage(data, originalMessage);
145 > } else { nls.ts
146 > message = originalMessage;
147 > }
148 >
149 > const value = _format(message, args);
150 >
151 > return {
152 > value,
153 > original: originalMessage === message ? value : _format(originalMessage, args)
154 > };
155 > }
156 > nls.ts
157 > export interface INLSLanguagePackConfiguration {
158 >
159 > /**
160 > * The path to the translations config file that contains pointers to
161 > * all message bundles for `main` and extensions.
162 > */
163 > readonly translationsConfigFile: string;
164 >
165 > /**
166 > * The path to the file containing the translations for this language
167 > * pack as flat string array.
168 > */
169 > readonly messagesFile: string;
170 >
171 > /**
172 > * The path to the file that can be used to signal a corrupt language
173 > * pack, for example when reading the `messagesFile` fails. This will
174 > * instruct the application to re-create the cache on next startup.
175 > */
176 > readonly corruptMarkerFile: string;
177 > }
178 >
179 > export interface INLSConfiguration {
180 >
181 > /**
182 > * Locale as defined in `argv.json` or `app.getLocale()`.
183 > */
184 > readonly userLocale: string;
185 >
186 > /**
187 > * Locale as defined by the OS (e.g. `app.getPreferredSystemLanguages()`).
188 > */
189 > readonly osLocale: string;
190 >
191 > /**
192 > * The actual language of the UI that ends up being used considering `userLocale`
193 > * and `osLocale`.
194 > */
195 > readonly resolvedLanguage: string;
196 >
197 > /**
198 > * Defined if a language pack is used that is not the
199 > * default english language pack. This requires a language
200 > * pack to be installed as extension.
201 > */
202 > readonly languagePack?: INLSLanguagePackConfiguration;
203 >
204 > /**
205 > * The path to the file containing the default english messages
206 > * as flat string array. The file is only present in built
207 > * versions of the application.
208 > */
209 > readonly defaultMessagesFile: string;
210 >
211 > /**
212 > * Below properties are deprecated and only there to continue support
213 > * for `vscode-nls` module that depends on them.
214 > * Refs https://github.com/microsoft/vscode-nls/blob/main/src/node/main.ts#L36-L46
215 > */
216 > /** @deprecated */
217 > readonly locale: string;
218 > /** @deprecated */
219 > readonly availableLanguages: Record<string, string>;
220 > /** @deprecated */
221 > readonly _languagePackSupport?: boolean;
222 > /** @deprecated */
223 > readonly _languagePackId?: string;
224 > /** @deprecated */
225 > readonly _translationsConfigFile?: string;
226 > /** @deprecated */
227 > readonly _cacheRoot?: string;
228 > /** @deprecated */
229 > readonly _resolvedLanguagePackCoreLocation?: string;
230 > /** @deprecated */
231 > readonly _corruptedFile?: string;
232 > }
233 >
234 > export interface ILanguagePack {
235 > readonly hash: string;
236 > readonly label: string | undefined;
237 > readonly extensions: {
238 > readonly extensionIdentifier: { readonly id: string; readonly uuid?: string };
239 > readonly version: string;
240 > }[];
241 > readonly translations: Record<string, string | undefined>;
242 > }
243 >
244 > export type ILanguagePacks = Record<string, ILanguagePack | undefined>;
src/vs/base/test/common/virtualScheduling/processor.ts 215 covered LOC · 19 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- processor.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken } from '../../../common/cancellation.js';
7 > import { Disposable, DisposableStore, IDisposable } from '../../../common/lifecycle.js';
8 > import { Embedding, nextMacrotask } from './embedding.js';
9 > import { TimeApi } from './timeApi.js';
10 > import { ROOT_TRACE, TraceContext } from './trace.js';
11 > import { EventSource, VirtualClock, VirtualEvent, VirtualTime } from './virtualClock.js';
12 >
13 > // ============================================================================
14 > // Termination policy
15 > // ============================================================================
16 >
17 > /**
18 > * When a {@link Run} should terminate.
19 > *
20 > * Greenfield design choice: termination is *always* explicit. There is no
21 > * "bare run()" that terminates on first empty queue, because that creates a
22 > * race with the caller's microtask chain (the run can resolve before the
23 > * caller's `.then` has had a chance to schedule).
24 > */
25 > export type TerminationPolicy =
26 > /** Resolve as soon as the virtual queue is empty. */
27 > | { readonly kind: 'idle' }
28 > /** Resolve when the token is cancelled AND the queue is empty. */
29 > | { readonly kind: 'token'; readonly token: CancellationToken }
30 > /** Resolve when virtual time has reached `time` and all events scheduled
31 > * at or before `time` have been processed. A sentinel event at `time`
32 > * is scheduled by the processor so virtual time always reaches it. */
33 > | { readonly kind: 'time'; readonly time: VirtualTime };
34 >
35 > export const untilIdle: TerminationPolicy = { kind: 'idle' };
36 > export function untilToken(token: CancellationToken): TerminationPolicy { return { kind: 'token', token }; }
37 > export function untilTime(time: VirtualTime): TerminationPolicy { return { kind: 'time', time }; }
38 >
39 > export interface RunOptions {
40 > readonly until: TerminationPolicy;
41 > /** Maximum number of virtual events this run will execute. Default: 100. */
42 > readonly maxEvents?: number;
43 > /** Maximum causal-trace depth this run will tolerate. Useful for catching
44 > * runaway self-rescheduling timers. */
45 > readonly maxTraceDepth?: number;
46 > }
47 >
48 > // ============================================================================
49 > // Run — internal state for a single processor.run() invocation
50 > // ============================================================================
51 >
52 > type RunStatus = 'continue' | 'done' | { readonly error: Error };
53 >
54 > class Run {
55 > private static _idCounter = 0;
56 > public readonly id = ++Run._idCounter;
57 >
58 > public readonly promise: Promise<void>;
59 > private _resolve!: () => void;
60 > private _reject!: (e: Error) => void;
61 > private _settled = false;
62 > public get settled(): boolean { return this._settled; }
63 >
64 > constructor(
65 public readonly options: RunOptions,
66 public readonly executedAtStart: number,
69 this.promise = new Promise<void>((res, rej) => { this._resolve = res; this._reject = rej; });
70 }
72 > settle(error?: Error): void {
73 if (this._settled) { return; }
74 this._settled = true;
75 if (error) { this._reject(error); } else { this._resolve(); }
76 }
78 > evaluate(clock: VirtualClock, executedTotal: number, makeOverflow: () => Error): RunStatus {
79 const local = executedTotal - this.executedAtStart;
80 if (local >= this.maxEvents && clock.hasEvents) {
98 }
99 }
100 > } processor.ts
101 >
102 > // ============================================================================
103 > // Step outcome — what the pure state machine tells the trampoline
104 > // ============================================================================
105 >
106 > type StepOutcome =
107 > /** Either a virtual event was executed, or a run was rejected for a
108 > * bookkeeping reason (depth/event overflow). The trampoline should let
109 > * the embedding decide how to reach the next step. */
110 > | 'progress'
111 > /** No actionable event under any active deadline. The trampoline should
112 > * park until something wakes the processor. */
113 > | 'park'
114 > /** No active runs. The trampoline should stop driving. */
115 > | 'quiesce';
116 >
117 > // ============================================================================
118 > // VirtualTimeProcessor
119 > // ============================================================================
120 >
121 > export interface VirtualTimeProcessorOptions {
122 > readonly defaultMaxEvents?: number;
123 > }
124 >
125 > /**
126 > * # VirtualTimeProcessor
127 > *
128 > * Drives a {@link VirtualClock} from the host event loop. This is the
129 > * **embedding** of a small virtual event loop into the host event loop.
130 > *
131 > * ## Responsibilities, separated
132 > *
133 > * - {@link _step} is a *pure* state-machine advance. It reads the clock,
134 > * decides what to do, optionally executes one virtual event, and returns
135 > * a {@link StepOutcome}. It never touches host time.
136 > *
137 > * - {@link _drive} is the *trampoline*. It calls `_step` and lets the
138 > * {@link Embedding} decide whether to loop in place (`'continueSync'`)
139 > * or schedule the next iteration on the host (`'cbScheduled'`). It is
140 > * the only code that touches host time.
141 > *
142 > * - {@link Run} carries the user's termination predicate. Runs are pure
143 > * over `_step`'s observations; they never schedule.
144 > *
145 > * ## Invariants
146 > *
147 > * 1. **Single driver.** At any moment at most one `_drive` invocation is
148 > * active per processor (the `_inDrive` guard).
149 > *
150 > * 2. **Step is pure w.r.t. host time.** `_step` only reads the clock,
151 > * mutates the run set via settling, and synchronously runs at most one
152 > * virtual event. It never calls into a host time API.
153 > *
154 > * 3. **Embedding chooses the host primitive.** Whether the next step runs
155 > * inline, after a microtask drain, or on a paint frame is entirely the
156 > * embedding's decision — *per event*.
157 > *
158 > * 4. **Park is breakable.** While parked, the processor wakes on
159 > * {@link VirtualClock.onEventScheduled}, on a token cancellation, and
160 > * on a new run being added.
161 > *
162 > * 5. **Disposal is terminal.** After dispose, all runs are rejected and
163 > * `_step`/`_drive` short-circuit to `'quiesce'`.
164 > *
165 > * ## On the trace-reset sink
166 > *
167 > * The trace context's deferred reset (see {@link TraceContext.runAsHandler})
168 > * needs a "fire after the microtask closure" primitive. The processor passes
169 > * its *own* {@link nextMacrotask} as that sink, so the reset goes through
170 > * the same primitive the embedding uses for its own host hops. This removes
171 > * any race between the processor's hops and the trace-reset timer.
172 > */
173 > export class VirtualTimeProcessor extends Disposable {
174 >
175 > private readonly _runs = new Map<Run, IDisposable>();
176 > private readonly _history: VirtualEvent[] = [];
177 > private _executedTotal = 0;
178 > private _disposed = false;
179 >
180 > private _inDrive = false;
181 > private _parkCleanup: IDisposable | undefined;
182 >
183 > private readonly _defaultMaxEvents: number;
184 >
185 > public get history(): readonly VirtualEvent[] { return this._history; }
186 > public get executedTotal(): number { return this._executedTotal; }
187 >
188 > constructor(
189 private readonly _clock: VirtualClock,
190 private readonly _embedding: Embedding,
196 this._register({ dispose: () => this._onDispose() });
197 }
198 > processor.ts
199 > // ---- Public API -----------------------------------------------------
200 >
201 > /** Start a run with the given termination policy. */
202 > run(options: RunOptions): Promise<void> {
203 const run = new Run(options, this._executedTotal, options.maxEvents ?? this._defaultMaxEvents);
204 const cleanup = new DisposableStore();
226 return run.promise;
227 }
228 > processor.ts
229 > // ---- The pure step --------------------------------------------------
230 >
231 > private _step(): StepOutcome {
232 if (this._disposed) { return 'quiesce'; }
233
254 return 'progress';
255 }
256 > processor.ts
257 > private _executeOne(event: VirtualEvent): void {
258 try {
259 TraceContext.instance.runAsHandler(
280 }
281 }
282 > processor.ts
283 > // ---- The trampoline -------------------------------------------------
284 >
285 > private readonly _drive = (): void => {
286 > if (this._inDrive) { return; }
287 > this._inDrive = true;
288 > try {
289 > while (true) {
290 > const outcome = this._step();
291 > if (outcome === 'quiesce') { return; }
292 > if (outcome === 'park') { this._park(); return; } processor.ts
293 >
294 > // 'progress': read the next event so the embedding can pick a
295 > // per-event primitive. If there is none, loop and let the next
296 > // `_step` decide between 'park' and 'quiesce'.
297 > const next = this._clock.peekNext();
298 > if (next === undefined) { continue; }
299 > processor.ts
300 > const choice = this._embedding(next, this._drive);
301 > if (choice === 'cbScheduled') { return; }
302 > // 'continueSync': loop in place. processor.ts
303 > }
304 > } finally {
305 > this._inDrive = false;
306 > }
307 > };
308 >
309 > // ---- Park & wake ----------------------------------------------------
310 >
311 > private _park(): void {
312 this._unpark();
313 const store = new DisposableStore();
315 this._parkCleanup = store;
316 }
317 > processor.ts
318 > private _unpark(): void {
319 this._parkCleanup?.dispose();
320 this._parkCleanup = undefined;
321 }
322 > processor.ts
323 > private _wake(): void {
324 if (this._disposed) { return; }
325 this._unpark();
337 nextMacrotask(this._realApi, this._drive);
338 }
339 > processor.ts
340 > // ---- Run lifecycle --------------------------------------------------
341 >
342 > private _settleFinishedRuns(): void {
343 for (const run of [...this._runs.keys()]) {
344 if (run.settled) { continue; }
351 }
352 }
353 > processor.ts
354 > private _settleRun(run: Run, error?: Error): void {
355 const cleanup = this._runs.get(run);
356 if (!cleanup) { return; }
359 run.settle(error);
360 }
361 > processor.ts
362 > private _buildOverflow(run: Run): Error {
363 const local = this._executedTotal - run.executedAtStart;
364 return new Error(
367 );
368 }
369 > processor.ts
370 > private _buildDepthOverflow(run: Run, depth: number): Error {
371 return new Error(
372 `[VirtualTimeProcessor] Run #${run.id} exceeded maxTraceDepth (${run.options.maxTraceDepth}) — ` +
375 );
376 }
377 > processor.ts
378 > private _onDispose(): void {
379 this._disposed = true;
380 this._unpark();
382 for (const run of [...this._runs.keys()]) { this._settleRun(run, err); }
383 }
384 > } processor.ts
src/vs/platform/contextkey/common/scanner.ts 203 covered LOC · 58 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- scanner.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CharCode } from '../../../base/common/charCode.js';
7 > import { illegalState } from '../../../base/common/errors.js';
8 > import { localize } from '../../../nls.js';
9 >
10 > export const enum TokenType {
11 > LParen,
12 > RParen,
13 > Neg,
14 > Eq,
15 > NotEq,
16 > Lt,
17 > LtEq,
18 > Gt,
19 > GtEq,
20 > RegexOp,
21 > RegexStr,
22 > True,
23 > False,
24 > In,
25 > Not,
26 > And,
27 > Or,
28 > Str,
29 > QuotedStr,
30 > Error,
31 > EOF,
32 > }
33 >
34 > export type Token =
35 > | { type: TokenType.LParen; offset: number }
36 > | { type: TokenType.RParen; offset: number }
37 > | { type: TokenType.Neg; offset: number }
38 > | { type: TokenType.Eq; offset: number; isTripleEq: boolean }
39 > | { type: TokenType.NotEq; offset: number; isTripleEq: boolean }
40 > | { type: TokenType.Lt; offset: number }
41 > | { type: TokenType.LtEq; offset: number }
42 > | { type: TokenType.Gt; offset: number }
43 > | { type: TokenType.GtEq; offset: number }
44 > | { type: TokenType.RegexOp; offset: number }
45 > | { type: TokenType.RegexStr; offset: number; lexeme: string }
46 > | { type: TokenType.True; offset: number }
47 > | { type: TokenType.False; offset: number }
48 > | { type: TokenType.In; offset: number }
49 > | { type: TokenType.Not; offset: number }
50 > | { type: TokenType.And; offset: number }
51 > | { type: TokenType.Or; offset: number }
52 > | { type: TokenType.Str; offset: number; lexeme: string }
53 > | { type: TokenType.QuotedStr; offset: number; lexeme: string }
54 > | { type: TokenType.Error; offset: number; lexeme: string }
55 > | { type: TokenType.EOF; offset: number };
56 >
57 > type KeywordTokenType = TokenType.Not | TokenType.In | TokenType.False | TokenType.True;
58 > type TokenTypeWithoutLexeme =
59 > TokenType.LParen |
60 > TokenType.RParen |
61 > TokenType.Neg |
62 > TokenType.Lt |
63 > TokenType.LtEq |
64 > TokenType.Gt |
65 > TokenType.GtEq |
66 > TokenType.RegexOp |
67 > TokenType.True |
68 > TokenType.False |
69 > TokenType.In |
70 > TokenType.Not |
71 > TokenType.And |
72 > TokenType.Or |
73 > TokenType.EOF;
74 >
75 > /**
76 > * Example:
77 > * `foo == bar'` - note how single quote doesn't have a corresponding closing quote,
78 > * so it's reported as unexpected
79 > */
80 > export type LexingError = {
81 > offset: number; /** note that this doesn't take into account escape characters from the original encoding of the string, e.g., within an extension manifest file's JSON encoding */
82 > lexeme: string;
83 > additionalInfo?: string;
84 > };
85 >
86 function hintDidYouMean(...meant: string[]) {
87 switch (meant.length) {
96 }
97 }
98 > scanner.ts
99 > const hintDidYouForgetToOpenOrCloseQuote = localize('contextkey.scanner.hint.didYouForgetToOpenOrCloseQuote', "Did you forget to open or close the quote?");
100 > const hintDidYouForgetToEscapeSlash = localize('contextkey.scanner.hint.didYouForgetToEscapeSlash', "Did you forget to escape the '/' (slash) character? Put two backslashes before it to escape, e.g., '\\\\/\'.");
101 >
102 > /**
103 > * A simple scanner for context keys.
104 > *
105 > * Example:
106 > *
107 > * ```ts
108 > * const scanner = new Scanner().reset('resourceFileName =~ /docker/ && !config.docker.enabled');
109 > * const tokens = [...scanner];
110 > * if (scanner.errorTokens.length > 0) {
111 > * scanner.errorTokens.forEach(err => console.error(`Unexpected token at ${err.offset}: ${err.lexeme}\nHint: ${err.additional}`));
112 > * } else {
113 > * // process tokens
114 > * }
115 > * ```
116 > */
117 > export class Scanner {
118 >
119 > static getLexeme(token: Token): string {
120 > switch (token.type) {
121 > case TokenType.LParen:
122 > return '('; scanner.ts
123 > case TokenType.RParen: scanner.ts
124 > return ')'; scanner.ts
125 > case TokenType.Neg: scanner.ts
126 > return '!'; scanner.ts
127 > case TokenType.Eq: scanner.ts
128 > return token.isTripleEq ? '===' : '=='; scanner.ts
129 > case TokenType.NotEq: scanner.ts
130 > return token.isTripleEq ? '!==' : '!='; scanner.ts
131 > case TokenType.Lt: scanner.ts
132 > return '<'; scanner.ts
133 > case TokenType.LtEq: scanner.ts
134 > return '<='; scanner.ts
135 > case TokenType.Gt: scanner.ts
136 > return '>'; scanner.ts
137 > case TokenType.GtEq: scanner.ts
138 > return '>='; scanner.ts
139 > case TokenType.RegexOp: scanner.ts
140 > return '=~'; scanner.ts
141 > case TokenType.RegexStr: scanner.ts
142 > return token.lexeme; scanner.ts
143 > case TokenType.True: scanner.ts
144 > return 'true'; scanner.ts
145 > case TokenType.False: scanner.ts
146 > return 'false'; scanner.ts
147 > case TokenType.In: scanner.ts
148 > return 'in'; scanner.ts
149 > case TokenType.Not: scanner.ts
150 > return 'not'; scanner.ts
151 > case TokenType.And: scanner.ts
152 > return '&&'; scanner.ts
153 > case TokenType.Or: scanner.ts
154 > return '||'; scanner.ts
155 > case TokenType.Str: scanner.ts
156 > return token.lexeme; scanner.ts
157 > case TokenType.QuotedStr: scanner.ts
158 > return token.lexeme; scanner.ts
159 > case TokenType.Error: scanner.ts
160 > return token.lexeme; scanner.ts
161 > case TokenType.EOF: scanner.ts
162 > return 'EOF'; scanner.ts
163 > default: scanner.ts
164 > throw illegalState(`unhandled token type: ${JSON.stringify(token)}; have you forgotten to add a case?`); scanner.ts
165 > } scanner.ts
166 > }
167 >
168 > private static _regexFlags = new Set(['i', 'g', 's', 'm', 'y', 'u'].map(ch => ch.charCodeAt(0)));
169 >
170 > private static _keywords = new Map<string, KeywordTokenType>([
171 > ['not', TokenType.Not],
172 > ['in', TokenType.In],
173 > ['false', TokenType.False],
174 > ['true', TokenType.True],
175 > ]);
176 >
177 > private _input: string = '';
178 > private _start: number = 0;
179 > private _current: number = 0;
180 > private _tokens: Token[] = [];
181 > private _errors: LexingError[] = [];
182 >
183 > get errors(): Readonly<LexingError[]> {
184 return this._errors;
185 }
186 > scanner.ts
187 > reset(value: string) {
188 this._input = value;
189
195 return this;
196 }
197 > scanner.ts
198 > scan() {
199 while (!this._isAtEnd()) {
200
267 return Array.from(this._tokens);
268 }
269 > scanner.ts
270 > private _match(expected: number): boolean {
271 if (this._isAtEnd()) {
272 return false;
278 return true;
279 }
280 > scanner.ts
281 > private _advance(): number {
282 return this._input.charCodeAt(this._current++);
283 }
284 > scanner.ts
285 > private _peek(): number {
286 return this._isAtEnd() ? CharCode.Null : this._input.charCodeAt(this._current);
287 }
288 > scanner.ts
289 > private _addToken(type: TokenTypeWithoutLexeme) {
290 this._tokens.push({ type, offset: this._start });
291 }
292 > scanner.ts
293 > private _error(additional?: string) {
294 const offset = this._start;
295 const lexeme = this._input.substring(this._start, this._current);
298 this._tokens.push(errToken);
299 }
300 > scanner.ts
301 > // u - unicode, y - sticky // TODO@ulugbekna: we accept double quotes as part of the string rather than as a delimiter (to preserve old parser's behavior)
302 > private stringRe = /[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy;
303 > private _string() {
304 this.stringRe.lastIndex = this._start;
305 const match = this.stringRe.exec(this._input);
315 }
316 }
317 > scanner.ts
318 > // captures the lexeme without the leading and trailing '
319 > private _quotedString() {
320 while (this._peek() !== CharCode.SingleQuote && !this._isAtEnd()) { // TODO@ulugbekna: add support for escaping ' ?
321 this._advance();
332 this._tokens.push({ type: TokenType.QuotedStr, lexeme: this._input.substring(this._start + 1, this._current - 1), offset: this._start + 1 });
333 }
334 > scanner.ts
335 > /*
336 > * Lexing a regex expression: /.../[igsmyu]*
337 > * Based on https://github.com/microsoft/TypeScript/blob/9247ef115e617805983740ba795d7a8164babf89/src/compiler/scanner.ts#L2129-L2181
338 > *
339 > * Note that we want slashes within a regex to be escaped, e.g., /file:\\/\\/\\// should match `file:///`
340 > */
341 > private _regex() {
342 let p = this._current;
343
378 this._tokens.push({ type: TokenType.RegexStr, lexeme, offset: this._start });
379 }
380 > scanner.ts
381 > private _isAtEnd() {
382 return this._current >= this._input.length;
383 }
384 > } scanner.ts
src/vs/base/common/buffer.ts 202 covered LOC · 62 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- buffer.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Lazy } from './lazy.js';
7 > import * as streams from './stream.js';
8 >
9 > interface NodeBuffer {
10 > allocUnsafe(size: number): Uint8Array;
11 > isBuffer(obj: unknown): obj is NodeBuffer;
12 > from(arrayBuffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;
13 > from(data: string): Uint8Array;
14 > }
15 >
16 > declare const Buffer: NodeBuffer;
17 >
18 > const hasBuffer = (typeof Buffer !== 'undefined');
19 > const indexOfTable = new Lazy(() => new Uint8Array(256));
20 >
21 > let textEncoder: { encode: (input: string) => Uint8Array } | null;
22 > let textDecoder: { decode: (input: Uint8Array) => string } | null;
23 >
24 > export class VSBuffer {
25 >
26 > /**
27 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
28 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
29 > */
30 > static alloc(byteLength: number): VSBuffer {
31 > if (hasBuffer) { buffer.ts
32 > return new VSBuffer(Buffer.allocUnsafe(byteLength));
33 > } else {
34 return new VSBuffer(new Uint8Array(byteLength));
35 }
36 > } buffer.ts
37 > buffer.ts
38 > /**
39 > * When running in a nodejs context, if `actual` is not a nodejs Buffer, the backing store for
40 > * the returned `VSBuffer` instance might use a nodejs Buffer allocated from node's Buffer pool,
41 > * which is not transferrable.
42 > */
43 > static wrap(actual: Uint8Array): VSBuffer {
44 > if (hasBuffer && !(Buffer.isBuffer(actual))) { buffer.ts
45 // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
46 // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array
47 actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
48 }
49 > return new VSBuffer(actual); buffer.ts
50 > }
51 > buffer.ts
52 > /**
53 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
54 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
55 > */
56 > static fromString(source: string, options?: { dontUseNodeBuffer?: boolean }): VSBuffer {
57 > const dontUseNodeBuffer = options?.dontUseNodeBuffer || false; buffer.ts
58 > if (!dontUseNodeBuffer && hasBuffer) {
59 > return new VSBuffer(Buffer.from(source));
60 > } else {
61 if (!textEncoder) {
62 textEncoder = new TextEncoder();
64 return new VSBuffer(textEncoder.encode(source));
65 }
66 > } buffer.ts
67 > buffer.ts
68 > /**
69 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
70 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
71 > */
72 > static fromByteArray(source: number[]): VSBuffer {
73 const result = VSBuffer.alloc(source.length);
74 for (let i = 0, len = source.length; i < len; i++) {
77 return result;
78 }
79 > buffer.ts
80 > /**
81 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
82 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
83 > */
84 > static concat(buffers: VSBuffer[], totalLength?: number): VSBuffer {
85 > if (typeof totalLength === 'undefined') { buffer.ts
86 > totalLength = 0; buffer.ts
87 > for (let i = 0, len = buffers.length; i < len; i++) {
88 > totalLength += buffers[i].byteLength; buffer.ts
89 > }
90 > } buffer.ts
91 > buffer.ts
92 > const ret = VSBuffer.alloc(totalLength);
93 > let offset = 0;
94 > for (let i = 0, len = buffers.length; i < len; i++) {
95 > const element = buffers[i]; buffer.ts
96 > ret.set(element, offset);
97 > offset += element.byteLength;
98 > }
99 > buffer.ts
100 > return ret;
101 > }
102 > buffer.ts
103 > static isNativeBuffer(buffer: unknown): boolean {
104 return hasBuffer && Buffer.isBuffer(buffer);
105 }
106 > buffer.ts
107 > readonly buffer: Uint8Array;
108 > readonly byteLength: number;
109 >
110 > private constructor(buffer: Uint8Array) {
111 > this.buffer = buffer; buffer.ts
112 > this.byteLength = this.buffer.byteLength;
113 > }
114 > buffer.ts
115 > /**
116 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
117 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
118 > */
119 > clone(): VSBuffer {
120 const result = VSBuffer.alloc(this.byteLength);
121 result.set(this);
122 return result;
123 }
124 > buffer.ts
125 > toString(): string {
126 > if (hasBuffer) { buffer.ts
127 > return this.buffer.toString();
128 > } else {
129 if (!textDecoder) {
130 textDecoder = new TextDecoder(undefined, { ignoreBOM: true });
132 return textDecoder.decode(this.buffer);
133 }
134 > } buffer.ts
135 > buffer.ts
136 > slice(start?: number, end?: number): VSBuffer {
137 // IMPORTANT: use subarray instead of slice because TypedArray#slice
138 // creates shallow copy and NodeBuffer#slice doesn't. The use of subarray
140 return new VSBuffer(this.buffer.subarray(start, end));
141 }
142 > buffer.ts
143 > set(array: VSBuffer, offset?: number): void;
144 > set(array: Uint8Array, offset?: number): void;
145 > set(array: ArrayBuffer, offset?: number): void;
146 > set(array: ArrayBufferView, offset?: number): void;
147 > set(array: VSBuffer | Uint8Array | ArrayBuffer | ArrayBufferView, offset?: number): void;
148 > set(array: VSBuffer | Uint8Array | ArrayBuffer | ArrayBufferView, offset?: number): void {
149 > if (array instanceof VSBuffer) { buffer.ts
150 > this.buffer.set(array.buffer, offset);
151 > } else if (array instanceof Uint8Array) {
152 this.buffer.set(array, offset);
153 } else if (array instanceof ArrayBuffer) {
158 throw new Error(`Unknown argument 'array'`);
159 }
160 > } buffer.ts
161 > buffer.ts
162 > readUInt32BE(offset: number): number {
163 return readUInt32BE(this.buffer, offset);
164 }
165 > buffer.ts
166 > writeUInt32BE(value: number, offset: number): void {
167 writeUInt32BE(this.buffer, value, offset);
168 }
169 > buffer.ts
170 > readUInt32LE(offset: number): number {
171 return readUInt32LE(this.buffer, offset);
172 }
173 > buffer.ts
174 > writeUInt32LE(value: number, offset: number): void {
175 writeUInt32LE(this.buffer, value, offset);
176 }
177 > buffer.ts
178 > readUInt8(offset: number): number {
179 return readUInt8(this.buffer, offset);
180 }
181 > buffer.ts
182 > writeUInt8(value: number, offset: number): void {
183 writeUInt8(this.buffer, value, offset);
184 }
185 > buffer.ts
186 > indexOf(subarray: VSBuffer | Uint8Array, offset = 0) {
187 return binaryIndexOf(this.buffer, subarray instanceof VSBuffer ? subarray.buffer : subarray, offset);
188 }
189 > buffer.ts
190 > equals(other: VSBuffer): boolean {
191 if (this === other) {
192 return true;
199 return this.buffer.every((value, index) => value === other.buffer[index]);
200 }
201 > } buffer.ts
202 >
203 > /**
204 > * Like String.indexOf, but works on Uint8Arrays.
205 > * Uses the boyer-moore-horspool algorithm to be reasonably speedy.
206 > */
207 > export function binaryIndexOf(haystack: Uint8Array, needle: Uint8Array, offset = 0): number {
208 const needleLen = needle.byteLength;
209 const haystackLen = haystack.byteLength;
248 return result;
249 }
250 > buffer.ts
251 > export function readUInt16LE(source: Uint8Array, offset: number): number {
252 return (
253 ((source[offset + 0] << 0) >>> 0) |
255 );
256 }
257 > buffer.ts
258 > export function writeUInt16LE(destination: Uint8Array, value: number, offset: number): void {
259 destination[offset + 0] = (value & 0b11111111);
260 value = value >>> 8;
261 destination[offset + 1] = (value & 0b11111111);
262 }
263 > buffer.ts
264 > export function readUInt32BE(source: Uint8Array, offset: number): number {
265 return (
266 source[offset] * 2 ** 24
270 );
271 }
272 > buffer.ts
273 > export function writeUInt32BE(destination: Uint8Array, value: number, offset: number): void {
274 destination[offset + 3] = value;
275 value = value >>> 8;
280 destination[offset] = value;
281 }
282 > buffer.ts
283 > export function readUInt32LE(source: Uint8Array, offset: number): number {
284 return (
285 ((source[offset + 0] << 0) >>> 0) |
289 );
290 }
291 > buffer.ts
292 > export function writeUInt32LE(destination: Uint8Array, value: number, offset: number): void {
293 destination[offset + 0] = (value & 0b11111111);
294 value = value >>> 8;
299 destination[offset + 3] = (value & 0b11111111);
300 }
301 > buffer.ts
302 > export function readUInt8(source: Uint8Array, offset: number): number {
303 return source[offset];
304 }
305 > buffer.ts
306 > export function writeUInt8(destination: Uint8Array, value: number, offset: number): void {
307 destination[offset] = value;
308 }
309 > buffer.ts
310 > export interface VSBufferReadable extends streams.Readable<VSBuffer> { }
311 >
312 > export interface VSBufferReadableStream extends streams.ReadableStream<VSBuffer> { }
313 >
314 > export interface VSBufferWriteableStream extends streams.WriteableStream<VSBuffer> { }
315 >
316 > export interface VSBufferReadableBufferedStream extends streams.ReadableBufferedStream<VSBuffer> { }
317 >
318 > export function readableToBuffer(readable: VSBufferReadable): VSBuffer {
319 return streams.consumeReadable<VSBuffer>(readable, chunks => VSBuffer.concat(chunks));
320 }
321 > buffer.ts
322 > export function bufferToReadable(buffer: VSBuffer): VSBufferReadable {
323 return streams.toReadable<VSBuffer>(buffer);
324 }
325 > buffer.ts
326 > export function streamToBuffer(stream: streams.ReadableStream<VSBuffer>): Promise<VSBuffer> {
327 > return streams.consumeStream<VSBuffer>(stream, chunks => VSBuffer.concat(chunks)); buffer.ts
328 > }
329 > buffer.ts
330 export async function bufferedStreamToBuffer(bufferedStream: streams.ReadableBufferedStream<VSBuffer>): Promise<VSBuffer> {
331 if (bufferedStream.ended) {
342 ]);
343 }
344 > buffer.ts
345 > export function bufferToStream(buffer: VSBuffer): streams.ReadableStream<VSBuffer> {
346 > return streams.toStream<VSBuffer>(buffer, chunks => VSBuffer.concat(chunks)); buffer.ts
347 > }
348 > buffer.ts
349 > export function streamToBufferReadableStream(stream: streams.ReadableStreamEvents<Uint8Array | string>): streams.ReadableStream<VSBuffer> {
350 return streams.transform<Uint8Array | string, VSBuffer>(stream, { data: data => typeof data === 'string' ? VSBuffer.fromString(data) : VSBuffer.wrap(data) }, chunks => VSBuffer.concat(chunks));
351 }
352 > buffer.ts
353 > export function newWriteableBufferStream(options?: streams.WriteableStreamOptions): streams.WriteableStream<VSBuffer> {
354 return streams.newWriteableStream<VSBuffer>(chunks => VSBuffer.concat(chunks), options);
355 }
356 > buffer.ts
357 > export function prefixedBufferReadable(prefix: VSBuffer, readable: VSBufferReadable): VSBufferReadable {
358 return streams.prefixedReadable(prefix, readable, chunks => VSBuffer.concat(chunks));
359 }
360 > buffer.ts
361 > export function prefixedBufferStream(prefix: VSBuffer, stream: VSBufferReadableStream): VSBufferReadableStream {
362 return streams.prefixedStream(prefix, stream, chunks => VSBuffer.concat(chunks));
363 }
364 > buffer.ts
365 > /** Decodes base64 to a uint8 array. URL-encoded and unpadded base64 is allowed. */
366 > export function decodeBase64(encoded: string) {
367 let building = 0;
368 let remainder = 0;
424 return VSBuffer.wrap(buffer).slice(0, unpadded);
425 }
426 > buffer.ts
427 > const base64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
428 > const base64UrlSafeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
429 >
430 > /** Encodes a buffer to a base64 string. */
431 > export function encodeBase64({ buffer }: VSBuffer, padded = true, urlSafe = false) {
432 const dictionary = urlSafe ? base64UrlSafeAlphabet : base64Alphabet;
433 let output = '';
463 return output;
464 }
465 > buffer.ts
466 > const hexChars = '0123456789abcdef';
467 > export function encodeHex({ buffer }: VSBuffer): string {
468 let result = '';
469 for (let i = 0; i < buffer.length; i++) {
474 return result;
475 }
476 > buffer.ts
477 > export function decodeHex(hex: string): VSBuffer {
478 if (hex.length % 2 !== 0) {
479 throw new SyntaxError('Hex string must have an even length');
485 return VSBuffer.wrap(out);
486 }
487 > buffer.ts
488 function decodeHexChar(str: string, position: number) {
489 const s = str.charCodeAt(position);
src/vs/platform/telemetry/common/telemetryUtils.ts 199 covered LOC · 15 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- telemetryUtils.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { cloneAndChange, safeStringify } from '../../../base/common/objects.js';
7 > import { isObject } from '../../../base/common/types.js';
8 > import { URI } from '../../../base/common/uri.js';
9 > import { localize } from '../../../nls.js';
10 > import { IConfigurationService } from '../../configuration/common/configuration.js';
11 > import { IEnvironmentService } from '../../environment/common/environment.js';
12 > import { LoggerGroup } from '../../log/common/log.js';
13 > import { IProductService } from '../../product/common/productService.js';
14 > import { getRemoteName } from '../../remote/common/remoteHosts.js';
15 > import { verifyMicrosoftInternalDomain } from './commonProperties.js';
16 > import { ICustomEndpointTelemetryService, ITelemetryData, ITelemetryEndpoint, ITelemetryService, TelemetryConfiguration, TelemetryLevel, TELEMETRY_CRASH_REPORTER_SETTING_ID, TELEMETRY_OLD_SETTING_ID, TELEMETRY_SETTING_ID } from './telemetry.js';
17 >
18 > /**
19 > * A special class used to denoting a telemetry value which should not be clean.
20 > * This is because that value is "Trusted" not to contain identifiable information such as paths.
21 > * NOTE: This is used as an API type as well, and should not be changed.
22 > */
23 > export class TelemetryTrustedValue<T> {
24 > // This is merely used as an identifier as the instance will be lost during serialization over the exthost
25 > public readonly isTrustedTelemetryValue = true;
26 > constructor(public readonly value: T) { }
27 > }
28 >
29 > export class NullTelemetryServiceShape implements ITelemetryService {
30 > declare readonly _serviceBrand: undefined;
31 > readonly telemetryLevel = TelemetryLevel.NONE;
32 > readonly sessionId = 'someValue.sessionId';
33 > readonly machineId = 'someValue.machineId';
34 > readonly sqmId = 'someValue.sqmId';
35 > readonly devDeviceId = 'someValue.devDeviceId';
36 > readonly firstSessionDate = 'someValue.firstSessionDate';
37 > readonly sendErrorTelemetry = false;
38 > publicLog() { }
39 > publicLog2() { }
40 > publicLogError() { }
41 > publicLogError2() { }
42 > setExperimentProperty() { }
43 > setCommonProperty() { }
44 > }
45 >
46 > export const NullTelemetryService = new NullTelemetryServiceShape();
47 >
48 > export class NullEndpointTelemetryService implements ICustomEndpointTelemetryService {
49 > _serviceBrand: undefined;
50 >
51 > async publicLog(_endpoint: ITelemetryEndpoint, _eventName: string, _data?: ITelemetryData): Promise<void> {
52 // noop
53 }
55 > async publicLogError(_endpoint: ITelemetryEndpoint, _errorEventName: string, _data?: ITelemetryData): Promise<void> {
56 // noop
57 }
59 >
60 > export const telemetryLogId = 'telemetry';
61 > export const TelemetryLogGroup: LoggerGroup = { id: telemetryLogId, name: localize('telemetryLogName', "Telemetry") };
62 >
63 > export interface ITelemetryAppender {
64 > log(eventName: string, data: ITelemetryData): void;
65 > flush(): Promise<void>;
66 > }
67 >
68 > export const NullAppender: ITelemetryAppender = { log: () => null, flush: () => Promise.resolve(undefined) };
69 >
70 >
71 > /* __GDPR__FRAGMENT__
72 > "URIDescriptor" : {
73 > "mimeType" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
74 > "scheme": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
75 > "ext": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
76 > "path": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
77 > }
78 > */
79 > export interface URIDescriptor {
80 > mimeType?: string;
81 > scheme?: string;
82 > ext?: string;
83 > path?: string;
84 > }
85 >
86 > /**
87 > * Determines whether or not we support logging telemetry.
88 > * This checks if the product is capable of collecting telemetry but not whether or not it can send it
89 > * For checking the user setting and what telemetry you can send please check `getTelemetryLevel`.
90 > * This returns true if `--disable-telemetry` wasn't used, the product.json allows for telemetry, and we're not testing an extension
91 > * If false telemetry is disabled throughout the product
92 > * @param productService
93 > * @param environmentService
94 > * @returns false - telemetry is completely disabled, true - telemetry is logged locally, but may not be sent
95 > */
96 > export function supportsTelemetry(productService: IProductService, environmentService: IEnvironmentService): boolean {
97 // If it's OSS and telemetry isn't disabled via the CLI we will allow it for logging only purposes
98 if (!environmentService.isBuilt && !environmentService.disableTelemetry) {
101 return !(environmentService.disableTelemetry || !productService.enableTelemetry);
102 }
104 > /**
105 > * Checks to see if we're in logging only mode to debug telemetry.
106 > * This is if telemetry is enabled and we're in OSS, but no telemetry key is provided so it's not being sent just logged.
107 > * @param productService
108 > * @param environmentService
109 > * @returns True if telemetry is actually disabled and we're only logging for debug purposes
110 > */
111 > export function isLoggingOnly(productService: IProductService, environmentService: IEnvironmentService): boolean {
112 // If we're testing an extension, log telemetry for debug purposes
113 if (environmentService.extensionTestsLocationURI) {
129 return true;
130 }
132 > /**
133 > * Determines how telemetry is handled based on the user's configuration.
134 > *
135 > * @param configurationService
136 > * @returns OFF, ERROR, ON
137 > */
138 > export function getTelemetryLevel(configurationService: IConfigurationService): TelemetryLevel {
139 const newConfig = configurationService.getValue<TelemetryConfiguration>(TELEMETRY_SETTING_ID);
140 const crashReporterConfig = configurationService.getValue<boolean | undefined>(TELEMETRY_CRASH_REPORTER_SETTING_ID);
158 }
159 }
161 > export interface Properties {
162 > [key: string]: string;
163 > }
164 >
165 > export interface Measurements {
166 > [key: string]: number;
167 > }
168 >
169 > export function validateTelemetryData(data?: unknown): { properties: Properties; measurements: Measurements } {
170
171 const properties: Properties = {};
204 };
205 }
207 > interface IRemoteAuthoringConfig {
208 > remoteExtensionTips?: { readonly [remoteName: string]: unknown };
209 > virtualWorkspaceExtensionTips?: { readonly [remoteName: string]: unknown };
210 > }
211 >
212 > export function cleanRemoteAuthority(remoteAuthority: string | undefined, config: IRemoteAuthoringConfig): string {
213 if (!remoteAuthority) {
214 return 'none';
229 return 'other';
230 }
232 function flatten(obj: unknown, result: Record<string, unknown>, order: number = 0, prefix?: string): void {
233 if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
258 }
259 }
261 > /**
262 > * Whether or not this is an internal user
263 > * @param productService The product service
264 > * @param configService The config servivce
265 > * @returns true if internal, false otherwise
266 > */
267 > export function isInternalTelemetry(productService: IProductService, configService: IConfigurationService) {
268 const msftInternalDomains = productService.msftInternalDomains || [];
269 const internalTesting = configService.getValue<boolean>('telemetry.internalTesting');
270 return verifyMicrosoftInternalDomain(msftInternalDomains) || internalTesting;
271 }
273 > interface IPathEnvironment {
274 > appRoot: string;
275 > extensionsPath: string;
276 > userDataPath: string;
277 > userHome: URI;
278 > tmpDir: URI;
279 > }
280 >
281 > export function getPiiPathsFromEnvironment(paths: IPathEnvironment): string[] {
282 return [paths.appRoot, paths.extensionsPath, paths.userHome.fsPath, paths.tmpDir.fsPath, paths.userDataPath];
283 }
285 > //#region Telemetry Cleaning
286 >
287 > /**
288 > * Cleans a given stack of possible paths
289 > * @param stack The stack to sanitize
290 > * @param cleanupPatterns Cleanup patterns to remove from the stack
291 > * @returns The cleaned stack
292 > */
293 function anonymizeFilePaths(stack: string, cleanupPatterns: RegExp[]): string {
294
356 return updatedStack;
357 }
359 > const userDataRegexes = [
360 > { label: 'URL', regex: /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s]*/ },
361 > { label: 'Google API Key', regex: /AIza[A-Za-z0-9_\\\-]{35}/ },
362 > { label: 'JWT', regex: /eyJ[0eXAiOiJKV1Qi|hbGci|a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+/ },
363 > { label: 'Slack Token', regex: /xox[pbar]\-[A-Za-z0-9]/ },
364 > { label: 'GitHub Token', regex: /(gh[psuro]_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59})/ },
365 > { label: 'Generic Secret', regex: /(key|token|sig|secret|signature|password|passwd|pwd|android:value)[^a-zA-Z0-9]/i },
366 > { label: 'CLI Credentials', regex: /((login|psexec|(certutil|psexec)\.exe).{1,50}(\s-u(ser(name)?)?\s+.{3,100})?\s-(admin|user|vm|root)?p(ass(word)?)?\s+["']?[^$\-\/\s]|(^|[\s\r\n\\])net(\.exe)?.{1,5}(user\s+|share\s+\/user:| user -? secrets ? set) \s + [^ $\s \/])/ },
367 > { label: 'Microsoft Entra ID', regex: /eyJ(?:0eXAiOiJKV1Qi|hbGci|[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.)/ },
368 > { label: 'Email', regex: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/ }
369 > ];
370 >
371 > /**
372 > * Redacts a value if it contains commonly leaked PII.
373 > * @param value The value returned (as-is) when no PII is detected
374 > * @param probe The string actually matched against the PII heuristics. Defaults
375 > * to `value`; callers may pass a value that includes a trailing delimiter (e.g. a
376 > * newline) so that heuristics relying on a non-alphanumeric boundary match the
377 > * same way they would against the original whole string.
378 > * @returns A `<REDACTED: ...>` marker if the probe matched, otherwise `value`
379 > */
380 function redactIfPossibleUserInfo(value: string, probe: string = value): string {
381 for (const secretRegex of userDataRegexes) {
386 return value;
387 }
389 > /**
390 > * Attempts to remove commonly leaked PII.
391 > *
392 > * When a match is found the check is applied per line so that a single suspicious
393 > * frame (e.g. a stack frame containing a function name such as `getStorageKey`
394 > * which matches the broad `Generic Secret` heuristic) only redacts that line —
395 > * replacing it with a `<REDACTED: ...>` marker — instead of wiping the entire
396 > * multi-line value such as a whole callstack.
397 > * @param property The property whose offending lines will be replaced with a redaction marker if they contain user data
398 > * @returns The new value for the property
399 > */
400 function removePropertiesWithPossibleUserInfo(property: string): string {
401 // If for some reason it is undefined we skip it (this shouldn't be possible);
436 return lines.join('\n');
437 }
439 >
440 > /**
441 > * Does a best possible effort to clean a data object from any possible PII.
442 > * @param data The data object to clean
443 > * @param paths Any additional patterns that should be removed from the data set
444 > * @returns A new object with the PII removed
445 > */
446 > export function cleanData(data: ITelemetryData | undefined, cleanUpPatterns: RegExp[]): Record<string, unknown> {
447 if (!data) {
448 return {};
src/vs/base/common/jsonSchema.ts 194 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- jsonSchema.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export type JSONSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'array' | 'object';
7 >
8 > export interface IJSONSchema {
9 > id?: string;
10 > $id?: string;
11 > $schema?: string;
12 > type?: JSONSchemaType | JSONSchemaType[];
13 > title?: string;
14 > default?: any;
15 > definitions?: IJSONSchemaMap;
16 > description?: string;
17 > properties?: IJSONSchemaMap;
18 > patternProperties?: IJSONSchemaMap;
19 > additionalProperties?: boolean | IJSONSchema;
20 > minProperties?: number;
21 > maxProperties?: number;
22 > dependencies?: IJSONSchemaMap | { [prop: string]: string[] };
23 > items?: IJSONSchema | IJSONSchema[];
24 > minItems?: number;
25 > maxItems?: number;
26 > uniqueItems?: boolean;
27 > additionalItems?: boolean | IJSONSchema;
28 > pattern?: string;
29 > minLength?: number;
30 > maxLength?: number;
31 > minimum?: number;
32 > maximum?: number;
33 > exclusiveMinimum?: boolean | number;
34 > exclusiveMaximum?: boolean | number;
35 > multipleOf?: number;
36 > required?: string[];
37 > $ref?: string;
38 > anyOf?: IJSONSchema[];
39 > allOf?: IJSONSchema[];
40 > oneOf?: IJSONSchema[];
41 > not?: IJSONSchema;
42 > enum?: any[];
43 > format?: string;
44 >
45 > // schema draft 06
46 > const?: any;
47 > contains?: IJSONSchema;
48 > propertyNames?: IJSONSchema;
49 > examples?: any[];
50 >
51 > // schema draft 07
52 > $comment?: string;
53 > if?: IJSONSchema;
54 > then?: IJSONSchema;
55 > else?: IJSONSchema;
56 >
57 > // schema 2019-09
58 > unevaluatedProperties?: boolean | IJSONSchema;
59 > unevaluatedItems?: boolean | IJSONSchema;
60 > minContains?: number;
61 > maxContains?: number;
62 > deprecated?: boolean;
63 > dependentRequired?: { [prop: string]: string[] };
64 > dependentSchemas?: IJSONSchemaMap;
65 > $defs?: { [name: string]: IJSONSchema };
66 > $anchor?: string;
67 > $recursiveRef?: string;
68 > $recursiveAnchor?: string;
69 > $vocabulary?: any;
70 >
71 > // schema 2020-12
72 > prefixItems?: IJSONSchema[];
73 > $dynamicRef?: string;
74 > $dynamicAnchor?: string;
75 >
76 > // VSCode extensions
77 >
78 > defaultSnippets?: IJSONSchemaSnippet[];
79 > errorMessage?: string;
80 > patternErrorMessage?: string;
81 > deprecationMessage?: string;
82 > markdownDeprecationMessage?: string;
83 > enumDescriptions?: string[];
84 > markdownEnumDescriptions?: string[];
85 > markdownDescription?: string;
86 > doNotSuggest?: boolean;
87 > suggestSortText?: string;
88 > allowComments?: boolean;
89 > allowTrailingCommas?: boolean;
90 > secret?: boolean;
91 > }
92 >
93 > export interface IJSONSchemaMap {
94 > [name: string]: IJSONSchema;
95 > }
96 >
97 > export interface IJSONSchemaSnippet {
98 > label?: string;
99 > description?: string;
100 > body?: any; // a object that will be JSON stringified
101 > bodyText?: string; // an already stringified JSON object that can contain new lines (\n) and tabs (\t)
102 > }
103 >
104 > /**
105 > * Converts a basic JSON schema to a TypeScript type.
106 > */
107 > export type TypeFromJsonSchema<T> =
108 > // enum
109 > T extends { enum: infer EnumValues }
110 > ? UnionOf<EnumValues>
111 >
112 > // Object with list of required properties.
113 > // Values are required or optional based on `required` list.
114 > : T extends { type: 'object'; properties: infer P; required: infer RequiredList }
115 > ? {
116 > [K in keyof P]: IsRequired<K, RequiredList> extends true ? TypeFromJsonSchema<P[K]> : TypeFromJsonSchema<P[K]> | undefined;
117 > } & AdditionalPropertiesType<T>
118 >
119 > // Object with no required properties.
120 > // All values are optional
121 > : T extends { type: 'object'; properties: infer P }
122 > ? { [K in keyof P]: TypeFromJsonSchema<P[K]> | undefined } & AdditionalPropertiesType<T>
123 >
124 > // Array
125 > : T extends { type: 'array'; items: infer Items }
126 > ? Items extends [...infer R]
127 > // If items is an array, we treat it like a tuple
128 > ? { [K in keyof R]: TypeFromJsonSchema<Items[K]> }
129 > : Array<TypeFromJsonSchema<Items>>
130 >
131 > // oneOf / anyof
132 > // These are handled the same way as they both represent a union type.
133 > // However at the validation level, they have different semantics.
134 > : T extends { oneOf: infer I }
135 > ? MapSchemaToType<I>
136 > : T extends { anyOf: infer I }
137 > ? MapSchemaToType<I>
138 >
139 > // Primitive types
140 > : T extends { type: infer Type }
141 > // Basic type
142 > ? Type extends 'string' | 'number' | 'integer' | 'boolean' | 'null'
143 > ? SchemaPrimitiveTypeNameToType<Type>
144 > // Union of primitive types
145 > : Type extends [...infer R]
146 > ? UnionOf<{ [K in keyof R]: SchemaPrimitiveTypeNameToType<R[K]> }>
147 > : never
148 >
149 > // Fallthrough
150 > : never;
151 >
152 > type SchemaPrimitiveTypeNameToType<T> =
153 > T extends 'string' ? string :
154 > T extends 'number' | 'integer' ? number :
155 > T extends 'boolean' ? boolean :
156 > T extends 'null' ? null :
157 > never;
158 >
159 > type UnionOf<T> =
160 > T extends [infer First, ...infer Rest]
161 > ? First | UnionOf<Rest>
162 > : never;
163 >
164 > type IsRequired<K, RequiredList> =
165 > RequiredList extends []
166 > ? false
167 >
168 > : RequiredList extends [K, ...infer _]
169 > ? true
170 >
171 > : RequiredList extends [infer _, ...infer R]
172 > ? IsRequired<K, R>
173 >
174 > : false;
175 >
176 > type AdditionalPropertiesType<Schema> =
177 > Schema extends { additionalProperties: infer AP }
178 > ? AP extends false ? {} : { [key: string]: TypeFromJsonSchema<Schema['additionalProperties']> }
179 > : {};
180 >
181 > type MapSchemaToType<T> = T extends [infer First, ...infer Rest]
182 > ? TypeFromJsonSchema<First> | MapSchemaToType<Rest>
183 > : never;
184 >
185 > interface Equals { schemas: IJSONSchema[]; id?: string }
186 >
187 > export function getCompressedContent(schema: IJSONSchema): string {
188 let hasDups = false;
189
258 return str;
259 }
261 > type IJSONSchemaRef = IJSONSchema | boolean;
262 >
263 function isObject(thing: unknown): thing is object {
264 return typeof thing === 'object' && thing !== null;
265 }
267 > /*
268 > * Traverse a JSON schema and visit each schema node
269 > */
270 function traverseNodes(root: IJSONSchema, visit: (schema: IJSONSchema) => boolean) {
271 if (!root || typeof root !== 'object') {
src/vs/base/common/platform.ts 189 covered LOC · 12 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- platform.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as nls from '../../nls.js';
7 >
8 > export const LANGUAGE_DEFAULT = 'en';
9 >
10 > let _isWindows = false;
11 > let _isMacintosh = false;
12 > let _isLinux = false;
13 > let _isLinuxSnap = false;
14 > let _isNative = false;
15 > let _isWeb = false;
16 > let _isElectron = false;
17 > let _isIOS = false;
18 > let _isCI = false;
19 > let _isMobile = false;
20 > let _locale: string | undefined = undefined;
21 > let _language: string = LANGUAGE_DEFAULT;
22 > let _platformLocale: string = LANGUAGE_DEFAULT;
23 > let _translationsConfigFile: string | undefined = undefined;
24 > let _userAgent: string | undefined = undefined;
25 >
26 > export interface IProcessEnvironment {
27 > [key: string]: string | undefined;
28 > }
29 >
30 > /**
31 > * This interface is intentionally not identical to node.js
32 > * process because it also works in sandboxed environments
33 > * where the process object is implemented differently. We
34 > * define the properties here that we need for `platform`
35 > * to work and nothing else.
36 > */
37 > export interface INodeProcess {
38 > platform: string;
39 > arch: string;
40 > env: IProcessEnvironment;
41 > versions?: {
42 > node?: string;
43 > electron?: string;
44 > chrome?: string;
45 > };
46 > type?: string;
47 > cwd: () => string;
48 > }
49 >
50 > declare const process: INodeProcess;
51 >
52 > const $globalThis: any = globalThis;
53 >
54 > let nodeProcess: INodeProcess | undefined = undefined;
55 > if (typeof $globalThis.vscode !== 'undefined' && typeof $globalThis.vscode.process !== 'undefined') {
56 // Native environment (sandboxed)
57 nodeProcess = $globalThis.vscode.process;
58 > } else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') { platform.ts
59 > // Native environment (non-sandboxed)
60 > nodeProcess = process;
61 > }
62 >
63 > const isElectronProcess = typeof nodeProcess?.versions?.electron === 'string';
64 > const isElectronRenderer = isElectronProcess && nodeProcess?.type === 'renderer';
65 >
66 > interface INavigator {
67 > userAgent: string;
68 > maxTouchPoints?: number;
69 > language: string;
70 > }
71 > declare const navigator: INavigator;
72 >
73 > // Native environment
74 > if (typeof nodeProcess === 'object') {
75 > _isWindows = (nodeProcess.platform === 'win32');
76 > _isMacintosh = (nodeProcess.platform === 'darwin');
77 > _isLinux = (nodeProcess.platform === 'linux');
78 > _isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION'];
79 > _isElectron = isElectronProcess;
80 > _isCI = !!nodeProcess.env['CI'] || !!nodeProcess.env['BUILD_ARTIFACTSTAGINGDIRECTORY'] || !!nodeProcess.env['GITHUB_WORKSPACE'];
81 > _locale = LANGUAGE_DEFAULT;
82 > _language = LANGUAGE_DEFAULT;
83 > const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG'];
84 > if (rawNlsConfig) {
85 try {
86 const nlsConfig: nls.INLSConfiguration = JSON.parse(rawNlsConfig);
113 console.error('Unable to resolve platform.');
114 }
115 > platform.ts
116 > export const enum Platform {
117 > Web,
118 > Mac,
119 > Linux,
120 > Windows
121 > }
122 > export type PlatformName = 'Web' | 'Windows' | 'Mac' | 'Linux';
123 >
124 > export function PlatformToString(platform: Platform): PlatformName {
125 switch (platform) {
126 case Platform.Web: return 'Web';
130 }
131 }
132 > platform.ts
133 > let _platform: Platform = Platform.Web;
134 > if (_isMacintosh) {
135 _platform = Platform.Mac;
136 > } else if (_isWindows) { platform.ts
137 _platform = Platform.Windows;
138 > } else if (_isLinux) { platform.ts
139 > _platform = Platform.Linux;
140 > }
141 >
142 > export const isWindows = _isWindows;
143 > export const isMacintosh = _isMacintosh;
144 > export const isLinux = _isLinux;
145 > export const isLinuxSnap = _isLinuxSnap;
146 > export const isNative = _isNative;
147 > export const isElectron = _isElectron;
148 > export const isWeb = _isWeb;
149 > export const isWebWorker = (_isWeb && typeof $globalThis.importScripts === 'function');
150 > export const webWorkerOrigin = isWebWorker ? $globalThis.origin : undefined;
151 > export const isIOS = _isIOS;
152 > export const isMobile = _isMobile;
153 > /**
154 > * Whether we run inside a CI environment, such as
155 > * GH actions or Azure Pipelines.
156 > */
157 > export const isCI = _isCI;
158 > export const platform = _platform;
159 > export const userAgent = _userAgent;
160 >
161 > /**
162 > * The language used for the user interface. The format of
163 > * the string is all lower case (e.g. zh-tw for Traditional
164 > * Chinese or de for German)
165 > */
166 > export const language = _language;
167 >
168 > export namespace Language {
169 >
170 > export function value(): string {
171 return language;
172 }
173 > platform.ts
174 > export function isDefaultVariant(): boolean {
175 if (language.length === 2) {
176 return language === 'en';
181 }
182 }
183 > platform.ts
184 > export function isDefault(): boolean {
185 return language === 'en';
186 }
187 > } platform.ts
188 >
189 > /**
190 > * Desktop: The OS locale or the locale specified by --locale or `argv.json`.
191 > * Web: matches `platformLocale`.
192 > *
193 > * The UI is not necessarily shown in the provided locale.
194 > */
195 > export const locale = _locale;
196 >
197 > /**
198 > * This will always be set to the OS/browser's locale regardless of
199 > * what was specified otherwise. The format of the string is all
200 > * lower case (e.g. zh-tw for Traditional Chinese). The UI is not
201 > * necessarily shown in the provided locale.
202 > */
203 > export const platformLocale = _platformLocale;
204 >
205 > /**
206 > * The translations that are available through language packs.
207 > */
208 > export const translationsConfigFile = _translationsConfigFile;
209 >
210 > export const setTimeout0IsFaster = (typeof $globalThis.postMessage === 'function' && !$globalThis.importScripts);
211 >
212 > /**
213 > * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-.
214 > *
215 > * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay
216 > * that browsers set when the nesting level is > 5.
217 > */
218 > export const setTimeout0 = (() => {
219 > if (setTimeout0IsFaster) {
220 interface IQueueElement {
221 id: number;
246 };
247 }
248 > return (callback: () => void) => setTimeout(callback); platform.ts
249 > })();
250 >
251 > export const enum OperatingSystem {
252 > Windows = 1,
253 > Macintosh = 2,
254 > Linux = 3
255 > }
256 > export const OS = (_isMacintosh || _isIOS ? OperatingSystem.Macintosh : (_isWindows ? OperatingSystem.Windows : OperatingSystem.Linux));
257 >
258 > let _isLittleEndian = true;
259 > let _isLittleEndianComputed = false;
260 > export function isLittleEndian(): boolean {
261 if (!_isLittleEndianComputed) {
262 _isLittleEndianComputed = true;
269 return _isLittleEndian;
270 }
271 > platform.ts
272 > export const isChrome = !!(userAgent && userAgent.indexOf('Chrome') >= 0);
273 > export const isFirefox = !!(userAgent && userAgent.indexOf('Firefox') >= 0);
274 > export const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf('Safari') >= 0));
275 > export const isEdge = !!(userAgent && userAgent.indexOf('Edg/') >= 0);
276 > export const isAndroid = !!(userAgent && userAgent.indexOf('Android') >= 0);
277 > export const hasElectronUserAgent = !!(userAgent && userAgent.indexOf('Electron') >= 0);
278 >
279 > export function isTahoeOrNewer(osVersion: string): boolean {
280 return parseFloat(osVersion) >= 25;
281 }
src/vs/base/common/errors.ts 183 covered LOC · 32 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- errors.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export interface ErrorListenerCallback {
7 > (error: any): void;
8 > }
9 >
10 > export interface ErrorListenerUnbind {
11 > (): void;
12 > }
13 >
14 > // Avoid circular dependency on EventEmitter by implementing a subset of the interface.
15 > export class ErrorHandler {
16 > private unexpectedErrorHandler: (e: any) => void;
17 > private listeners: ErrorListenerCallback[];
18 >
19 > constructor() {
20 >
21 > this.listeners = [];
22 >
23 > this.unexpectedErrorHandler = function (e: any) {
24 setTimeout(() => {
25 if (e.stack) {
34 }, 0);
35 };
36 > } errors.ts
37 >
38 > addListener(listener: ErrorListenerCallback): ErrorListenerUnbind {
39 this.listeners.push(listener);
40
43 };
44 }
45 > errors.ts
46 > private emit(e: any): void {
47 this.listeners.forEach((listener) => {
48 listener(e);
49 });
50 }
51 > errors.ts
52 > private _removeListener(listener: ErrorListenerCallback): void {
53 this.listeners.splice(this.listeners.indexOf(listener), 1);
54 }
55 > errors.ts
56 > setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {
57 > this.unexpectedErrorHandler = newUnexpectedErrorHandler;
58 > }
59 >
60 > getUnexpectedErrorHandler(): (e: any) => void {
61 return this.unexpectedErrorHandler;
62 }
63 > errors.ts
64 > onUnexpectedError(e: any): void {
65 this.unexpectedErrorHandler(e);
66 this.emit(e);
67 }
68 > errors.ts
69 > // For external errors, we don't want the listeners to be called
70 > onUnexpectedExternalError(e: any): void {
71 this.unexpectedErrorHandler(e);
72 }
73 > } errors.ts
74 >
75 > export const errorHandler = new ErrorHandler();
76 >
77 > /** @skipMangle */
78 > export function setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {
79 > errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
80 > }
81 >
82 > /**
83 > * Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be
84 > * logged at most once, to avoid a loop.
85 > *
86 > * @see https://github.com/microsoft/vscode-remote-release/issues/6481
87 > */
88 > export function isSigPipeError(e: unknown): e is Error {
89 if (!e || typeof e !== 'object') {
90 return false;
94 return cast.code === 'EPIPE' && cast.syscall?.toUpperCase() === 'WRITE';
95 }
96 > errors.ts
97 > /**
98 > * This function should only be called with errors that indicate a bug in the product.
99 > * E.g. buggy extensions/invalid user-input/network issues should not be able to trigger this code path.
100 > * If they are, this indicates there is also a bug in the product.
101 > */
102 > export function onBugIndicatingError(e: any): undefined {
103 errorHandler.onUnexpectedError(e);
104 return undefined;
105 }
106 > errors.ts
107 > export function onUnexpectedError(e: any): undefined {
108 // ignore errors from cancelled promises
109 if (!isCancellationError(e)) {
112 return undefined;
113 }
114 > errors.ts
115 > export function onUnexpectedExternalError(e: any): undefined {
116 // ignore errors from cancelled promises
117 if (!isCancellationError(e)) {
120 return undefined;
121 }
122 > errors.ts
123 > type ObjectWithCode = {
124 > readonly code: unknown;
125 > };
126 >
127 function hasErrorCode(error: object): error is ObjectWithCode {
128 return Object.hasOwn(error, 'code');
129 }
130 > errors.ts
131 > export function getErrorCode(error: unknown): string | undefined {
132 if (!error || typeof error !== 'object' || !hasErrorCode(error)) {
133 return undefined;
136 return typeof code === 'string' || typeof code === 'number' ? String(code) : undefined;
137 }
138 > errors.ts
139 > export interface SerializedError {
140 > readonly $isError: true;
141 > readonly name: string;
142 > readonly message: string;
143 > readonly stack: string;
144 > readonly noTelemetry: boolean;
145 > readonly code?: string;
146 > readonly cause?: SerializedError;
147 > }
148 >
149 > type ErrorWithCode = Error & {
150 > code: string | undefined;
151 > };
152 >
153 > export function transformErrorForSerialization(error: Error): SerializedError;
154 > export function transformErrorForSerialization(error: any): any;
155 > export function transformErrorForSerialization(error: any): any {
156 if (error instanceof Error) {
157 const { name, message, cause } = error;
172 return error;
173 }
174 > errors.ts
175 > export function transformErrorFromSerialization(data: SerializedError): Error {
176 let error: Error;
177 if (data.noTelemetry) {
191 return error;
192 }
193 > errors.ts
194 > // see https://github.com/v8/v8/wiki/Stack%20Trace%20API#basic-stack-traces
195 > export interface V8CallSite {
196 > getThis(): unknown;
197 > getTypeName(): string | null;
198 > getFunction(): Function | undefined;
199 > getFunctionName(): string | null;
200 > getMethodName(): string | null;
201 > getFileName(): string | null;
202 > getLineNumber(): number | null;
203 > getColumnNumber(): number | null;
204 > getEvalOrigin(): string | undefined;
205 > isToplevel(): boolean;
206 > isEval(): boolean;
207 > isNative(): boolean;
208 > isConstructor(): boolean;
209 > toString(): string;
210 > }
211 >
212 > export const canceledName = 'Canceled';
213 >
214 > /**
215 > * Checks if the given error is a promise in canceled state
216 > */
217 > export function isCancellationError(error: any): boolean {
218 if (error instanceof CancellationError) {
219 return true;
221 return error instanceof Error && error.name === canceledName && error.message === canceledName;
222 }
223 > errors.ts
224 > // !!!IMPORTANT!!!
225 > // Do NOT change this class because it is also used as an API-type.
226 > export class CancellationError extends Error {
227 > constructor() {
228 super(canceledName);
229 this.name = this.message;
230 }
231 > } errors.ts
232 >
233 > export class PendingMigrationError extends Error {
234 >
235 > private static readonly _name = 'PendingMigrationError';
236 >
237 > static is(error: unknown): error is PendingMigrationError {
238 return error instanceof PendingMigrationError || (error instanceof Error && error.name === PendingMigrationError._name);
239 }
240 > errors.ts
241 > constructor(message: string) {
242 super(message);
243 this.name = PendingMigrationError._name;
244 }
245 > } errors.ts
246 >
247 > /**
248 > * @deprecated use {@link CancellationError `new CancellationError()`} instead
249 > */
250 > export function canceled(): Error {
251 const error = new Error(canceledName);
252 error.name = error.message;
253 return error;
254 }
255 > errors.ts
256 > export function illegalArgument(name?: string): Error {
257 if (name) {
258 return new Error(`Illegal argument: ${name}`);
261 }
262 }
263 > errors.ts
264 > export function illegalState(name?: string): Error {
265 if (name) {
266 return new Error(`Illegal state: ${name}`);
269 }
270 }
271 > errors.ts
272 > export class ReadonlyError extends TypeError {
273 > constructor(name?: string) {
274 super(name ? `${name} is read-only and cannot be changed` : 'Cannot change read-only property');
275 }
276 > } errors.ts
277 >
278 > export function getErrorMessage(err: any): string {
279 if (!err) {
280 return 'Error';
291 return String(err);
292 }
293 > errors.ts
294 > export class NotImplementedError extends Error {
295 > constructor(message?: string) {
296 super('NotImplemented');
297 if (message) {
299 }
300 }
301 > } errors.ts
302 >
303 > export class NotSupportedError extends Error {
304 > constructor(message?: string) {
305 super('NotSupported');
306 if (message) {
308 }
309 }
310 > } errors.ts
311 >
312 > export class ExpectedError extends Error {
313 readonly isExpected = true;
314 > } errors.ts
315 >
316 > /**
317 > * Error that when thrown won't be logged in telemetry as an unhandled error.
318 > */
319 > export class ErrorNoTelemetry extends Error {
320 > override readonly name: string;
321 >
322 > constructor(msg?: string) {
323 super(msg);
324 this.name = 'CodeExpectedError';
325 }
326 > errors.ts
327 > public static fromError(err: Error): ErrorNoTelemetry {
328 if (err instanceof ErrorNoTelemetry) {
329 return err;
335 return result;
336 }
337 > errors.ts
338 > public static isErrorNoTelemetry(err: Error): err is ErrorNoTelemetry {
339 return err.name === 'CodeExpectedError';
340 }
341 > } errors.ts
342 >
343 > /**
344 > * This error indicates a bug.
345 > * Do not throw this for invalid user input.
346 > * Only catch this error to recover gracefully from bugs.
347 > */
348 > export class BugIndicatingError extends Error {
349 > constructor(message?: string) {
350 super(message || 'An unexpected bug occurred.');
351 Object.setPrototypeOf(this, BugIndicatingError.prototype);
src/vs/platform/instantiation/common/instantiationService.ts 172 covered LOC · 44 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- instantiationService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { GlobalIdleValue } from '../../../base/common/async.js';
7 > import { Event } from '../../../base/common/event.js';
8 > import { illegalState } from '../../../base/common/errors.js';
9 > import { DisposableStore, dispose, IDisposable, isDisposable, toDisposable } from '../../../base/common/lifecycle.js';
10 > import { SyncDescriptor, SyncDescriptor0 } from './descriptors.js';
11 > import { Graph } from './graph.js';
12 > import { GetLeadingNonServiceArgs, IInstantiationService, ServiceIdentifier, ServicesAccessor, _util } from './instantiation.js';
13 > import { ServiceCollection } from './serviceCollection.js';
14 > import { LinkedList } from '../../../base/common/linkedList.js';
15 >
16 > // TRACING
17 > const _enableAllTracing = false
18 > // || "TRUE" // DO NOT CHECK IN!
19 > ;
20 >
21 > class CyclicDependencyError extends Error {
22 > constructor(graph: Graph<any>) {
23 super('cyclic dependency between services');
24 this.message = graph.findCycleSlow() ?? `UNABLE to detect cycle, dumping graph: \n${graph.toString()}`;
25 }
27 >
28 > export class InstantiationService implements IInstantiationService {
29 >
30 > declare readonly _serviceBrand: undefined;
31 >
32 > readonly _globalGraph?: Graph<string>;
33 > private _globalGraphImplicitDependency?: string;
34 >
35 > private _isDisposed = false;
36 > private readonly _servicesToMaybeDispose = new Set<any>();
37 > private readonly _children = new Set<InstantiationService>();
38 >
39 > constructor(
40 > private readonly _services: ServiceCollection = new ServiceCollection(), instantiationService.ts
41 > private readonly _strict: boolean = false,
42 > private readonly _parent?: InstantiationService,
43 > private readonly _enableTracing: boolean = _enableAllTracing
44 > ) {
45 >
46 > this._services.set(IInstantiationService, this);
47 > this._globalGraph = _enableTracing ? _parent?._globalGraph ?? new Graph(e => e) : undefined;
48 > }
50 > dispose(): void {
51 if (!this._isDisposed) {
52 this._isDisposed = true;
86 return result;
87 }
89 > invokeFunction<R, TS extends any[] = []>(fn: (accessor: ServicesAccessor, ...args: TS) => R, ...args: TS): R {
90 this._throwIfDisposed();
91
113 }
114 }
116 > createInstance<T>(descriptor: SyncDescriptor0<T>): T;
117 > createInstance<Ctor extends new (...args: any[]) => unknown, R extends InstanceType<Ctor>>(ctor: Ctor, ...args: GetLeadingNonServiceArgs<ConstructorParameters<Ctor>>): R;
118 > createInstance(ctorOrDescriptor: any | SyncDescriptor<any>, ...rest: unknown[]): unknown {
119 > this._throwIfDisposed(); instantiationService.ts
120 >
121 > let _trace: Trace;
122 > let result: unknown;
123 > if (ctorOrDescriptor instanceof SyncDescriptor) {
124 _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor.ctor);
125 result = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
126 > } else { instantiationService.ts
127 > _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor);
128 > result = this._createInstance(ctorOrDescriptor, rest, _trace);
129 > }
130 > _trace.stop();
131 > return result;
132 > }
134 > private _createInstance<T>(ctor: any, args: unknown[] = [], _trace: Trace): T {
136 > // arguments defined by service decorators
137 > const serviceDependencies = _util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
138 > const serviceArgs: unknown[] = [];
139 > for (const dependency of serviceDependencies) {
140 > const service = this._getOrCreateServiceInstance(dependency.id, _trace); instantiationService.ts
141 > if (!service) {
142 > this._throwIfStrict(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`, false); instantiationService.ts
143 > }
144 > serviceArgs.push(service); instantiationService.ts
145 > }
147 > const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
148 >
149 > // check for argument mismatches, adjust static args if needed
150 > if (args.length !== firstServiceArgPos) {
151 console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
152
158 }
159 }
161 > // now create the instance
162 > return Reflect.construct<any, T>(ctor, args.concat(serviceArgs));
163 > }
165 > private _setCreatedServiceInstance<T>(id: ServiceIdentifier<T>, instance: T): void {
166 if (this._services.get(id) instanceof SyncDescriptor) {
167 this._services.set(id, instance);
172 }
173 }
175 > private _getServiceInstanceOrDescriptor<T>(id: ServiceIdentifier<T>): T | SyncDescriptor<T> {
176 > const instanceOrDesc = this._services.get(id); instantiationService.ts
177 > if (!instanceOrDesc && this._parent) {
178 > return this._parent._getServiceInstanceOrDescriptor(id); instantiationService.ts
179 > } else { instantiationService.ts
180 > return instanceOrDesc;
181 > }
182 > }
184 > protected _getOrCreateServiceInstance<T>(id: ServiceIdentifier<T>, _trace: Trace): T {
185 > if (this._globalGraph && this._globalGraphImplicitDependency) { instantiationService.ts
186 this._globalGraph.insertEdge(this._globalGraphImplicitDependency, String(id));
187 }
188 > const thing = this._getServiceInstanceOrDescriptor(id); instantiationService.ts
189 > if (thing instanceof SyncDescriptor) {
190 return this._safeCreateAndCacheServiceInstance(id, thing, _trace.branch(id, true));
191 > } else { instantiationService.ts
192 > _trace.branch(id, false); instantiationService.ts
193 > return thing;
194 > }
197 > private readonly _activeInstantiations = new Set<ServiceIdentifier<any>>();
198 >
199 >
200 > private _safeCreateAndCacheServiceInstance<T>(id: ServiceIdentifier<T>, desc: SyncDescriptor<T>, _trace: Trace): T {
201 if (this._activeInstantiations.has(id)) {
202 throw new Error(`illegal state - RECURSIVELY instantiating service '${id}'`);
209 }
210 }
212 > private _createAndCacheServiceInstance<T>(id: ServiceIdentifier<T>, desc: SyncDescriptor<T>, _trace: Trace): T {
213
214 type Triple = { id: ServiceIdentifier<any>; desc: SyncDescriptor<any>; _trace: Trace };
279 return <T>this._getServiceInstanceOrDescriptor(id);
280 }
282 > private _createServiceInstanceWithOwner<T>(id: ServiceIdentifier<T>, ctor: any, args: unknown[] = [], supportsDelayedInstantiation: boolean, _trace: Trace): T {
283 if (this._services.get(id) instanceof SyncDescriptor) {
284 return this._createServiceInstance(id, ctor, args, supportsDelayedInstantiation, _trace, this._servicesToMaybeDispose);
289 }
290 }
292 > private _createServiceInstance<T>(id: ServiceIdentifier<T>, ctor: any, args: unknown[] = [], supportsDelayedInstantiation: boolean, _trace: Trace, disposeBucket: Set<any>): T {
293 if (!supportsDelayedInstantiation) {
294 // eager instantiation
384 }
385 }
387 > private _throwIfStrict(msg: string, printWarning: boolean): void {
388 > if (printWarning) { instantiationService.ts
389 console.warn(msg);
390 }
391 > if (this._strict) { instantiationService.ts
392 throw new Error(msg);
393 }
396 >
397 > //#region -- tracing ---
398 >
399 > const enum TraceType {
400 > None = 0,
401 > Creation = 1,
402 > Invocation = 2,
403 > Branch = 3,
404 > }
405 >
406 > export class Trace {
407 >
408 > static all = new Set<string>();
409 >
410 > private static readonly _None = new class extends Trace {
411 > constructor() { super(TraceType.None, null); }
412 > override stop() { }
413 > override branch() { return this; }
414 > };
415 >
416 > static traceInvocation(_enableTracing: boolean, ctor: any): Trace {
417 return !_enableTracing ? Trace._None : new Trace(TraceType.Invocation, ctor.name || new Error().stack!.split('\n').slice(3, 4).join('\n'));
418 }
420 > static traceCreation(_enableTracing: boolean, ctor: any): Trace {
421 > return !_enableTracing ? Trace._None : new Trace(TraceType.Creation, ctor.name); instantiationService.ts
422 > }
424 > private static _totals: number = 0;
425 > private readonly _start: number = Date.now();
426 > private readonly _dep: [ServiceIdentifier<any>, boolean, Trace?][] = [];
427 >
428 > private constructor(
429 > readonly type: TraceType,
430 > readonly name: string | null
431 > ) { }
432 >
433 > branch(id: ServiceIdentifier<any>, first: boolean): Trace {
434 const child = new Trace(TraceType.Branch, id.toString());
435 this._dep.push([id, first, child]);
436 return child;
437 }
439 > stop() {
440 const dur = Date.now() - this._start;
441 Trace._totals += dur;
src/vs/platform/userDataSync/common/abstractJsonSynchronizer.ts 170 covered LOC · 31 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- abstractJsonSynchronizer.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken } from '../../../base/common/cancellation.js';
7 > import { URI } from '../../../base/common/uri.js';
8 > import { IConfigurationService } from '../../configuration/common/configuration.js';
9 > import { IEnvironmentService } from '../../environment/common/environment.js';
10 > import { IFileService } from '../../files/common/files.js';
11 > import { IStorageService } from '../../storage/common/storage.js';
12 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
13 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
14 > import { IUserDataProfile } from '../../userDataProfile/common/userDataProfile.js';
15 > import { AbstractFileSynchroniser, IAcceptResult, IFileResourcePreview, IMergeResult } from './abstractSynchronizer.js';
16 > import { Change, IRemoteUserData, IUserDataSyncLocalStoreService, IUserDataSyncConfiguration, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, USER_DATA_SYNC_SCHEME, SyncResource } from './userDataSync.js';
17 >
18 > export interface IJsonResourcePreview extends IFileResourcePreview {
19 > previewResult: IMergeResult;
20 > }
21 >
22 > export abstract class AbstractJsonSynchronizer extends AbstractFileSynchroniser implements IUserDataSynchroniser {
23 >
24 > protected readonly version: number = 1;
25 > private readonly previewResource: URI;
26 > private readonly baseResource: URI;
27 > private readonly localResource: URI;
28 > private readonly remoteResource: URI;
29 > private readonly acceptedResource: URI;
30 >
31 > constructor(
32 > fileResource: URI, abstractJsonSynchronizer.ts
33 > syncResourceMetadata: { syncResource: SyncResource; profile: IUserDataProfile },
34 > collection: string | undefined,
35 > previewFileName: string,
36 > @IFileService fileService: IFileService,
37 > @IEnvironmentService environmentService: IEnvironmentService,
38 > @IStorageService storageService: IStorageService,
39 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
40 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
41 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
42 > @ITelemetryService telemetryService: ITelemetryService,
43 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
44 > @IConfigurationService configurationService: IConfigurationService,
45 > @IUriIdentityService uriIdentityService: IUriIdentityService,
46 > ) {
47 > super(fileResource, syncResourceMetadata, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
48 >
49 > this.previewResource = this.extUri.joinPath(this.syncPreviewFolder, previewFileName);
50 > this.baseResource = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' });
51 > this.localResource = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' });
52 > this.remoteResource = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' });
53 > this.acceptedResource = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' });
54 > }
56 > protected abstract getContentFromSyncContent(syncContent: string): string | null;
57 > protected abstract toSyncContent(content: string | null): object;
58 >
59 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean, userDataSyncConfiguration: IUserDataSyncConfiguration): Promise<IJsonResourcePreview[]> {
60 > const remoteContent = remoteUserData.syncData ? this.getContentFromSyncContent(remoteUserData.syncData.content) : null; abstractJsonSynchronizer.ts
61 >
62 > // Use remote data as last sync data if last sync data does not exist and remote data is from same machine
63 > lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
64 > const lastSyncContent: string | null = lastSyncUserData?.syncData ? this.getContentFromSyncContent(lastSyncUserData.syncData.content) : null;
65 >
66 > // Get file content last to get the latest
67 > const fileContent = await this.getLocalFileContent();
68 >
69 > let content: string | null = null;
70 > let hasLocalChanged: boolean = false;
71 > let hasRemoteChanged: boolean = false;
72 > let hasConflicts: boolean = false;
73 >
74 > if (remoteUserData.syncData) {
75 const localContent = fileContent ? fileContent.value.toString() : null;
76 if (!lastSyncContent // First time sync
86 }
87 }
89 > // First time syncing to remote
90 > else if (fileContent) {
91 > this.logService.trace(`${this.syncResourceLogLabel}: Remote ${this.syncResource.syncResource} does not exist. Synchronizing ${this.syncResource.syncResource} for the first time.`); abstractJsonSynchronizer.ts
92 > content = fileContent.value.toString();
93 > hasRemoteChanged = true;
94 > }
96 > const previewResult: IMergeResult = {
97 > content: hasConflicts ? lastSyncContent : content,
98 > localChange: hasLocalChanged ? fileContent ? Change.Modified : Change.Added : Change.None,
99 > remoteChange: hasRemoteChanged ? Change.Modified : Change.None,
100 > hasConflicts
101 > };
102 >
103 > const localContent = fileContent ? fileContent.value.toString() : null;
104 > return [{
105 > fileContent,
106 >
107 > baseResource: this.baseResource,
108 > baseContent: lastSyncContent,
109 >
110 > localResource: this.localResource,
111 > localContent,
112 > localChange: previewResult.localChange,
113 >
114 > remoteResource: this.remoteResource,
115 > remoteContent,
116 > remoteChange: previewResult.remoteChange,
117 >
118 > previewResource: this.previewResource,
119 > previewResult,
120 > acceptedResource: this.acceptedResource,
121 > }];
122 > }
124 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
125 const lastSyncContent: string | null = lastSyncUserData?.syncData ? this.getContentFromSyncContent(lastSyncUserData.syncData.content) : null;
126 if (lastSyncContent === null) {
133 return result.hasLocalChanged || result.hasRemoteChanged;
134 }
136 > protected async getMergeResult(resourcePreview: IJsonResourcePreview, token: CancellationToken): Promise<IMergeResult> {
137 > return resourcePreview.previewResult; abstractJsonSynchronizer.ts
138 > }
140 > protected async getAcceptResult(resourcePreview: IJsonResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
141 > /* Accept local resource */ abstractJsonSynchronizer.ts
142 > if (this.extUri.isEqual(resource, this.localResource)) {
143 return {
144 content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
147 };
148 }
150 > /* Accept remote resource */
151 > if (this.extUri.isEqual(resource, this.remoteResource)) {
152 return {
153 content: resourcePreview.remoteContent,
156 };
157 }
159 > /* Accept preview resource */
160 > if (this.extUri.isEqual(resource, this.previewResource)) {
161 > if (content === undefined) {
162 > return {
163 > content: resourcePreview.previewResult.content,
164 > localChange: resourcePreview.previewResult.localChange,
165 > remoteChange: resourcePreview.previewResult.remoteChange,
166 > };
167 > } else {
168 return {
169 content,
172 };
173 }
175
176 throw new Error(`Invalid Resource: ${resource.toString()}`);
179 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [IJsonResourcePreview, IAcceptResult][], force: boolean): Promise<void> {
180 > const { fileContent } = resourcePreviews[0][0]; abstractJsonSynchronizer.ts
181 > const { content, localChange, remoteChange } = resourcePreviews[0][1];
182 >
183 > if (localChange === Change.None && remoteChange === Change.None) {
184 > this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing ${this.syncResource.syncResource}.`); abstractJsonSynchronizer.ts
185 > }
187 > if (localChange !== Change.None) {
188 this.logService.trace(`${this.syncResourceLogLabel}: Updating local ${this.syncResource.syncResource}...`);
189 if (fileContent) {
197 this.logService.info(`${this.syncResourceLogLabel}: Updated local ${this.syncResource.syncResource}`);
198 }
200 > if (remoteChange !== Change.None) {
201 > this.logService.trace(`${this.syncResourceLogLabel}: Updating remote ${this.syncResource.syncResource}...`); abstractJsonSynchronizer.ts
202 > const remoteContents = JSON.stringify(this.toSyncContent(content));
203 > remoteUserData = await this.updateRemoteUserData(remoteContents, force ? null : remoteUserData.ref);
204 > this.logService.info(`${this.syncResourceLogLabel}: Updated remote ${this.syncResource.syncResource}`); abstractJsonSynchronizer.ts
205 > }
207 > // Delete the preview
208 > try {
209 > await this.fileService.del(this.previewResource);
210 > } catch (e) { /* ignore */ }
211 >
212 > if (lastSyncUserData?.ref !== remoteUserData.ref) { abstractJsonSynchronizer.ts
213 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized ${this.syncResource.syncResource}...`); abstractJsonSynchronizer.ts
214 > await this.updateLastSyncUserData(remoteUserData);
215 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized ${this.syncResource.syncResource}`);
216 > }
219 > async hasLocalData(): Promise<boolean> {
220 return this.fileService.exists(this.file);
221 }
223 > async resolveContent(uri: URI): Promise<string | null> {
224 if (this.extUri.isEqual(this.remoteResource, uri)
225 || this.extUri.isEqual(this.baseResource, uri)
231 return null;
232 }
234 > private merge(originalLocalContent: string | null, originalRemoteContent: string | null, baseContent: string | null): {
235 content: string | null;
236 hasLocalChanged: boolean;
274 return { content: originalLocalContent, hasLocalChanged: true, hasRemoteChanged: true, hasConflicts: true };
275 }
src/vs/platform/environment/common/environment.ts 165 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- environment.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { URI } from '../../../base/common/uri.js';
7 > import { NativeParsedArgs } from './argv.js';
8 > import { createDecorator, refineServiceDecorator } from '../../instantiation/common/instantiation.js';
9 >
10 > export const IEnvironmentService = createDecorator<IEnvironmentService>('environmentService');
11 > export const INativeEnvironmentService = refineServiceDecorator<IEnvironmentService, INativeEnvironmentService>(IEnvironmentService);
12 >
13 > export interface IDebugParams {
14 > port: number | null;
15 > break: boolean;
16 > }
17 >
18 > export interface IExtensionHostDebugParams extends IDebugParams {
19 > debugId?: string;
20 > env?: Record<string, string>;
21 > }
22 >
23 > /**
24 > * Type of extension.
25 > *
26 > * **NOTE**: This is defined in `platform/environment` because it can appear as a CLI argument.
27 > */
28 > export type ExtensionKind = 'ui' | 'workspace' | 'web';
29 >
30 > /**
31 > * A basic environment service that can be used in various processes,
32 > * such as main, renderer and shared process. Use subclasses of this
33 > * service for specific environment.
34 > */
35 > export interface IEnvironmentService {
36 >
37 > readonly _serviceBrand: undefined;
38 >
39 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
40 > //
41 > // NOTE: KEEP THIS INTERFACE AS SMALL AS POSSIBLE.
42 > //
43 > // AS SUCH:
44 > // - PUT NON-WEB PROPERTIES INTO NATIVE ENVIRONMENT SERVICE
45 > // - PUT WORKBENCH ONLY PROPERTIES INTO WORKBENCH ENVIRONMENT SERVICE
46 > // - PUT ELECTRON-MAIN ONLY PROPERTIES INTO MAIN ENVIRONMENT SERVICE
47 > //
48 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
49 >
50 > // --- user roaming data
51 > stateResource: URI;
52 > userRoamingDataHome: URI;
53 > keyboardLayoutResource: URI;
54 > argvResource: URI;
55 >
56 > // --- data paths
57 > untitledWorkspacesHome: URI;
58 > workspaceStorageHome: URI;
59 > localHistoryHome: URI;
60 > cacheHome: URI;
61 > appSharedDataHome: URI;
62 >
63 > // --- settings sync
64 > userDataSyncHome: URI;
65 > sync: 'on' | 'off' | undefined;
66 >
67 > // --- continue edit session
68 > continueOn?: string;
69 > editSessionId?: string;
70 >
71 > // --- extension development
72 > debugExtensionHost: IExtensionHostDebugParams;
73 > isExtensionDevelopment: boolean;
74 > disableExtensions: boolean | string[];
75 > skipBuiltinExtensions?: readonly string[];
76 > enableExtensions?: readonly string[];
77 > extensionDevelopmentLocationURI?: URI[];
78 > extensionDevelopmentKind?: ExtensionKind[];
79 > extensionTestsLocationURI?: URI;
80 >
81 > // --- logging
82 > logsHome: URI;
83 > logLevel?: string;
84 > extensionLogLevel?: [string, string][];
85 > verbose: boolean;
86 > isBuilt: boolean;
87 >
88 > // --- telemetry/exp
89 > disableTelemetry: boolean;
90 > disableExperiments: boolean;
91 > serviceMachineIdResource: URI;
92 >
93 > // --- agent sessions workspace
94 > agentSessionsWorkspace: URI;
95 > // --- Policy
96 > policyFile?: URI;
97 >
98 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
99 > //
100 > // NOTE: KEEP THIS INTERFACE AS SMALL AS POSSIBLE.
101 > //
102 > // AS SUCH:
103 > // - PUT NON-WEB PROPERTIES INTO NATIVE ENVIRONMENT SERVICE
104 > // - PUT WORKBENCH ONLY PROPERTIES INTO WORKBENCH ENVIRONMENT SERVICE
105 > // - PUT ELECTRON-MAIN ONLY PROPERTIES INTO MAIN ENVIRONMENT SERVICE
106 > //
107 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
108 > }
109 >
110 > /**
111 > * A subclass of the `IEnvironmentService` to be used only in native
112 > * environments (Windows, Linux, macOS) but not e.g. web.
113 > */
114 > export interface INativeEnvironmentService extends IEnvironmentService {
115 >
116 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
117 > //
118 > // NOTE: KEEP THIS INTERFACE AS SMALL AS POSSIBLE.
119 > //
120 > // AS SUCH:
121 > // - PUT WORKBENCH ONLY PROPERTIES INTO WORKBENCH ENVIRONMENT SERVICE
122 > // - PUT ELECTRON-MAIN ONLY PROPERTIES INTO MAIN ENVIRONMENT SERVICE
123 > //
124 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
125 >
126 > // --- CLI Arguments
127 > args: NativeParsedArgs;
128 >
129 > // --- data paths
130 > /**
131 > * Root path of the JavaScript sources.
132 > *
133 > * Note: This is NOT the installation root
134 > * directory itself but contained in it at
135 > * a level that is platform dependent.
136 > */
137 > appRoot: string;
138 > userHome: URI;
139 > appSettingsHome: URI;
140 > tmpDir: URI;
141 > userDataPath: string;
142 >
143 > // --- extensions
144 > extensionsPath: string;
145 > extensionsDownloadLocation: URI;
146 > builtinExtensionsPath: string;
147 >
148 > // --- use in-memory Secret Storage
149 > useInMemorySecretStorage?: boolean;
150 >
151 > crossOriginIsolated?: boolean;
152 > exportPolicyData?: string;
153 > exportDefaultKeybindings?: string;
154 >
155 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
156 > //
157 > // NOTE: KEEP THIS INTERFACE AS SMALL AS POSSIBLE.
158 > //
159 > // AS SUCH:
160 > // - PUT NON-WEB PROPERTIES INTO NATIVE ENVIRONMENT SERVICE
161 > // - PUT WORKBENCH ONLY PROPERTIES INTO WORKBENCH ENVIRONMENT SERVICE
162 > // - PUT ELECTRON-MAIN ONLY PROPERTIES INTO MAIN ENVIRONMENT SERVICE
163 > //
164 > // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
165 > }
src/vs/base/common/policy.ts 161 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- policy.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { localize } from '../../nls.js';
7 > import { IPolicyData } from './defaultAccount.js';
8 >
9 > /**
10 > * System-wide policy file path for Linux systems.
11 > */
12 > export const LINUX_SYSTEM_POLICY_FILE_PATH = '/etc/vscode/policy.json';
13 >
14 > export type PolicyName = string;
15 > export type LocalizedValue = {
16 > key: string;
17 > value: string;
18 > };
19 >
20 > export type PolicyValue = string | number | boolean;
21 > export type ManagedSettingValue = PolicyValue;
22 > export type ManagedSettingsData = Readonly<Record<string, ManagedSettingValue>>;
23 >
24 > export interface IManagedSettingPolicyDefinition {
25 > readonly type: 'string' | 'number' | 'boolean';
26 > }
27 >
28 > export type IManagedSettingsPolicyDefinitions = Readonly<Record<string, IManagedSettingPolicyDefinition>>;
29 >
30 > export enum PolicyCategory {
31 > Extensions = 'Extensions',
32 > IntegratedTerminal = 'IntegratedTerminal',
33 > InteractiveSession = 'InteractiveSession',
34 > Telemetry = 'Telemetry',
35 > Update = 'Update',
36 > }
37 >
38 > export const PolicyCategoryData: {
39 > [key in PolicyCategory]: { name: LocalizedValue }
40 > } = {
41 > [PolicyCategory.Extensions]: {
42 > name: {
43 > key: 'extensionsConfigurationTitle', value: localize('extensionsConfigurationTitle', "Extensions"),
44 > }
45 > },
46 > [PolicyCategory.IntegratedTerminal]: {
47 > name: {
48 > key: 'terminalIntegratedConfigurationTitle', value: localize('terminalIntegratedConfigurationTitle', "Integrated Terminal"),
49 > }
50 > },
51 > [PolicyCategory.InteractiveSession]: {
52 > name: {
53 > key: 'interactiveSessionConfigurationTitle', value: localize('interactiveSessionConfigurationTitle', "Chat"),
54 > }
55 > },
56 > [PolicyCategory.Telemetry]: {
57 > name: {
58 > key: 'telemetryConfigurationTitle', value: localize('telemetryConfigurationTitle', "Telemetry"),
59 > }
60 > },
61 > [PolicyCategory.Update]: {
62 > name: {
63 > key: 'updateConfigurationTitle', value: localize('updateConfigurationTitle', "Update"),
64 > }
65 > }
66 > };
67 >
68 > export interface IPolicy {
69 >
70 > /**
71 > * The policy name.
72 > */
73 > readonly name: PolicyName;
74 >
75 > /**
76 > * The policy category.
77 > */
78 > readonly category: PolicyCategory;
79 >
80 > /**
81 > * The Code version in which this policy was introduced.
82 > */
83 > readonly minimumVersion: `${number}.${number}`;
84 >
85 > /**
86 > * Localization info for the policy.
87 > *
88 > * IMPORTANT: the key values for these must be unique to avoid collisions, as during the export time the module information is not available.
89 > */
90 > readonly localization: {
91 > /** The localization key or key value pair. If only a key is provided, the default value will fallback to the parent configuration's description property. */
92 > description: LocalizedValue;
93 > /** List of localization key or key value pair. If only a key is provided, the default value will fallback to the parent configuration's enumDescriptions property. */
94 > enumDescriptions?: LocalizedValue[];
95 > };
96 >
97 > /**
98 > * The value that an ACCOUNT-based feature will use when its corresponding policy is active.
99 > *
100 > * Only applicable when policy is tagged with ACCOUNT. When an account-based feature's policy is enabled,
101 > * this value determines what value the feature receives.
102 > *
103 > * For example:
104 > * - If evaluated value is `true`, the feature's setting is locked to `true` WHEN the policy is in effect.
105 > * - If evaluated value is `foo`, the feature's setting is locked to 'foo' WHEN the policy is in effect.
106 > *
107 > * If `undefined`, the feature's setting is not locked and can be overridden by other means.
108 > */
109 > readonly value?: (policyData: IPolicyData) => string | number | boolean | undefined;
110 >
111 > /**
112 > * Declares Copilot managed-settings keys this policy's value callback reads.
113 > * Keys are dot-separated managed-settings paths, for example
114 > * `permissions.disableBypassPermissionsMode`.
115 > */
116 > readonly managedSettings?: IManagedSettingsPolicyDefinitions;
117 >
118 > /**
119 > * The most-restrictive value that should be applied when the user is subject to the
120 > * "Require Approved Account" gate but the gate is not yet satisfied (i.e. no approved
121 > * GitHub account is signed in or the account-side policy data has not yet resolved).
122 > *
123 > * If omitted, the gate falls back to a type-driven safe default
124 > * (`false` for boolean, `0` for number, `''` for string).
125 > *
126 > * Only consulted while the gate is active and unsatisfied; ignored otherwise.
127 > */
128 > readonly restrictedValue?: string | number | boolean;
129 > }
130 >
131 > /**
132 > * A subordinate attachment to an existing {@link IPolicy} (the "owner"). A setting may declare a
133 > * `policyReference` instead of a full `policy` to be governed by a policy owned by another setting,
134 > * letting a single enterprise policy lock more than one setting (e.g. gating an agent in both the
135 > * editor window and the Agents window).
136 > *
137 > * A reference is a pure pointer: it carries no policy semantics of its own. The owner is the single
138 > * source of truth for the policy's catalog metadata *and* its runtime behaviour (type, value
139 > * callback, etc.); a reference only contributes the policy name so the setting is gated and the OS
140 > * policy watcher observes the name in processes where the owner is not loaded.
141 > */
142 > export interface IPolicyReference {
143 >
144 > /** The name of the owning {@link IPolicy} this setting attaches to. */
145 > readonly name: PolicyName;
146 > }
147 >
148 > /**
149 > * A `product.json` `extensionConfigurationPolicy` entry that attaches its setting to a policy
150 > * *owned* by an in-code setting, instead of declaring a full owner {@link IPolicy}. This mirrors the
151 > * in-code `policyReference` configuration field, so the same indirection can be expressed from
152 > * `product.json` — where the owner's runtime behaviour (notably its `value` callback) cannot live.
153 > *
154 > * An `extensionConfigurationPolicy` entry is therefore either a full {@link IPolicy} (the setting
155 > * "parents"/owns the policy, the current syntax) or this reference wrapper.
156 > */
157 > export interface IExtensionConfigurationPolicyReference {
158 >
159 > /** Pointer to the owning {@link IPolicy} declared by an in-code setting. */
160 > readonly policyReference: IPolicyReference;
161 > }
src/vs/platform/configuration/common/configurationService.ts 154 covered LOC · 26 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- configurationService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { distinct, equals as arrayEquals } from '../../../base/common/arrays.js';
7 > import { Queue, RunOnceScheduler } from '../../../base/common/async.js';
8 > import { VSBuffer } from '../../../base/common/buffer.js';
9 > import { Emitter, Event } from '../../../base/common/event.js';
10 > import { JSONPath, ParseError, parse } from '../../../base/common/json.js';
11 > import { applyEdits, setProperty } from '../../../base/common/jsonEdit.js';
12 > import { Edit, FormattingOptions } from '../../../base/common/jsonFormatter.js';
13 > import { Disposable, IDisposable } from '../../../base/common/lifecycle.js';
14 > import { ResourceMap } from '../../../base/common/map.js';
15 > import { equals } from '../../../base/common/objects.js';
16 > import { OS, OperatingSystem } from '../../../base/common/platform.js';
17 > import { extUriBiasedIgnorePathCase } from '../../../base/common/resources.js';
18 > import { URI } from '../../../base/common/uri.js';
19 > import { ConfigurationTarget, IConfigurationChange, IConfigurationChangeEvent, IConfigurationData, IConfigurationOverrides, IConfigurationService, IConfigurationUpdateOptions, IConfigurationUpdateOverrides, IConfigurationValue, isConfigurationOverrides, isConfigurationUpdateOverrides } from './configuration.js';
20 > import { Configuration, ConfigurationChangeEvent, ConfigurationModel, UserSettings } from './configurationModels.js';
21 > import { keyFromOverrideIdentifiers } from './configurationRegistry.js';
22 > import { DefaultConfiguration, IPolicyConfiguration, NullPolicyConfiguration, PolicyConfiguration } from './configurations.js';
23 > import { FileOperationError, FileOperationResult, IFileService } from '../../files/common/files.js';
24 > import { ILogService } from '../../log/common/log.js';
25 > import { IPolicyService, NullPolicyService } from '../../policy/common/policy.js';
26 >
27 > export class ConfigurationService extends Disposable implements IConfigurationService, IDisposable {
28 >
29 > declare readonly _serviceBrand: undefined;
30 >
31 > private configuration: Configuration;
32 > private readonly defaultConfiguration: DefaultConfiguration;
33 > private readonly policyConfiguration: IPolicyConfiguration;
34 > private readonly userConfiguration: UserSettings;
35 > private readonly reloadConfigurationScheduler: RunOnceScheduler;
36 >
37 > private readonly _onDidChangeConfiguration: Emitter<IConfigurationChangeEvent> = this._register(new Emitter<IConfigurationChangeEvent>());
38 > readonly onDidChangeConfiguration: Event<IConfigurationChangeEvent> = this._onDidChangeConfiguration.event;
39 >
40 > private readonly configurationEditing: ConfigurationEditing;
41 >
42 > constructor(
43 > private readonly settingsResource: URI, configurationService.ts
44 > fileService: IFileService,
45 > policyService: IPolicyService,
46 > private readonly logService: ILogService,
47 > ) {
48 > super();
49 > this.defaultConfiguration = this._register(new DefaultConfiguration(logService));
50 > this.policyConfiguration = policyService instanceof NullPolicyService ? new NullPolicyConfiguration() : this._register(new PolicyConfiguration(this.defaultConfiguration, policyService, logService));
51 > this.userConfiguration = this._register(new UserSettings(this.settingsResource, {}, extUriBiasedIgnorePathCase, fileService, logService));
52 > this.configuration = new Configuration(
53 > this.defaultConfiguration.configurationModel,
54 > this.policyConfiguration.configurationModel,
55 > ConfigurationModel.createEmptyModel(logService),
56 > ConfigurationModel.createEmptyModel(logService),
57 > ConfigurationModel.createEmptyModel(logService),
58 > ConfigurationModel.createEmptyModel(logService),
59 > new ResourceMap<ConfigurationModel>(),
60 > ConfigurationModel.createEmptyModel(logService),
61 > new ResourceMap<ConfigurationModel>(),
62 > logService
63 > );
64 > this.configurationEditing = new ConfigurationEditing(settingsResource, fileService, this);
65 >
66 > this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.reloadConfiguration(), 50));
67 > this._register(this.defaultConfiguration.onDidChangeConfiguration(({ defaults, properties }) => this.onDidDefaultConfigurationChange(defaults, properties)));
68 > this._register(this.policyConfiguration.onDidChangeConfiguration(model => this.onDidPolicyConfigurationChange(model)));
69 > this._register(this.userConfiguration.onDidChange(() => this.reloadConfigurationScheduler.schedule()));
70 > }
72 > async initialize(): Promise<void> {
73 > const [defaultModel, policyModel, userModel] = await Promise.all([this.defaultConfiguration.initialize(), this.policyConfiguration.initialize(), this.userConfiguration.loadConfiguration()]); configurationService.ts
74 > this.configuration = new Configuration(
75 > defaultModel,
76 > policyModel,
77 > ConfigurationModel.createEmptyModel(this.logService),
78 > userModel,
79 > ConfigurationModel.createEmptyModel(this.logService),
80 > ConfigurationModel.createEmptyModel(this.logService),
81 > new ResourceMap<ConfigurationModel>(),
82 > ConfigurationModel.createEmptyModel(this.logService),
83 > new ResourceMap<ConfigurationModel>(),
84 > this.logService
85 > );
86 > }
88 > getConfigurationData(): IConfigurationData {
89 return this.configuration.toData();
90 }
92 > getValue<T>(): T;
93 > getValue<T>(section: string): T;
94 > getValue<T>(overrides: IConfigurationOverrides): T;
95 > getValue<T>(section: string, overrides: IConfigurationOverrides): T;
96 > getValue(arg1?: unknown, arg2?: unknown): unknown {
97 > const section = typeof arg1 === 'string' ? arg1 : undefined; configurationService.ts
98 > const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
99 > return this.configuration.getValue(section, overrides, undefined);
100 > }
102 > updateValue(key: string, value: unknown): Promise<void>;
103 > updateValue(key: string, value: unknown, overrides: IConfigurationOverrides | IConfigurationUpdateOverrides): Promise<void>;
104 > updateValue(key: string, value: unknown, target: ConfigurationTarget): Promise<void>;
105 > updateValue(key: string, value: unknown, overrides: IConfigurationOverrides | IConfigurationUpdateOverrides, target: ConfigurationTarget, options?: IConfigurationUpdateOptions): Promise<void>;
106 > async updateValue(key: string, value: unknown, arg3?: unknown, arg4?: unknown, options?: IConfigurationUpdateOptions): Promise<void> {
107 const overrides: IConfigurationUpdateOverrides | undefined = isConfigurationUpdateOverrides(arg3) ? arg3
108 : isConfigurationOverrides(arg3) ? { resource: arg3.resource, overrideIdentifiers: arg3.overrideIdentifier ? [arg3.overrideIdentifier] : undefined } : undefined;
143 await this.reloadConfiguration();
144 }
146 > inspect<T>(key: string, overrides: IConfigurationOverrides = {}): IConfigurationValue<T> {
147 > return this.configuration.inspect<T>(key, overrides, undefined); configurationService.ts
148 > }
150 > keys(): {
151 default: string[];
152 policy: string[];
157 return this.configuration.keys(undefined);
158 }
160 > async reloadConfiguration(): Promise<void> {
161 > const configurationModel = await this.userConfiguration.loadConfiguration(); configurationService.ts
162 > this.onDidChangeUserConfiguration(configurationModel);
163 > }
165 > private onDidChangeUserConfiguration(userConfigurationModel: ConfigurationModel): void {
166 > const previous = this.configuration.toData(); configurationService.ts
167 > const change = this.configuration.compareAndUpdateLocalUserConfiguration(userConfigurationModel);
168 > this.trigger(change, previous, ConfigurationTarget.USER);
169 > }
171 > private onDidDefaultConfigurationChange(defaultConfigurationModel: ConfigurationModel, properties: string[]): void {
172 const previous = this.configuration.toData();
173 const change = this.configuration.compareAndUpdateDefaultConfiguration(defaultConfigurationModel, properties);
174 this.trigger(change, previous, ConfigurationTarget.DEFAULT);
175 }
177 > private onDidPolicyConfigurationChange(policyConfiguration: ConfigurationModel): void {
178 const previous = this.configuration.toData();
179 const change = this.configuration.compareAndUpdatePolicyConfiguration(policyConfiguration);
180 this.trigger(change, previous, ConfigurationTarget.DEFAULT);
181 }
183 > private trigger(configurationChange: IConfigurationChange, previous: IConfigurationData, source: ConfigurationTarget): void {
184 > const event = new ConfigurationChangeEvent(configurationChange, { data: previous }, this.configuration, undefined, this.logService); configurationService.ts
185 > event.source = source;
186 > this._onDidChangeConfiguration.fire(event);
187 > }
189 >
190 > class ConfigurationEditing {
191 >
192 > private readonly queue: Queue<void>;
193 >
194 > constructor(
195 > private readonly settingsResource: URI, configurationService.ts
196 > private readonly fileService: IFileService,
197 > private readonly configurationService: IConfigurationService,
198 > ) {
199 > this.queue = new Queue<void>();
200 > }
202 > write(path: JSONPath, value: unknown): Promise<void> {
203 return this.queue.queue(() => this.doWriteConfiguration(path, value)); // queue up writes to prevent race conditions
204 }
206 > private async doWriteConfiguration(path: JSONPath, value: unknown): Promise<void> {
207 let content: string;
208 try {
228 await this.fileService.writeFile(this.settingsResource, VSBuffer.fromString(content));
229 }
231 > private getEdits(content: string, path: JSONPath, value: unknown): Edit[] {
232 const { tabSize, insertSpaces, eol } = this.formattingOptions;
233
244 return setProperty(content, path, value, { tabSize, insertSpaces, eol });
245 }
247 > private _formattingOptions: Required<FormattingOptions> | undefined;
248 > private get formattingOptions(): Required<FormattingOptions> {
249 if (!this._formattingOptions) {
250 let eol = OS === OperatingSystem.Linux || OS === OperatingSystem.Macintosh ? '\n' : '\r\n';
src/vs/platform/storage/common/storageIpc.ts 150 covered LOC · 22 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- storageIpc.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { Disposable } from '../../../base/common/lifecycle.js';
8 > import { UriDto } from '../../../base/common/uri.js';
9 > import { IChannel } from '../../../base/parts/ipc/common/ipc.js';
10 > import { IStorageDatabase, IStorageItemsChangeEvent, IUpdateRequest } from '../../../base/parts/storage/common/storage.js';
11 > import { IUserDataProfile } from '../../userDataProfile/common/userDataProfile.js';
12 > import { ISerializedSingleFolderWorkspaceIdentifier, ISerializedWorkspaceIdentifier, IEmptyWorkspaceIdentifier, IAnyWorkspaceIdentifier } from '../../workspace/common/workspace.js';
13 >
14 > export type Key = string;
15 > export type Value = string;
16 > export type Item = [Key, Value];
17 >
18 > export interface IBaseSerializableStorageRequest {
19 >
20 > /**
21 > * Profile to correlate storage. Only used when no
22 > * workspace is provided. Can be undefined to denote
23 > * application scope.
24 > */
25 > readonly profile: UriDto<IUserDataProfile> | undefined;
26 >
27 > /**
28 > * Workspace to correlate storage. Can be undefined to
29 > * denote application or profile scope depending on profile.
30 > */
31 > readonly workspace: ISerializedWorkspaceIdentifier | ISerializedSingleFolderWorkspaceIdentifier | IEmptyWorkspaceIdentifier | undefined;
32 >
33 > /**
34 > * Whether this request targets the application shared storage
35 > * that is shared across VS Code and Sessions app.
36 > */
37 > readonly applicationShared?: boolean;
38 >
39 > /**
40 > * Additional payload for the request to perform.
41 > */
42 > readonly payload?: unknown;
43 > }
44 >
45 > export interface ISerializableUpdateRequest extends IBaseSerializableStorageRequest {
46 > insert?: Item[];
47 > delete?: Key[];
48 > }
49 >
50 > export interface ISerializableGetValueRequest extends IBaseSerializableStorageRequest {
51 > readonly key: Key;
52 > }
53 >
54 > export interface ISerializableCompareAndSwapRequest extends ISerializableGetValueRequest {
55 > readonly expectedValue: Value | undefined;
56 > readonly newValue: Value;
57 > }
58 >
59 > export interface ISerializableCompareAndSwapResult {
60 > readonly swapped: boolean;
61 > readonly currentValue: Value | undefined;
62 > }
63 >
64 > export interface ISerializableItemsChangeEvent {
65 > readonly changed?: Item[];
66 > readonly deleted?: Key[];
67 > }
68 >
69 > abstract class BaseStorageDatabaseClient extends Disposable implements IStorageDatabase {
70 >
71 > abstract readonly onDidChangeItemsExternal: Event<IStorageItemsChangeEvent>;
72 >
73 > protected get applicationShared(): boolean {
74 > return false;
75 > }
76 >
77 > constructor(
78 protected channel: IChannel,
79 protected profile: UriDto<IUserDataProfile> | undefined,
82 super();
83 }
85 > async getItems(): Promise<Map<string, string>> {
86 const serializableRequest: IBaseSerializableStorageRequest = { profile: this.profile, workspace: this.workspace, applicationShared: this.applicationShared };
87 const items: Item[] = await this.channel.call('getItems', serializableRequest);
89 return new Map(items);
90 }
92 > updateItems(request: IUpdateRequest): Promise<void> {
93 const serializableRequest: ISerializableUpdateRequest = { profile: this.profile, workspace: this.workspace, applicationShared: this.applicationShared };
94
103 return this.channel.call('updateItems', serializableRequest);
104 }
106 > optimize(): Promise<void> {
107 const serializableRequest: IBaseSerializableStorageRequest = { profile: this.profile, workspace: this.workspace, applicationShared: this.applicationShared };
108
109 return this.channel.call('optimize', serializableRequest);
110 }
112 > abstract close(): Promise<void>;
113 > }
114 >
115 > abstract class BaseProfileAwareStorageDatabaseClient extends BaseStorageDatabaseClient {
116 >
117 > private readonly _onDidChangeItemsExternal = this._register(new Emitter<IStorageItemsChangeEvent>());
118 > readonly onDidChangeItemsExternal = this._onDidChangeItemsExternal.event;
119 >
120 > constructor(channel: IChannel, profile: UriDto<IUserDataProfile> | undefined) {
121 super(channel, profile, undefined);
122
123 this.registerListeners();
124 }
126 > private registerListeners(): void {
127 this._register(this.channel.listen<ISerializableItemsChangeEvent>('onDidChangeStorage', { profile: this.profile, applicationShared: this.applicationShared })((e: ISerializableItemsChangeEvent) => this.onDidChangeStorage(e)));
128 }
130 > private onDidChangeStorage(e: ISerializableItemsChangeEvent): void {
131 if (Array.isArray(e.changed) || Array.isArray(e.deleted)) {
132 this._onDidChangeItemsExternal.fire({
136 }
137 }
138 > } storageIpc.ts
139 >
140 > export class ApplicationStorageDatabaseClient extends BaseProfileAwareStorageDatabaseClient {
141 >
142 > constructor(channel: IChannel) {
143 super(channel, undefined);
144 }
146 > async close(): Promise<void> {
147
148 // The application storage database is shared across all instances so
152 this.dispose();
153 }
154 > } storageIpc.ts
155 >
156 > export class ApplicationSharedStorageDatabaseClient extends BaseProfileAwareStorageDatabaseClient {
157 >
158 > constructor(channel: IChannel) {
159 super(channel, undefined);
160 }
162 > protected override get applicationShared(): boolean {
163 return true;
164 }
166 > async close(): Promise<void> {
167
168 // The application shared storage database is shared across all instances so
172 this.dispose();
173 }
174 > } storageIpc.ts
175 >
176 > export class ProfileStorageDatabaseClient extends BaseProfileAwareStorageDatabaseClient {
177 >
178 > async close(): Promise<void> {
179
180 // The profile storage database is shared across all instances of
185 this.dispose();
186 }
187 > } storageIpc.ts
188 >
189 > export class WorkspaceStorageDatabaseClient extends BaseStorageDatabaseClient implements IStorageDatabase {
190 >
191 > readonly onDidChangeItemsExternal = Event.None; // unsupported for workspace storage because we only ever write from one window
192 >
193 > constructor(channel: IChannel, workspace: IAnyWorkspaceIdentifier) {
194 super(channel, undefined, workspace);
195 }
197 > async close(): Promise<void> {
198
199 // The workspace storage database is only used in this instance
203 this.dispose();
204 }
205 > } storageIpc.ts
206 >
207 > export class StorageClient {
208 >
209 > constructor(private readonly channel: IChannel) { }
210 >
211 > isUsed(path: string): Promise<boolean> {
212 const serializableRequest: ISerializableUpdateRequest = { payload: path, profile: undefined, workspace: undefined };
213
214 return this.channel.call('isUsed', serializableRequest);
215 }
216 > } storageIpc.ts
217 >
218 > export class FallbackApplicationStorageDatabaseClient extends Disposable implements IStorageDatabase {
219 >
220 > onDidChangeItemsExternal = Event.None;
221 >
222 > constructor(private readonly channel: IChannel) {
223 super();
224 }
226 > async getItems(): Promise<Map<string, string>> {
227 const serializableRequest: IBaseSerializableStorageRequest = { profile: undefined, workspace: undefined, applicationShared: true };
228 const items: Item[] = await this.channel.call('getFallbackApplicationStorageItems', serializableRequest);
229 return new Map(items);
230 }
232 > updateItems(): Promise<void> {
233 throw new Error('Not supported');
234 }
236 > optimize(): Promise<void> {
237 throw new Error('Not supported');
238 }
240 > close(): Promise<void> {
241 throw new Error('Not supported');
242 }
243 > } storageIpc.ts
src/vs/platform/userDataSync/common/userDataProfilesManifestSync.ts 145 covered LOC · 28 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataProfilesManifestSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken } from '../../../base/common/cancellation.js';
7 > import { toFormattedString } from '../../../base/common/jsonFormatter.js';
8 > import { URI } from '../../../base/common/uri.js';
9 > import { IConfigurationService } from '../../configuration/common/configuration.js';
10 > import { IEnvironmentService } from '../../environment/common/environment.js';
11 > import { IFileService } from '../../files/common/files.js';
12 > import { IStorageService } from '../../storage/common/storage.js';
13 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
14 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
15 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
16 > import { AbstractSynchroniser, IAcceptResult, IMergeResult, IResourcePreview } from './abstractSynchronizer.js';
17 > import { merge } from './userDataProfilesManifestMerge.js';
18 > import { Change, IRemoteUserData, ISyncData, ISyncUserDataProfile, IUserData, IUserDataSyncEnablementService, IUserDataSynchroniser, IUserDataSyncLocalStoreService, IUserDataSyncLogService, IUserDataSyncStoreService, SyncResource, USER_DATA_SYNC_SCHEME, UserDataSyncError, UserDataSyncErrorCode } from './userDataSync.js';
19 >
20 > interface IUserDataProfileManifestResourceMergeResult extends IAcceptResult {
21 > readonly local: { added: ISyncUserDataProfile[]; removed: IUserDataProfile[]; updated: ISyncUserDataProfile[] };
22 > readonly remote: { added: IUserDataProfile[]; removed: ISyncUserDataProfile[]; updated: IUserDataProfile[] } | null;
23 > }
24 >
25 > interface IUserDataProfilesManifestResourcePreview extends IResourcePreview {
26 > readonly previewResult: IUserDataProfileManifestResourceMergeResult;
27 > readonly remoteProfiles: ISyncUserDataProfile[] | null;
28 > }
29 >
30 > export class UserDataProfilesManifestSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {
31 >
32 > protected readonly version: number = 2;
33 > readonly previewResource: URI = this.extUri.joinPath(this.syncPreviewFolder, 'profiles.json');
34 > readonly baseResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'base' });
35 > readonly localResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' });
36 > readonly remoteResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' });
37 > readonly acceptedResource: URI = this.previewResource.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' });
38 >
39 > constructor(
40 > profile: IUserDataProfile, userDataProfilesManifestSync.ts
41 > collection: string | undefined,
42 > @IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService,
43 > @IFileService fileService: IFileService,
44 > @IEnvironmentService environmentService: IEnvironmentService,
45 > @IStorageService storageService: IStorageService,
46 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
47 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
48 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
49 > @IConfigurationService configurationService: IConfigurationService,
50 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
51 > @ITelemetryService telemetryService: ITelemetryService,
52 > @IUriIdentityService uriIdentityService: IUriIdentityService,
53 > ) {
54 > super({ syncResource: SyncResource.Profiles, profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
55 > this._register(userDataProfilesService.onDidChangeProfiles(() => this.triggerLocalChange()));
56 > }
58 > async getLastSyncedProfiles(): Promise<ISyncUserDataProfile[] | null> {
59 > const lastSyncUserData = await this.getLastSyncUserData(); userDataProfilesManifestSync.ts
60 > return lastSyncUserData?.syncData ? parseUserDataProfilesManifest(lastSyncUserData.syncData) : null;
61 > }
63 > async getRemoteSyncedProfiles(refOrLatestData: string | IUserData | null): Promise<ISyncUserDataProfile[] | null> {
64 const lastSyncUserData = await this.getLastSyncUserData();
65 const remoteUserData = await this.getLatestRemoteUserData(refOrLatestData, lastSyncUserData);
66 return remoteUserData?.syncData ? parseUserDataProfilesManifest(remoteUserData.syncData) : null;
67 }
69 > protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<IUserDataProfilesManifestResourcePreview[]> {
70 > const remoteProfiles: ISyncUserDataProfile[] | null = remoteUserData.syncData ? parseUserDataProfilesManifest(remoteUserData.syncData) : null; userDataProfilesManifestSync.ts
71 > const lastSyncProfiles: ISyncUserDataProfile[] | null = lastSyncUserData?.syncData ? parseUserDataProfilesManifest(lastSyncUserData.syncData) : null;
72 > const localProfiles = this.getLocalUserDataProfiles();
73 >
74 > const { local, remote } = merge(localProfiles, remoteProfiles, lastSyncProfiles, []);
75 > const previewResult: IUserDataProfileManifestResourceMergeResult = {
76 > local, remote,
77 > content: lastSyncProfiles ? this.stringifyRemoteProfiles(lastSyncProfiles) : null,
78 > localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? Change.Modified : Change.None,
79 > remoteChange: remote !== null ? Change.Modified : Change.None,
80 > };
81 >
82 > const localContent = stringifyLocalProfiles(localProfiles, false);
83 > return [{
84 > baseResource: this.baseResource,
85 > baseContent: lastSyncProfiles ? this.stringifyRemoteProfiles(lastSyncProfiles) : null,
86 > localResource: this.localResource,
87 > localContent,
88 > remoteResource: this.remoteResource,
89 > remoteContent: remoteProfiles ? this.stringifyRemoteProfiles(remoteProfiles) : null,
90 > remoteProfiles,
91 > previewResource: this.previewResource,
92 > previewResult,
93 > localChange: previewResult.localChange,
94 > remoteChange: previewResult.remoteChange,
95 > acceptedResource: this.acceptedResource
96 > }];
97 > }
99 > protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> {
100 const lastSyncProfiles: ISyncUserDataProfile[] | null = lastSyncUserData?.syncData ? parseUserDataProfilesManifest(lastSyncUserData.syncData) : null;
101 const localProfiles = this.getLocalUserDataProfiles();
103 return !!remote?.added.length || !!remote?.removed.length || !!remote?.updated.length;
104 }
106 > protected async getMergeResult(resourcePreview: IUserDataProfilesManifestResourcePreview, token: CancellationToken): Promise<IMergeResult> {
107 return { ...resourcePreview.previewResult, hasConflicts: false };
108 }
110 > protected async getAcceptResult(resourcePreview: IUserDataProfilesManifestResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> {
111 /* Accept local resource */
112 if (this.extUri.isEqual(resource, this.localResource)) {
126 throw new Error(`Invalid Resource: ${resource.toString()}`);
127 }
129 > private async acceptLocal(resourcePreview: IUserDataProfilesManifestResourcePreview): Promise<IUserDataProfileManifestResourceMergeResult> {
130 const localProfiles = this.getLocalUserDataProfiles();
131 const mergeResult = merge(localProfiles, null, null, []);
139 };
140 }
142 > private async acceptRemote(resourcePreview: IUserDataProfilesManifestResourcePreview): Promise<IUserDataProfileManifestResourceMergeResult> {
143 const remoteProfiles: ISyncUserDataProfile[] = resourcePreview.remoteContent ? JSON.parse(resourcePreview.remoteContent) : null;
144 const lastSyncProfiles: ISyncUserDataProfile[] = [];
171 }
172 }
174 > protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [IUserDataProfilesManifestResourcePreview, IUserDataProfileManifestResourceMergeResult][], force: boolean): Promise<void> {
175 > const { local, remote, localChange, remoteChange } = resourcePreviews[0][1]; userDataProfilesManifestSync.ts
176 > if (localChange === Change.None && remoteChange === Change.None) {
177 > this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing profiles.`); userDataProfilesManifestSync.ts
178 > }
180 > const remoteProfiles = resourcePreviews[0][0].remoteProfiles || [];
181 > if (remoteProfiles.length + (remote?.added.length ?? 0) - (remote?.removed.length ?? 0) > 20) {
182 throw new UserDataSyncError('Too many profiles to sync. Please remove some profiles and try again.', UserDataSyncErrorCode.LocalTooManyProfiles);
183 }
185 > if (localChange !== Change.None) {
186 await this.backupLocal(stringifyLocalProfiles(this.getLocalUserDataProfiles(), false));
187 await Promise.all(local.removed.map(async profile => {
206 }));
207 }
209 > if (remoteChange !== Change.None) {
210 this.logService.trace(`${this.syncResourceLogLabel}: Updating remote profiles...`);
211 const addedCollections: string[] = [];
248 }
249 }
251 > if (lastSyncUserData?.ref !== remoteUserData.ref) {
252 > // update last sync
253 > this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized profiles...`);
254 > await this.updateLastSyncUserData(remoteUserData);
255 > this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized profiles.`);
256 > }
257 > }
259 > async updateRemoteProfiles(profiles: ISyncUserDataProfile[], ref: string | null): Promise<IRemoteUserData> {
260 return this.updateRemoteUserData(this.stringifyRemoteProfiles(profiles), ref);
261 }
263 > async hasLocalData(): Promise<boolean> {
264 return this.getLocalUserDataProfiles().length > 0;
265 }
267 > async resolveContent(uri: URI): Promise<string | null> {
268 if (this.extUri.isEqual(this.remoteResource, uri)
269 || this.extUri.isEqual(this.baseResource, uri)
276 return null;
277 }
279 > private getLocalUserDataProfiles(): IUserDataProfile[] {
280 > return this.userDataProfilesService.profiles.filter(p => !p.isDefault && !p.isTransient); userDataProfilesManifestSync.ts
281 > }
283 > private stringifyRemoteProfiles(profiles: ISyncUserDataProfile[]): string {
284 return JSON.stringify([...profiles].sort((a, b) => a.name.localeCompare(b.name)));
285 }
287 > }
288 >
289 > export function stringifyLocalProfiles(profiles: IUserDataProfile[], format: boolean): string {
290 > const result = [...profiles].sort((a, b) => a.name.localeCompare(b.name)).map(p => ({ id: p.id, name: p.name })); userDataProfilesManifestSync.ts
291 > return format ? toFormattedString(result, {}) : JSON.stringify(result);
292 > }
294 > export function parseUserDataProfilesManifest(syncData: ISyncData): ISyncUserDataProfile[] {
295 return JSON.parse(syncData.content);
296 }
src/vs/base/common/cancellation.ts 137 covered LOC · 41 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- cancellation.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from './event.js';
7 > import { DisposableStore, IDisposable } from './lifecycle.js';
8 >
9 > export interface CancellationToken {
10 >
11 > /**
12 > * A flag signalling is cancellation has been requested.
13 > */
14 > readonly isCancellationRequested: boolean;
15 >
16 > /**
17 > * An event which fires when cancellation is requested. This event
18 > * only ever fires `once` as cancellation can only happen once. Listeners
19 > * that are registered after cancellation will be called (next event loop run),
20 > * but also only once.
21 > *
22 > * @event
23 > */
24 > readonly onCancellationRequested: (listener: (e: void) => unknown, thisArgs?: unknown, disposables?: IDisposable[]) => IDisposable;
25 > }
26 >
27 > const shortcutEvent: Event<void> = Object.freeze(function (callback, context?): IDisposable {
28 const handle = setTimeout(callback.bind(context), 0);
29 return { dispose() { clearTimeout(handle); } };
30 });
32 > export namespace CancellationToken {
33 >
34 > export function isCancellationToken(thing: unknown): thing is CancellationToken {
35 if (thing === CancellationToken.None || thing === CancellationToken.Cancelled) {
36 return true;
45 && typeof (thing as CancellationToken).onCancellationRequested === 'function';
46 }
48 >
49 > export const None = Object.freeze<CancellationToken>({
50 > isCancellationRequested: false,
51 > onCancellationRequested: Event.None
52 > });
53 >
54 > export const Cancelled = Object.freeze<CancellationToken>({
55 > isCancellationRequested: true,
56 > onCancellationRequested: shortcutEvent
57 > });
58 > }
59 >
60 > class MutableToken implements CancellationToken { cancellation.ts
61 >
62 > private _isCancelled: boolean = false;
63 > private _emitter: Emitter<void> | null = null;
65 > public cancel() {
66 if (!this._isCancelled) {
67 this._isCancelled = true;
72 }
73 }
75 > get isCancellationRequested(): boolean {
76 > return this._isCancelled; cancellation.ts
77 > }
79 > get onCancellationRequested(): Event<void> {
80 > if (this._isCancelled) { cancellation.ts
81 return shortcutEvent;
82 }
83 > if (!this._emitter) { cancellation.ts
84 > this._emitter = new Emitter<void>();
85 > }
86 > return this._emitter.event;
89 > public dispose(): void {
90 > if (this._emitter) { cancellation.ts
91 > this._emitter.dispose(); cancellation.ts
92 > this._emitter = null;
93 > }
96 >
97 > export class CancellationTokenSource {
98 >
99 > private _token?: CancellationToken = undefined;
100 > private _parentListener?: IDisposable = undefined;
101 >
102 > constructor(parent?: CancellationToken) {
103 > this._parentListener = parent && parent.onCancellationRequested(this.cancel, this); cancellation.ts
104 > }
106 > get token(): CancellationToken {
107 > if (!this._token) { cancellation.ts
108 > // be lazy and create the token only when cancellation.ts
109 > // actually needed
110 > this._token = new MutableToken();
111 > }
112 > return this._token; cancellation.ts
113 > }
115 > cancel(): void {
116 > if (!this._token) { cancellation.ts
117 > // save an object by returning the default cancellation.ts
118 > // cancelled token when cancellation happens
119 > // before someone asks for the token
120 > this._token = CancellationToken.Cancelled;
121 >
122 > } else if (this._token instanceof MutableToken) { cancellation.ts
123 // actually cancel
124 this._token.cancel();
125 }
126 > } cancellation.ts
128 > dispose(cancel: boolean = false): void {
129 > if (cancel) { cancellation.ts
130 > this.cancel(); cancellation.ts
131 > }
132 > this._parentListener?.dispose(); cancellation.ts
133 > if (!this._token) {
134 > // ensure to initialize with an empty token if we had none cancellation.ts
135 > this._token = CancellationToken.None;
136 >
137 > } else if (this._token instanceof MutableToken) { cancellation.ts
138 > // actually dispose cancellation.ts
139 > this._token.dispose();
140 > }
141 > } cancellation.ts
142 > } cancellation.ts
143 >
144 > export function cancelOnDispose(store: DisposableStore): CancellationToken {
145 const source = new CancellationTokenSource();
146 store.add({ dispose() { source.cancel(); } });
147 return source.token;
148 }
150 > /**
151 > * A pool that aggregates multiple cancellation tokens. The pool's own token
152 > * (accessible via `pool.token`) is cancelled only after every token added
153 > * to the pool has been cancelled. Adding tokens after the pool token has
154 > * been cancelled has no effect.
155 > */
156 > export class CancellationTokenPool {
157
158 private readonly _source = new CancellationTokenSource();
162 private _cancelled: number = 0;
163 private _isDone: boolean = false;
165 > get token(): CancellationToken {
166 return this._source.token;
167 }
169 > /**
170 > * Add a token to the pool. If the token is already cancelled it is counted
171 > * immediately. Tokens added after the pool token has been cancelled are ignored.
172 > */
173 > add(token: CancellationToken): void {
174 if (this._isDone) {
175 return;
191 this._listeners.add(d);
192 }
194 > private _check(): void {
195 if (!this._isDone && this._total > 0 && this._total === this._cancelled) {
196 this._isDone = true;
src/vs/platform/userDataProfile/common/userDataProfileStorageService.ts 135 covered LOC · 23 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataProfileStorageService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Disposable, DisposableMap, MutableDisposable, isDisposable, toDisposable } from '../../../base/common/lifecycle.js';
7 > import { IStorage, IStorageDatabase, Storage } from '../../../base/parts/storage/common/storage.js';
8 > import { createDecorator } from '../../instantiation/common/instantiation.js';
9 > import { AbstractStorageService, IStorageService, IStorageValueChangeEvent, StorageScope, StorageTarget, isProfileUsingDefaultStorage } from '../../storage/common/storage.js';
10 > import { Emitter, Event } from '../../../base/common/event.js';
11 > import { IRemoteService } from '../../ipc/common/services.js';
12 > import { ILogService } from '../../log/common/log.js';
13 > import { ApplicationStorageDatabaseClient, ProfileStorageDatabaseClient } from '../../storage/common/storageIpc.js';
14 > import { IUserDataProfile, IUserDataProfilesService, reviveProfile } from './userDataProfile.js';
15 >
16 > export interface IProfileStorageValueChanges {
17 > readonly profile: IUserDataProfile;
18 > readonly changes: IStorageValueChangeEvent[];
19 > }
20 >
21 > export interface IProfileStorageChanges {
22 > readonly targetChanges: IUserDataProfile[];
23 > readonly valueChanges: IProfileStorageValueChanges[];
24 > }
25 >
26 > export interface IStorageValue {
27 > readonly value: string | undefined;
28 > readonly target: StorageTarget;
29 > readonly scope?: StorageScope;
30 > }
31 >
32 > export const IUserDataProfileStorageService = createDecorator<IUserDataProfileStorageService>('IUserDataProfileStorageService');
33 > export interface IUserDataProfileStorageService {
34 > readonly _serviceBrand: undefined;
35 >
36 > /**
37 > * Emitted whenever data is updated or deleted in a profile storage or target of a profile storage entry changes
38 > */
39 > readonly onDidChange: Event<IProfileStorageChanges>;
40 >
41 > /**
42 > * Return the requested profile storage data
43 > * @param profile The profile from which the data has to be read from
44 > */
45 > readStorageData(profile: IUserDataProfile): Promise<Map<string, IStorageValue>>;
46 >
47 > /**
48 > * Update the given profile storage data in the profile storage
49 > * @param profile The profile to which the data has to be written to
50 > * @param data Data that has to be updated
51 > * @param target Storage target of the data
52 > * @param scope Storage scope of the data (defaults to PROFILE)
53 > */
54 > updateStorageData(profile: IUserDataProfile, data: Map<string, string | undefined | null>, target: StorageTarget, scope?: StorageScope): Promise<void>;
55 >
56 > /**
57 > * Calls a function with a storage service scoped to given profile.
58 > */
59 > withProfileScopedStorageService<T>(profile: IUserDataProfile, fn: (storageService: IStorageService) => Promise<T>): Promise<T>;
60 > }
61 >
62 > export abstract class AbstractUserDataProfileStorageService extends Disposable implements IUserDataProfileStorageService {
63 >
64 > _serviceBrand: undefined;
65 >
66 > readonly abstract onDidChange: Event<IProfileStorageChanges>;
67 >
68 > private readonly storageServicesMap: DisposableMap<string, StorageService> | undefined;
69 >
70 > constructor(
71 > persistStorages: boolean, userDataProfileStorageService.ts
72 > @IStorageService protected readonly storageService: IStorageService
73 > ) {
74 > super();
75 > if (persistStorages) {
76 this.storageServicesMap = this._register(new DisposableMap<string, StorageService>());
77 }
80 > async readStorageData(profile: IUserDataProfile): Promise<Map<string, IStorageValue>> {
81 > return this.withProfileScopedStorageService(profile, async storageService => this.getItems(storageService, profile)); userDataProfileStorageService.ts
82 > }
84 > async updateStorageData(profile: IUserDataProfile, data: Map<string, string | undefined | null>, target: StorageTarget, scope = StorageScope.PROFILE): Promise<void> {
85 return this.withProfileScopedStorageService(profile, async storageService => this.writeItems(storageService, data, target, scope));
86 }
88 > async withProfileScopedStorageService<T>(profile: IUserDataProfile, fn: (storageService: IStorageService) => Promise<T>): Promise<T> {
89 > if (this.storageService.hasScope(profile)) { userDataProfileStorageService.ts
90 > return fn(this.storageService); userDataProfileStorageService.ts
91 > }
92
93 > let storageService = this.storageServicesMap?.get(profile.id); userDataProfileStorageService.ts
94 > if (!storageService) {
95 storageService = new StorageService(this.createStorageDatabase(profile));
96 this.storageServicesMap?.set(profile.id, storageService);
116 }
117 }
120 > private getItems(storageService: IStorageService, profile: IUserDataProfile): Map<string, IStorageValue> {
121 > const result = new Map<string, IStorageValue>(); userDataProfileStorageService.ts
122 > const populate = (scope: StorageScope, target: StorageTarget) => {
123 > for (const key of storageService.keys(scope, target)) {
124 result.set(key, { value: storageService.get(key, scope), target, scope });
125 }
127 > populate(StorageScope.PROFILE, StorageTarget.USER);
128 > populate(StorageScope.PROFILE, StorageTarget.MACHINE);
129 > if (profile.isDefault) {
130 > populate(StorageScope.APPLICATION_SHARED, StorageTarget.USER); userDataProfileStorageService.ts
131 > populate(StorageScope.APPLICATION_SHARED, StorageTarget.MACHINE);
132 > }
133 > return result; userDataProfileStorageService.ts
134 > }
136 > private writeItems(storageService: IStorageService, items: Map<string, string | undefined | null>, target: StorageTarget, scope = StorageScope.PROFILE): void {
137 storageService.storeAll(Array.from(items.entries()).map(([key, value]) => ({ key, value, scope, target })), true);
138 }
140 > protected abstract createStorageDatabase(profile: IUserDataProfile): Promise<IStorageDatabase>;
141 > }
142 >
143 > export class RemoteUserDataProfileStorageService extends AbstractUserDataProfileStorageService implements IUserDataProfileStorageService {
144 >
145 > private readonly _onDidChange: Emitter<IProfileStorageChanges>;
146 > readonly onDidChange: Event<IProfileStorageChanges>;
147 >
148 > constructor(
149 persistStorages: boolean,
150 private readonly remoteService: IRemoteService,
173 this.onDidChange = this._onDidChange.event;
174 }
176 > protected async createStorageDatabase(profile: IUserDataProfile): Promise<IStorageDatabase> {
177 const storageChannel = this.remoteService.getChannel('storage');
178 return isProfileUsingDefaultStorage(profile) ? new ApplicationStorageDatabaseClient(storageChannel) : new ProfileStorageDatabaseClient(storageChannel, profile);
179 }
181 >
182 > class StorageService extends AbstractStorageService {
183 >
184 > private profileStorage: IStorage | undefined;
185 >
186 > constructor(private readonly profileStorageDatabase: Promise<IStorageDatabase>) {
187 super({ flushInterval: 100 });
188 }
190 > protected async doInitialize(): Promise<void> {
191 const profileStorageDatabase = await this.profileStorageDatabase;
192 const profileStorage = new Storage(profileStorageDatabase);
204 return this.profileStorage.init();
205 }
207 > protected getStorage(scope: StorageScope): IStorage | undefined {
208 return scope === StorageScope.PROFILE ? this.profileStorage : undefined;
209 }
211 > protected getLogDetails(): string | undefined { return undefined; }
212 > protected async switchToProfile(): Promise<void> { }
213 > protected async switchToWorkspace(): Promise<void> { }
214 > hasScope() { return false; }
215 > }
src/vs/platform/userDataSync/common/settingsMerge.ts 130 covered LOC · 46 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- settingsMerge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { distinct } from '../../../base/common/arrays.js';
7 > import { IStringDictionary } from '../../../base/common/collections.js';
8 > import { JSONVisitor, parse, visit } from '../../../base/common/json.js';
9 > import { applyEdits, setProperty, withFormatting } from '../../../base/common/jsonEdit.js';
10 > import { Edit, FormattingOptions, getEOL } from '../../../base/common/jsonFormatter.js';
11 > import * as objects from '../../../base/common/objects.js';
12 > import { IConfigurationService } from '../../configuration/common/configuration.js';
13 > import * as contentUtil from './content.js';
14 > import { getDisallowedIgnoredSettings, IConflictSetting } from './userDataSync.js';
15 >
16 > export interface IMergeResult {
17 > localContent: string | null;
18 > remoteContent: string | null;
19 > hasConflicts: boolean;
20 > conflictsSettings: IConflictSetting[];
21 > }
22 >
23 > export function getIgnoredSettings(defaultIgnoredSettings: string[], configurationService: IConfigurationService, settingsContent?: string): string[] {
24 > let value: ReadonlyArray<string> = []; settingsMerge.ts
25 > if (settingsContent) {
26 > value = getIgnoredSettingsFromContent(settingsContent); settingsMerge.ts
27 > } else { settingsMerge.ts
28 > value = getIgnoredSettingsFromConfig(configurationService);
29 > }
30 > const added: string[] = [], removed: string[] = [...getDisallowedIgnoredSettings()];
31 > if (Array.isArray(value)) {
32 > for (const key of value) {
33 if (key.startsWith('-')) {
34 removed.push(key.substring(1));
37 }
38 }
40 > return distinct([...defaultIgnoredSettings, ...added,].filter(setting => !removed.includes(setting)));
41 > }
43 > function getIgnoredSettingsFromConfig(configurationService: IConfigurationService): ReadonlyArray<string> { settingsMerge.ts
44 > let userValue = configurationService.inspect<string[]>('settingsSync.ignoredSettings').userValue;
45 > if (userValue !== undefined) {
46 return userValue;
47 }
48 > userValue = configurationService.inspect<string[]>('sync.ignoredSettings').userValue; settingsMerge.ts
49 > if (userValue !== undefined) {
50 return userValue;
51 }
52 > return configurationService.getValue<string[]>('settingsSync.ignoredSettings') || []; settingsMerge.ts
55 > function getIgnoredSettingsFromContent(settingsContent: string): string[] { settingsMerge.ts
56 > const parsed = parse(settingsContent);
57 > return parsed ? parsed['settingsSync.ignoredSettings'] || parsed['sync.ignoredSettings'] || [] : [];
58 > }
60 > export function removeComments(content: string, formattingOptions: FormattingOptions): string {
61 const source = parse(content) || {};
62 let result = '{}';
67 return result;
68 }
70 > export function updateIgnoredSettings(targetContent: string, sourceContent: string, ignoredSettings: string[], formattingOptions: FormattingOptions): string {
71 > if (ignoredSettings.length) { settingsMerge.ts
72 > const sourceTree = parseSettings(sourceContent); settingsMerge.ts
73 > const source = parse(sourceContent) || {};
74 > const target = parse(targetContent);
75 > if (!target) {
76 return targetContent;
77 }
78 > const settingsToAdd: INode[] = []; settingsMerge.ts
79 > for (const key of ignoredSettings) {
80 > const sourceValue = source[key];
81 > const targetValue = target[key];
82 >
83 > // Remove in target
84 > if (sourceValue === undefined) {
85 > targetContent = contentUtil.edit(targetContent, [key], undefined, formattingOptions); settingsMerge.ts
86 > }
87
88 // Update in target
94 settingsToAdd.push(findSettingNode(key, sourceTree)!);
95 }
97 >
98 > settingsToAdd.sort((a, b) => a.startOffset - b.startOffset);
99 > settingsToAdd.forEach(s => targetContent = addSetting(s.setting!.key, sourceContent, targetContent, formattingOptions));
100 > }
101 > return targetContent; settingsMerge.ts
102 > }
104 > export function merge(originalLocalContent: string, originalRemoteContent: string, baseContent: string | null, ignoredSettings: string[], resolvedConflicts: { key: string; value: any | undefined }[], formattingOptions: FormattingOptions): IMergeResult {
105
106 const localContentWithoutIgnoredSettings = updateIgnoredSettings(originalLocalContent, originalRemoteContent, ignoredSettings, formattingOptions);
250 return { localContent: hasLocalChanged ? localContent : null, remoteContent: hasRemoteChanged ? remoteContent : null, conflictsSettings: [...conflicts.values()], hasConflicts };
251 }
253 function areSame(localContent: string, remoteContent: string, ignoredSettings: string[]): boolean {
254 if (localContent === remoteContent) {
287 return true;
288 }
290 > export function isEmpty(content: string): boolean {
291 if (content) {
292 const nodes = parseSettings(content);
295 return true;
296 }
298 function compare(from: IStringDictionary<any> | null, to: IStringDictionary<any>, ignored: Set<string>): { added: Set<string>; removed: Set<string>; updated: Set<string> } {
299 const fromKeys = from ? Object.keys(from).filter(key => !ignored.has(key)) : [];
318 return { added, removed, updated };
319 }
321 > export function addSetting(key: string, sourceContent: string, targetContent: string, formattingOptions: FormattingOptions): string {
322 const source = parse(sourceContent);
323 const sourceTree = parseSettings(sourceContent);
326 return insertAtLocation(targetContent, key, source[key], insertLocation, targetTree, formattingOptions);
327 }
329 > interface InsertLocation {
330 > index: number;
331 > insertAfter: boolean;
332 > }
333 >
334 function getInsertLocation(key: string, sourceTree: INode[], targetTree: INode[]): InsertLocation {
335
438 return { index: targetTree.length - 1, insertAfter: true };
439 }
441 function insertAtLocation(content: string, key: string, value: any, location: InsertLocation, tree: INode[], formattingOptions: FormattingOptions): string {
442 let edits: Edit[];
449 return applyEdits(content, edits);
450 }
452 function getEditToInsertAtLocation(content: string, key: string, value: any, location: InsertLocation, tree: INode[], formattingOptions: FormattingOptions): Edit[] {
453 const newProperty = `${JSON.stringify(key)}: ${JSON.stringify(value)}`;
504
505 }
507 function findSettingNode(key: string, tree: INode[]): INode | undefined {
508 return tree.filter(node => node.setting?.key === key)[0];
509 }
511 function findPreviousSettingNode(index: number, tree: INode[]): INode | undefined {
512 for (let i = index - 1; i >= 0; i--) {
517 return undefined;
518 }
520 function findNextSettingNode(index: number, tree: INode[]): INode | undefined {
521 for (let i = index + 1; i < tree.length; i++) {
526 return undefined;
527 }
529 function findNodesBetween(nodes: INode[], from: INode, till: INode): INode[] {
530 const fromIndex = nodes.indexOf(from);
532 return nodes.filter((node, index) => fromIndex < index && index < tillIndex);
533 }
535 function findLastMatchingTargetCommentNode(sourceComments: INode[], targetComments: INode[]): INode | undefined {
536 if (sourceComments.length && targetComments.length) {
545 return undefined;
546 }
548 > interface INode {
549 > readonly startOffset: number;
550 > readonly endOffset: number;
551 > readonly value: string;
552 > readonly setting?: {
553 > readonly key: string;
554 > readonly commaOffset: number | undefined;
555 > };
556 > readonly comment?: string;
557 > }
558 >
559 > function parseSettings(content: string): INode[] { settingsMerge.ts
560 > const nodes: INode[] = [];
561 > let hierarchyLevel = -1;
562 > let startOffset: number;
563 > let key: string;
564 >
565 > const visitor: JSONVisitor = {
566 > onObjectBegin: (offset: number) => {
567 > hierarchyLevel++; settingsMerge.ts
568 > },
569 > onObjectProperty: (name: string, offset: number, length: number) => { settingsMerge.ts
570 if (hierarchyLevel === 0) {
571 // this is setting key
574 }
575 },
576 > onObjectEnd: (offset: number, length: number) => { settingsMerge.ts
577 > hierarchyLevel--; settingsMerge.ts
578 > if (hierarchyLevel === 0) {
579 nodes.push({
580 startOffset,
587 });
588 }
589 > }, settingsMerge.ts
590 > onArrayBegin: (offset: number, length: number) => { settingsMerge.ts
591 hierarchyLevel++;
592 },
593 > onArrayEnd: (offset: number, length: number) => { settingsMerge.ts
594 hierarchyLevel--;
595 if (hierarchyLevel === 0) {
605 }
606 },
607 > onLiteralValue: (value: any, offset: number, length: number) => { settingsMerge.ts
608 if (hierarchyLevel === 0) {
609 nodes.push({
618 }
619 },
620 > onSeparator: (sep: string, offset: number, length: number) => { settingsMerge.ts
621 if (hierarchyLevel === 0) {
622 if (sep === ',') {
642 }
643 },
644 > onComment: (offset: number, length: number) => { settingsMerge.ts
645 if (hierarchyLevel === 0) {
646 nodes.push({
651 }
652 }
653 > }; settingsMerge.ts
654 > visit(content, visitor);
655 > return nodes;
656 > }
src/vs/platform/instantiation/test/common/instantiationServiceMock.ts 127 covered LOC · 36 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- instantiationServiceMock.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as sinon from 'sinon';
7 > import { DisposableStore, IDisposable, toDisposable } from '../../../../base/common/lifecycle.js';
8 > import { SyncDescriptor, SyncDescriptor0 } from '../../common/descriptors.js';
9 > import { GetLeadingNonServiceArgs, ServiceIdentifier, ServicesAccessor } from '../../common/instantiation.js';
10 > import { InstantiationService, Trace } from '../../common/instantiationService.js';
11 > import { ServiceCollection } from '../../common/serviceCollection.js';
12 >
13 > interface IServiceMock<T> {
14 > id: ServiceIdentifier<T>;
15 > service: any;
16 > }
17 >
18 > const isSinonSpyLike = (fn: Function): fn is sinon.SinonSpy => fn && 'callCount' in fn;
19 >
20 > export class TestInstantiationService extends InstantiationService implements IDisposable, ServicesAccessor {
21 >
22 > private _servciesMap: Map<ServiceIdentifier<any>, any>;
23 > private readonly _classStubs: Map<Function, any> = new Map();
24 > private readonly _parentTestService: TestInstantiationService | undefined;
25 >
26 > constructor(private _serviceCollection: ServiceCollection = new ServiceCollection(), strict: boolean = false, parent?: InstantiationService, private _properDispose?: boolean) {
27 > super(_serviceCollection, strict, parent); instantiationServiceMock.ts
28 >
29 > this._servciesMap = new Map<ServiceIdentifier<any>, any>();
30 > if (parent instanceof TestInstantiationService) {
31 > this._parentTestService = parent; instantiationServiceMock.ts
32 > }
35 > public get<T>(service: ServiceIdentifier<T>): T {
36 > return super._getOrCreateServiceInstance(service, Trace.traceCreation(false, TestInstantiationService)); instantiationServiceMock.ts
37 > }
39 > public set<T>(service: ServiceIdentifier<T>, instance: T): T {
40 return <T>this._serviceCollection.set(service, instance);
41 }
43 > public mock<T>(service: ServiceIdentifier<T>): T | sinon.SinonMock {
44 return <T>this._create(service, { mock: true });
45 }
47 > public stubInstance<T>(ctor: new (...args: any[]) => T, instance: Partial<T>): void {
48 this._classStubs.set(ctor, instance);
49 }
51 > protected _getClassStub(ctor: Function): unknown {
52 > return this._classStubs.get(ctor) ?? this._parentTestService?._getClassStub(ctor); instantiationServiceMock.ts
53 > }
55 > public override createInstance<T>(descriptor: SyncDescriptor0<T>): T;
56 > public override createInstance<Ctor extends new (...args: any[]) => unknown, R extends InstanceType<Ctor>>(ctor: Ctor, ...args: GetLeadingNonServiceArgs<ConstructorParameters<Ctor>>): R;
57 > public override createInstance(ctorOrDescriptor: any | SyncDescriptor<any>, ...rest: unknown[]): unknown {
58 > const stub = this._getClassStub(ctorOrDescriptor as Function); instantiationServiceMock.ts
59 > if (stub) {
60 return stub;
61 }
62 > return super.createInstance(ctorOrDescriptor, ...rest); instantiationServiceMock.ts
63 > }
65 > public stub<T>(service: ServiceIdentifier<T>, obj: Partial<NoInfer<T>> | Function): T;
66 > public stub<T, V>(service: ServiceIdentifier<T>, obj: Partial<NoInfer<T>> | Function, property: string, value: V): V extends Function ? sinon.SinonSpy : sinon.SinonStub;
67 > public stub<T, V>(service: ServiceIdentifier<T>, property: string, value: V): V extends Function ? sinon.SinonSpy : sinon.SinonStub;
68 > public stub<T>(serviceIdentifier: ServiceIdentifier<T>, arg2: any, arg3?: string, arg4?: any): sinon.SinonStub | sinon.SinonSpy {
69 > const service = typeof arg2 !== 'string' ? arg2 : undefined; instantiationServiceMock.ts
70 > const serviceMock: IServiceMock<any> = { id: serviceIdentifier, service: service };
71 > const property = typeof arg2 === 'string' ? arg2 : arg3;
72 > const value = typeof arg2 === 'string' ? arg3 : arg4;
73 >
74 > const stubObject = this._create(serviceMock, { stub: true }, service && !property);
75 > if (property) {
76 if (stubObject[property]) {
77 if (stubObject[property].hasOwnProperty('restore')) {
91 }
92 }
93 > return stubObject; instantiationServiceMock.ts
94 > }
96 > public stubPromise<T>(service?: ServiceIdentifier<T>, fnProperty?: string, value?: any): T | sinon.SinonStub;
97 > public stubPromise<T, V>(service?: ServiceIdentifier<T>, ctor?: any, fnProperty?: string, value?: V): V extends Function ? sinon.SinonSpy : sinon.SinonStub;
98 > public stubPromise<T, V>(service?: ServiceIdentifier<T>, obj?: any, fnProperty?: string, value?: V): V extends Function ? sinon.SinonSpy : sinon.SinonStub;
99 > public stubPromise(arg1?: any, arg2?: any, arg3?: any, arg4?: any): sinon.SinonStub | sinon.SinonSpy {
100 arg3 = typeof arg2 === 'string' ? Promise.resolve(arg3) : arg3;
101 arg4 = typeof arg2 !== 'string' && typeof arg3 === 'string' ? Promise.resolve(arg4) : arg4;
102 return this.stub(arg1, arg2, arg3, arg4);
103 }
105 > public spy<T>(service: ServiceIdentifier<T>, fnProperty: string): sinon.SinonSpy {
106 const spy = sinon.spy();
107 this.stub(service, fnProperty, spy);
108 return spy;
109 }
111 > private _create<T>(serviceMock: IServiceMock<T>, options: SinonOptions, reset?: boolean): any;
112 > private _create<T>(ctor: any, options: SinonOptions): any;
113 > private _create(arg1: any, options: SinonOptions, reset: boolean = false): any {
114 > if (this.isServiceMock(arg1)) { instantiationServiceMock.ts
115 > const service = this._getOrCreateService(arg1, options, reset);
116 > this._serviceCollection.set(arg1.id, service);
117 > return service;
118 > }
119 > return options.mock ? sinon.mock(arg1) : this._createStub(arg1);
120 > }
122 > private _getOrCreateService<T>(serviceMock: IServiceMock<T>, opts: SinonOptions, reset?: boolean): any {
123 > const service: any = this._serviceCollection.get(serviceMock.id); instantiationServiceMock.ts
124 > if (!reset && service) {
125 if (opts.mock && service['sinonOptions'] && !!service['sinonOptions'].mock) {
126 return service;
130 }
131 }
132 > return this._createService(serviceMock, opts); instantiationServiceMock.ts
133 > }
135 > private _createService(serviceMock: IServiceMock<any>, opts: SinonOptions): any {
136 > serviceMock.service = serviceMock.service ? serviceMock.service : this._servciesMap.get(serviceMock.id); instantiationServiceMock.ts
137 > const service = opts.mock ? sinon.mock(serviceMock.service) : this._createStub(serviceMock.service);
138 > service['sinonOptions'] = opts;
139 > return service;
140 > }
142 > private _createStub(arg: any): any {
143 > return typeof arg === 'object' ? arg : sinon.createStubInstance(arg); instantiationServiceMock.ts
144 > }
146 > private isServiceMock(arg1: any): boolean {
147 > return typeof arg1 === 'object' && arg1.hasOwnProperty('id'); instantiationServiceMock.ts
148 > }
150 > override createChild(services: ServiceCollection): TestInstantiationService {
151 > return new TestInstantiationService(services, false, this); instantiationServiceMock.ts
152 > }
154 > override dispose() {
155 > sinon.restore(); instantiationServiceMock.ts
156 > if (this._properDispose) {
157 super.dispose();
158 }
161 >
162 > interface SinonOptions {
163 > mock?: boolean;
164 > stub?: boolean;
165 > }
166 >
167 > export type ServiceIdCtorPair<T> = [id: ServiceIdentifier<T>, ctorOrInstance: T | (new (...args: any[]) => T)];
168 >
169 > export function createServices(disposables: DisposableStore, services: ServiceIdCtorPair<any>[]): TestInstantiationService {
170 const serviceIdentifiers: ServiceIdentifier<any>[] = [];
171 const serviceCollection = new ServiceCollection();
src/vs/platform/instantiation/common/instantiation.ts 126 covered LOC · 12 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- instantiation.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { DisposableStore } from '../../../base/common/lifecycle.js';
7 > import * as descriptors from './descriptors.js';
8 > import { ServiceCollection } from './serviceCollection.js';
9 >
10 > // ------ internal util
11 >
12 > export namespace _util {
13 >
14 > export const serviceIds = new Map<string, ServiceIdentifier<any>>();
15 >
16 > export const DI_TARGET = '$di$target';
17 > export const DI_DEPENDENCIES = '$di$dependencies';
18 >
19 > export function getServiceDependencies(ctor: DI_TARGET_OBJ): { id: ServiceIdentifier<any>; index: number }[] {
20 > return ctor[DI_DEPENDENCIES] || []; instantiation.ts
21 > }
23 > export interface DI_TARGET_OBJ extends Function {
24 > [DI_TARGET]: Function;
25 > [DI_DEPENDENCIES]: { id: ServiceIdentifier<any>; index: number }[];
26 > }
27 > }
28 >
29 > // --- interfaces ------
30 >
31 > export type BrandedService = { _serviceBrand: undefined };
32 >
33 > export interface IConstructorSignature<T, Args extends any[] = []> {
34 > new <Services extends BrandedService[]>(...args: [...Args, ...Services]): T;
35 > }
36 >
37 > export interface ServicesAccessor {
38 > get<T>(id: ServiceIdentifier<T>): T;
39 > }
40 >
41 > export const IInstantiationService = createDecorator<IInstantiationService>('instantiationService');
42 >
43 > /**
44 > * Given a list of arguments as a tuple, attempt to extract the leading, non-service arguments
45 > * to their own tuple.
46 > */
47 > export type GetLeadingNonServiceArgs<TArgs extends any[]> =
48 > TArgs extends [] ? []
49 > : TArgs extends [...infer TFirst, BrandedService] ? GetLeadingNonServiceArgs<TFirst>
50 > : TArgs;
51 >
52 > export interface IInstantiationService {
53 >
54 > readonly _serviceBrand: undefined;
55 >
56 > /**
57 > * Synchronously creates an instance that is denoted by the descriptor
58 > */
59 > createInstance<T>(descriptor: descriptors.SyncDescriptor0<T>): T;
60 > createInstance<Ctor extends new (...args: any[]) => unknown, R extends InstanceType<Ctor>>(ctor: Ctor, ...args: GetLeadingNonServiceArgs<ConstructorParameters<Ctor>>): R;
61 >
62 > /**
63 > * Calls a function with a service accessor.
64 > */
65 > invokeFunction<R, TS extends any[] = []>(fn: (accessor: ServicesAccessor, ...args: TS) => R, ...args: TS): R;
66 >
67 > /**
68 > * Creates a child of this service which inherits all current services
69 > * and adds/overwrites the given services.
70 > *
71 > * NOTE that the returned child is `disposable` and should be disposed when not used
72 > * anymore. This will also dispose all the services that this service has created.
73 > */
74 > createChild(services: ServiceCollection, store?: DisposableStore): IInstantiationService;
75 >
76 > /**
77 > * Disposes this instantiation service.
78 > *
79 > * - Will dispose all services that this instantiation service has created.
80 > * - Will dispose all its children but not its parent.
81 > * - Will NOT dispose services-instances that this service has been created with
82 > * - Will NOT dispose consumer-instances this service has created
83 > */
84 > dispose(): void;
85 > }
86 >
87 >
88 > /**
89 > * Identifies a service of type `T`.
90 > */
91 > export interface ServiceIdentifier<T> {
92 > (...args: any[]): void;
93 > type: T;
94 > }
95 >
96 >
97 > function storeServiceDependency(id: ServiceIdentifier<unknown>, target: Function, index: number): void { instantiation.ts
98 > if ((target as _util.DI_TARGET_OBJ)[_util.DI_TARGET] === target) {
99 > (target as _util.DI_TARGET_OBJ)[_util.DI_DEPENDENCIES].push({ id, index }); instantiation.ts
100 > } else { instantiation.ts
101 > (target as _util.DI_TARGET_OBJ)[_util.DI_DEPENDENCIES] = [{ id, index }];
102 > (target as _util.DI_TARGET_OBJ)[_util.DI_TARGET] = target;
103 > }
104 > }
106 > /**
107 > * The *only* valid way to create a {{ServiceIdentifier}}.
108 > */
109 > export function createDecorator<T>(serviceId: string): ServiceIdentifier<T> {
110 >
111 > if (_util.serviceIds.has(serviceId)) {
112 return _util.serviceIds.get(serviceId)!;
113 }
115 > const id = function (target: Function, key: string, index: number) {
116 > if (arguments.length !== 3) { instantiation.ts
117 throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
118 }
119 > storeServiceDependency(id, target, index); instantiation.ts
120 > } as ServiceIdentifier<T>;
122 > id.toString = () => serviceId;
123 >
124 > _util.serviceIds.set(serviceId, id);
125 > return id;
126 > }
127 >
128 > export function refineServiceDecorator<T1, T extends T1>(serviceIdentifier: ServiceIdentifier<T1>): ServiceIdentifier<T> {
129 > return <ServiceIdentifier<T>>serviceIdentifier; instantiation.ts
130 > }
src/vs/base/test/common/virtualScheduling/trace.ts 122 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- trace.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { BugIndicatingError } from '../../../common/errors.js';
7 >
8 > /**
9 > * # Trace — causal-chain attribution for scheduled work
10 > *
11 > * A {@link Trace} is an immutable value identifying a causal chain. Every
12 > * non-root trace carries a `parent`; the head of the chain has no parent.
13 > * Use {@link child} to extend a chain when scheduling follow-up work.
14 > *
15 > * Traces are used to answer "who caused this?" for any virtual event:
16 > * useful for debugging, for per-owner termination, and for attribution in
17 > * error messages.
18 > */
19 > export class Trace {
20 > private static _idCounter = 0;
21 > public readonly id: number = ++Trace._idCounter;
22 > public readonly root: Trace;
23 > public readonly depth: number;
24 >
25 > constructor(
26 > public readonly parent: Trace | undefined,
27 > public readonly label: string,
28 > public readonly stack: string | undefined = undefined,
29 > ) {
30 > this.root = parent?.root ?? this;
31 > this.depth = (parent?.depth ?? -1) + 1;
32 > }
33 >
34 > child(label: string, stack?: string): Trace {
35 return new Trace(this, label, stack);
36 }
37 > trace.ts
38 > /** "#id label ← #id label ← … ← #id label" */
39 > describe(): string {
40 const parts: string[] = [];
41 for (let t: Trace | undefined = this; t; t = t.parent) {
44 return parts.join(' ← ');
45 }
46 > trace.ts
47 > toString(): string { return this.describe(); }
48 > }
49 >
50 > /** Sentinel for "no known causal predecessor". */
51 > export const ROOT_TRACE: Trace = new Trace(undefined, '<root>');
52 >
53 > export function createTraceRoot(label: string, stack?: string): Trace {
54 return new Trace(undefined, label, stack);
55 }
56 > trace.ts
57 > interface Frame {
58 > readonly trace: Trace;
59 > readonly prev: Frame | undefined;
60 > }
61 >
62 > const ROOT_FRAME: Frame = { trace: ROOT_TRACE, prev: undefined };
63 >
64 > /**
65 > * Options for {@link TraceContext.runAsHandler}.
66 > *
67 > * # Why this is a per-call option
68 > *
69 > * `runAsHandler` cannot restore the previous trace synchronously: microtasks
70 > * enqueued by `fn` (including awaited continuations) must observe the new
71 > * trace. So the reset is deferred — but it must fire after the *closure* of
72 > * the microtask queue (the current microtask plus every microtask it
73 > * recursively enqueues), not just one drain.
74 > *
75 > * Per spec, the host doesn't run a macrotask until the microtask queue is
76 > * empty, so any macrotask primitive (`setTimeout(0)`, `setImmediate`, the
77 > * `setTimeout0` shim) achieves this. Letting the *caller* supply the sink
78 > * means:
79 > *
80 > * - the {@link VirtualTimeProcessor} can route the reset through the same
81 > * primitive its embedding uses for its own host hops, eliminating any
82 > * race between the processor's hops and the trace-reset timer;
83 > *
84 > * - production code without a processor can still use a real
85 > * `setTimeout(0)`-based sink and get the same semantics;
86 > *
87 > * - tests can install a deterministic sink (e.g. a hand-driven queue) for
88 > * fully synchronous assertions.
89 > */
90 > export interface RunAsHandlerOptions {
91 > /**
92 > * Sink for the deferred trace-reset.
93 > *
94 > * Must invoke `reset` after the microtask closure that follows the
95 > * `runAsHandler` call returns — i.e. on the next host macrotask.
96 > */
97 > readonly afterMicrotaskClosure: (reset: () => void) => void;
98 > }
99 >
100 > /**
101 > * Holds the mutable "current trace frame" slot. Construct fresh instances
102 > * for test isolation, or use {@link TraceContext.instance} for shared state.
103 > */
104 > export class TraceContext {
105 > public static readonly instance = new TraceContext();
106 >
107 > private _current: Frame = ROOT_FRAME;
108 > private _isHandlerRunning = false;
109 >
110 > currentTrace(): Trace { return this._current.trace; }
111 >
112 > /**
113 > * Install `t` as current for the synchronous duration of `fn`, then
114 > * restore. Nestable. Microtasks enqueued by fn that run after fn returns
115 > * see the *restored* trace — use {@link runAsHandler} when continuation
116 > * inheritance is wanted.
117 > */
118 > runWithTrace<T>(t: Trace, fn: () => T): T {
119 const prev = this._current;
120 const next: Frame = { trace: t, prev };
132 }
133 }
134 > trace.ts
135 > /**
136 > * Install `t` as current and run `fn`. The trace stays current through
137 > * the microtask closure that follows `fn`, so awaited continuations
138 > * inside fn observe `t`. The reset is dispatched via
139 > * `opts.afterMicrotaskClosure`.
140 > *
141 > * Throws on synchronous re-entry: timer callbacks never nest on the
142 > * same JS stack frame, so this only fires for misuse.
143 > */
144 > runAsHandler<T>(t: Trace, fn: () => T, opts: RunAsHandlerOptions): T {
145 if (this._isHandlerRunning) {
146 throw new Error(
165 }
166 }
167 > trace.ts
168 > _resetForTesting(): void {
169 this._current = ROOT_FRAME;
170 this._isHandlerRunning = false;
171 }
172 > } trace.ts
src/vs/platform/configuration/common/configurations.ts 121 covered LOC · 30 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- configurations.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IStringDictionary } from '../../../base/common/collections.js';
7 > import { Emitter, Event } from '../../../base/common/event.js';
8 > import { Disposable } from '../../../base/common/lifecycle.js';
9 > import { deepClone, equals } from '../../../base/common/objects.js';
10 > import { isEmptyObject, isString } from '../../../base/common/types.js';
11 > import { ConfigurationModel } from './configurationModels.js';
12 > import { Extensions, IConfigurationRegistry, IRegisteredConfigurationPropertySchema } from './configurationRegistry.js';
13 > import { ILogService, NullLogService } from '../../log/common/log.js';
14 > import { IPolicyService, PolicyDefinition, PolicyValue } from '../../policy/common/policy.js';
15 > import { Registry } from '../../registry/common/platform.js';
16 > import { getErrorMessage } from '../../../base/common/errors.js';
17 > import * as json from '../../../base/common/json.js';
18 > import { PolicyName } from '../../../base/common/policy.js';
19 >
20 > export class DefaultConfiguration extends Disposable {
21 >
22 > private readonly _onDidChangeConfiguration = this._register(new Emitter<{ defaults: ConfigurationModel; properties: string[] }>());
23 > readonly onDidChangeConfiguration = this._onDidChangeConfiguration.event;
24 >
25 > private _configurationModel: ConfigurationModel;
26 > get configurationModel(): ConfigurationModel {
27 > return this._configurationModel;
28 > }
29 >
30 > constructor(private readonly logService: ILogService) {
31 > super(); configurations.ts
32 > this._configurationModel = ConfigurationModel.createEmptyModel(logService);
33 > }
35 > async initialize(): Promise<ConfigurationModel> {
36 > this.resetConfigurationModel(); configurations.ts
37 > this._register(Registry.as<IConfigurationRegistry>(Extensions.Configuration).onDidUpdateConfiguration(({ properties, defaultsOverrides }) => this.onDidUpdateConfiguration(Array.from(properties), defaultsOverrides)));
38 > return this.configurationModel;
39 > }
41 > reload(): ConfigurationModel {
42 this.resetConfigurationModel();
43 return this.configurationModel;
44 }
46 > protected onDidUpdateConfiguration(properties: string[], defaultsOverrides?: boolean): void {
47 this.updateConfigurationModel(properties, Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties());
48 this._onDidChangeConfiguration.fire({ defaults: this.configurationModel, properties });
49 }
51 > protected getConfigurationDefaultOverrides(): IStringDictionary<unknown> {
52 > return {}; configurations.ts
53 > }
55 > private resetConfigurationModel(): void {
56 > this._configurationModel = ConfigurationModel.createEmptyModel(this.logService); configurations.ts
57 > const properties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
58 > this.updateConfigurationModel(Object.keys(properties), properties);
59 > }
61 > private updateConfigurationModel(properties: string[], configurationProperties: IStringDictionary<IRegisteredConfigurationPropertySchema>): void {
62 > const configurationDefaultsOverrides = this.getConfigurationDefaultOverrides(); configurations.ts
63 > for (const key of properties) {
64 > const defaultOverrideValue = configurationDefaultsOverrides[key]; configurations.ts
65 > const propertySchema = configurationProperties[key];
66 > if (defaultOverrideValue !== undefined) {
67 this._configurationModel.setValue(key, defaultOverrideValue);
68 > } else if (propertySchema) { configurations.ts
69 > this._configurationModel.setValue(key, this.getDefaultValue(key, propertySchema));
70 > } else {
71 this._configurationModel.removeValue(key);
72 }
76 > protected getDefaultValue(_key: string, propertySchema: IRegisteredConfigurationPropertySchema): unknown {
77 > return deepClone(propertySchema.default); configurations.ts
78 > }
80 > }
81 >
82 > export interface IPolicyConfiguration {
83 > readonly onDidChangeConfiguration: Event<ConfigurationModel>;
84 > readonly configurationModel: ConfigurationModel;
85 > initialize(): Promise<ConfigurationModel>;
86 > }
87 >
88 > export class NullPolicyConfiguration implements IPolicyConfiguration {
89 > readonly onDidChangeConfiguration = Event.None; configurations.ts
90 > readonly configurationModel = ConfigurationModel.createEmptyModel(new NullLogService());
91 > async initialize() { return this.configurationModel; } configurations.ts
92 > }
93 >
94 > type ParsedType = IStringDictionary<unknown> | Array<unknown>;
95 >
96 > export class PolicyConfiguration extends Disposable implements IPolicyConfiguration {
97 >
98 > private readonly _onDidChangeConfiguration = this._register(new Emitter<ConfigurationModel>());
99 > readonly onDidChangeConfiguration = this._onDidChangeConfiguration.event;
100 >
101 > private readonly configurationRegistry: IConfigurationRegistry;
102 >
103 > private _configurationModel: ConfigurationModel;
104 > get configurationModel() { return this._configurationModel; }
105 >
106 > /** Last definition submitted per policy name; avoids redundant re-registration. */
107 > private readonly _submittedPolicyDefinitions = new Map<PolicyName, PolicyDefinition>();
108 >
109 > /** Maps each policy-controlled setting key to its policy name, so removed keys can be re-resolved. */
110 > private readonly _policyNameByKey = new Map<string, PolicyName>();
111 >
112 > constructor(
113 private readonly defaultConfiguration: DefaultConfiguration,
114 @IPolicyService private readonly policyService: IPolicyService,
119 this.configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
120 }
122 > async initialize(): Promise<ConfigurationModel> {
123 this.logService.trace('PolicyConfiguration#initialize');
124
129 return this._configurationModel;
130 }
132 > private toPolicyDefinitionType(configType: unknown, policyName: PolicyName): 'string' | 'number' | 'boolean' | undefined {
133 // `configType` may be a single type or a union (e.g. `['array', 'null']`).
134 // Normalize to an array and keep only the types we can represent as policies.
141 return supportedTypes.includes('number') ? 'number' : supportedTypes.includes('boolean') ? 'boolean' : 'string';
142 }
144 > private async updatePolicyDefinitions(properties: string[]): Promise<string[]> {
145 this.logService.trace('PolicyConfiguration#updatePolicyDefinitions', properties);
146 const keys: string[] = [];
183 return keys;
184 }
186 > private isSamePolicyDefinition(a: PolicyDefinition | undefined, b: PolicyDefinition): boolean {
187 return !!a && a.type === b.type && a.value === b.value && a.managedSettings === b.managedSettings && a.restrictedValue === b.restrictedValue;
188 }
190 > /** Resolve the authoritative definition: owner wins; references provide a bare type fallback. */
191 > private resolvePolicyDefinition(policyName: PolicyName): PolicyDefinition | undefined {
192 const configurationProperties = this.configurationRegistry.getConfigurationProperties();
193 const excludedConfigurationProperties = this.configurationRegistry.getExcludedConfigurationProperties();
214 return undefined;
215 }
217 > private onDidChangePolicies(policyNames: readonly PolicyName[]): void {
218 this.logService.trace('PolicyConfiguration#onDidChangePolicies', policyNames);
219 const policyConfigurations = this.configurationRegistry.getPolicyConfigurations();
232 this.update(keys, true);
233 }
235 > private update(keys: string[], trigger: boolean): void {
236 this.logService.trace('PolicyConfiguration#update', keys);
237 const configurationProperties = this.configurationRegistry.getConfigurationProperties();
286 }
287 }
289 > private parse(content: string): ParsedType {
290 let raw: ParsedType = {};
291 let currentProperty: string | null = null;
src/vs/platform/telemetry/common/telemetry.ts 115 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- telemetry.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { createDecorator } from '../../instantiation/common/instantiation.js';
7 > import { ClassifiedEvent, IGDPRProperty, OmitMetadata, StrictPropertyCheck } from './gdprTypings.js';
8 >
9 > export const ITelemetryService = createDecorator<ITelemetryService>('telemetryService');
10 >
11 > export interface ITelemetryData {
12 > from?: string;
13 > target?: string;
14 > [key: string]: string | unknown | undefined;
15 > }
16 >
17 > export interface ITelemetryService {
18 >
19 > readonly _serviceBrand: undefined;
20 >
21 > readonly telemetryLevel: TelemetryLevel;
22 >
23 > readonly sessionId: string;
24 > readonly machineId: string;
25 > readonly sqmId: string;
26 > readonly devDeviceId: string;
27 > readonly firstSessionDate: string;
28 > readonly msftInternal?: boolean;
29 >
30 > /**
31 > * Whether error telemetry will get sent. If false, `publicLogError` will no-op.
32 > */
33 > readonly sendErrorTelemetry: boolean;
34 >
35 > /**
36 > * @deprecated Use publicLog2 and the typescript GDPR annotation where possible
37 > */
38 > publicLog(eventName: string, data?: ITelemetryData): void;
39 >
40 > /**
41 > * Sends a telemetry event that has been privacy approved.
42 > * Do not call this unless you have been given approval.
43 > */
44 > publicLog2<E extends ClassifiedEvent<OmitMetadata<T>> = never, T extends IGDPRProperty = never>(eventName: string, data?: StrictPropertyCheck<T, E>): void;
45 >
46 > /**
47 > * @deprecated Use publicLogError2 and the typescript GDPR annotation where possible
48 > */
49 > publicLogError(errorEventName: string, data?: ITelemetryData): void;
50 >
51 > publicLogError2<E extends ClassifiedEvent<OmitMetadata<T>> = never, T extends IGDPRProperty = never>(eventName: string, data?: StrictPropertyCheck<T, E>): void;
52 >
53 > setExperimentProperty(name: string, value: string): void;
54 >
55 > /**
56 > * Sets a common property that will be attached to all telemetry events.
57 > * Common properties are added after PII cleaning and cannot be overridden by event data.
58 > */
59 > setCommonProperty(name: string, value: string | boolean): void;
60 > }
61 >
62 > export function telemetryLevelEnabled(service: ITelemetryService, level: TelemetryLevel): boolean {
63 return service.telemetryLevel >= level;
64 }
66 > /**
67 > * Replaces `/` and `\` with `|` in model identifiers to prevent the
68 > * telemetry pipeline from redacting them as file paths.
69 > */
70 > export function escapeModelIdForTelemetry(modelId: string | undefined): string | undefined {
71 return modelId?.replace(/[\/\\]/g, '|');
72 }
74 > export interface ITelemetryEndpoint {
75 > id: string;
76 > aiKey: string;
77 > sendErrorTelemetry: boolean;
78 > }
79 >
80 > export const ICustomEndpointTelemetryService = createDecorator<ICustomEndpointTelemetryService>('customEndpointTelemetryService');
81 >
82 > export interface ICustomEndpointTelemetryService {
83 > readonly _serviceBrand: undefined;
84 >
85 > publicLog(endpoint: ITelemetryEndpoint, eventName: string, data?: ITelemetryData): void;
86 > publicLogError(endpoint: ITelemetryEndpoint, errorEventName: string, data?: ITelemetryData): void;
87 > }
88 >
89 > // Keys
90 > export const currentSessionDateStorageKey = 'telemetry.currentSessionDate';
91 > export const firstSessionDateStorageKey = 'telemetry.firstSessionDate';
92 > export const lastSessionDateStorageKey = 'telemetry.lastSessionDate';
93 > export const machineIdKey = 'telemetry.machineId';
94 > export const sqmIdKey = 'telemetry.sqmId';
95 > export const devDeviceIdKey = 'telemetry.devDeviceId';
96 >
97 > // Configuration Keys
98 > export const TELEMETRY_SECTION_ID = 'telemetry';
99 > export const TELEMETRY_SETTING_ID = 'telemetry.telemetryLevel';
100 > export const TELEMETRY_CRASH_REPORTER_SETTING_ID = 'telemetry.enableCrashReporter';
101 > export const TELEMETRY_OLD_SETTING_ID = 'telemetry.enableTelemetry';
102 >
103 > export const enum TelemetryLevel {
104 > NONE = 0,
105 > CRASH = 1,
106 > ERROR = 2,
107 > USAGE = 3
108 > }
109 >
110 > export const enum TelemetryConfiguration {
111 > OFF = 'off',
112 > CRASH = 'crash',
113 > ERROR = 'error',
114 > ON = 'all'
115 > }
116 >
117 > export interface ICommonProperties {
118 > [name: string]: string | boolean | undefined;
119 > }
src/vs/base/common/hash.ts 114 covered LOC · 32 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- hash.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { encodeHex, VSBuffer } from './buffer.js';
7 > import * as strings from './strings.js';
8 >
9 > type NotSyncHashable = ArrayBufferLike | ArrayBufferView;
10 >
11 > /**
12 > * Return a hash value for an object.
13 > *
14 > * Note that this should not be used for binary data types. Instead,
15 > * prefer {@link hashAsync}.
16 > */
17 > export function hash<T>(obj: T extends NotSyncHashable ? never : T): number {
18 > return doHash(obj, 0); hash.ts
19 > }
20 > hash.ts
21 > export function doHash(obj: unknown, hashVal: number): number {
22 > switch (typeof obj) { hash.ts
23 > case 'object':
24 > if (obj === null) { hash.ts
25 return numberHash(349, hashVal);
26 > } else if (Array.isArray(obj)) { hash.ts
27 > return arrayHash(obj, hashVal);
28 > }
29 > return objectHash(obj, hashVal);
30 > case 'string': hash.ts
31 > return stringHash(obj, hashVal);
32 > case 'boolean':
33 > return booleanHash(obj, hashVal); hash.ts
34 > case 'number': hash.ts
35 return numberHash(obj, hashVal);
36 > case 'undefined': hash.ts
37 return numberHash(937, hashVal);
38 > default: hash.ts
39 return numberHash(617, hashVal);
40 > } hash.ts
41 > }
42 > hash.ts
43 > export function numberHash(val: number, initialHashVal: number): number {
44 > return (((initialHashVal << 5) - initialHashVal) + val) | 0; // hashVal * 31 + ch, keep as int32 hash.ts
45 > }
46 > hash.ts
47 > function booleanHash(b: boolean, initialHashVal: number): number { hash.ts
48 > return numberHash(b ? 433 : 863, initialHashVal);
49 > }
50 > hash.ts
51 > export function stringHash(s: string, hashVal: number) {
52 > hashVal = numberHash(149417, hashVal); hash.ts
53 > for (let i = 0, length = s.length; i < length; i++) {
54 > hashVal = numberHash(s.charCodeAt(i), hashVal);
55 > }
56 > return hashVal;
57 > }
58 > hash.ts
59 > function arrayHash(arr: unknown[], initialHashVal: number): number { hash.ts
60 > initialHashVal = numberHash(104579, initialHashVal);
61 > return arr.reduce<number>((hashVal, item) => doHash(item, hashVal), initialHashVal);
62 > }
63 > hash.ts
64 > function objectHash(obj: object, initialHashVal: number): number { hash.ts
65 > initialHashVal = numberHash(181387, initialHashVal);
66 > return Object.keys(obj).sort().reduce((hashVal, key) => {
67 > hashVal = stringHash(key, hashVal);
68 > return doHash((obj as Record<string, unknown>)[key], hashVal);
69 > }, initialHashVal);
70 > }
71 > hash.ts
72 >
73 >
74 > /** Hashes the input as SHA-1, returning a hex-encoded string. */
75 > export const hashAsync = (input: string | ArrayBufferView | VSBuffer) => {
76 // Note: I would very much like to expose a streaming interface for hashing
77 // generally, but this is not available in web crypto yet, see
96 return crypto.subtle.digest('sha-1', buff as ArrayBufferView<ArrayBuffer>).then(toHexString); // CodeQL [SM04514] we use sha1 here for validating old stored client state, not for security
97 };
98 > hash.ts
99 > const enum SHA1Constant {
100 > BLOCK_SIZE = 64, // 512 / 8
101 > UNICODE_REPLACEMENT = 0xFFFD,
102 > }
103 >
104 function leftRotate(value: number, bits: number, totalBits: number = 32): number {
105 // delta + bits = totalBits
112 return ((value << bits) | ((mask & value) >>> delta)) >>> 0;
113 }
114 > hash.ts
115 > function toHexString(buffer: ArrayBuffer): string;
116 > function toHexString(value: number, bitsize?: number): string;
117 function toHexString(bufferOrValue: ArrayBuffer | number, bitsize: number = 32): string {
118 if (bufferOrValue instanceof ArrayBuffer) {
122 return (bufferOrValue >>> 0).toString(16).padStart(bitsize / 4, '0');
123 }
124 > hash.ts
125 > /**
126 > * A SHA1 implementation that works with strings and does not allocate.
127 > *
128 > * Prefer to use {@link hashAsync} in async contexts
129 > */
130 > export class StringSHA1 {
131 > private static _bigBlock32 = new DataView(new ArrayBuffer(320)); // 80 * 4 = 320
132 >
133 > private _h0 = 0x67452301;
134 > private _h1 = 0xEFCDAB89;
135 > private _h2 = 0x98BADCFE;
136 > private _h3 = 0x10325476;
137 > private _h4 = 0xC3D2E1F0;
138 >
139 > private readonly _buff: Uint8Array;
140 > private readonly _buffDV: DataView;
141 > private _buffLen: number;
142 > private _totalLen: number;
143 > private _leftoverHighSurrogate: number;
144 > private _finished: boolean;
145 >
146 > constructor() {
147 this._buff = new Uint8Array(SHA1Constant.BLOCK_SIZE + 3 /* to fit any utf-8 */);
148 this._buffDV = new DataView(this._buff.buffer);
152 this._finished = false;
153 }
154 > hash.ts
155 > public update(str: string): void {
156 const strLen = str.length;
157 if (strLen === 0) {
208 this._leftoverHighSurrogate = leftoverHighSurrogate;
209 }
210 > hash.ts
211 > private _push(buff: Uint8Array, buffLen: number, codePoint: number): number {
212 if (codePoint < 0x0080) {
213 buff[buffLen++] = codePoint;
238 return buffLen;
239 }
240 > hash.ts
241 > public digest(): string {
242 if (!this._finished) {
243 this._finished = true;
253 return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4);
254 }
255 > hash.ts
256 > private _wrapUp(): void {
257 this._buff[this._buffLen++] = 0x80;
258 this._buff.subarray(this._buffLen).fill(0);
271 this._step();
272 }
273 > hash.ts
274 > private _step(): void {
275 const bigBlock32 = StringSHA1._bigBlock32;
276 const data = this._buffDV;
322 this._h4 = (this._h4 + e) & 0xffffffff;
323 }
324 > } hash.ts
src/vs/base/common/extpath.ts 112 covered LOC · 28 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extpath.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CharCode } from './charCode.js';
7 > import { isAbsolute, join, normalize, posix, sep } from './path.js';
8 > import { isWindows } from './platform.js';
9 > import { equalsIgnoreCase, rtrim, startsWithIgnoreCase } from './strings.js';
10 > import { isNumber } from './types.js';
11 >
12 > export function isPathSeparator(code: number) {
13 return code === CharCode.Slash || code === CharCode.Backslash;
14 }
15 > extpath.ts
16 > /**
17 > * Takes a Windows OS path and changes backward slashes to forward slashes.
18 > * This should only be done for OS paths from Windows (or user provided paths potentially from Windows).
19 > * Using it on a Linux or MaxOS path might change it.
20 > */
21 > export function toSlashes(osPath: string) {
22 return osPath.replace(/[\\/]/g, posix.sep);
23 }
24 > extpath.ts
25 > /**
26 > * Takes a Windows OS path (using backward or forward slashes) and turns it into a posix path:
27 > * - turns backward slashes into forward slashes
28 > * - makes it absolute if it starts with a drive letter
29 > * This should only be done for OS paths from Windows (or user provided paths potentially from Windows).
30 > * Using it on a Linux or MaxOS path might change it.
31 > */
32 > export function toPosixPath(osPath: string) {
33 if (osPath.indexOf('/') === -1) {
34 osPath = toSlashes(osPath);
39 return osPath;
40 }
41 > extpath.ts
42 > /**
43 > * Computes the _root_ this path, like `getRoot('c:\files') === c:\`,
44 > * `getRoot('files:///files/path') === files:///`,
45 > * or `getRoot('\\server\shares\path') === \\server\shares\`
46 > */
47 > export function getRoot(path: string, sep: string = posix.sep): string {
48 if (!path) {
49 return '';
111 return '';
112 }
113 > extpath.ts
114 > /**
115 > * Check if the path follows this pattern: `\\hostname\sharename`.
116 > *
117 > * @see https://msdn.microsoft.com/en-us/library/gg465305.aspx
118 > * @return A boolean indication if the path is a UNC path, on none-windows
119 > * always false.
120 > */
121 > export function isUNC(path: string): boolean {
122 if (!isWindows) {
123 // UNC is a windows concept
162 return true;
163 }
164 > extpath.ts
165 > // Reference: https://en.wikipedia.org/wiki/Filename
166 > const WINDOWS_INVALID_FILE_CHARS = /[\\/:\*\?"<>\|]/g;
167 > const UNIX_INVALID_FILE_CHARS = /[/]/g;
168 > const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])(\.(.*?))?$/i;
169 > export function isValidBasename(name: string | null | undefined, isWindowsOS: boolean = isWindows): boolean {
170 const invalidFileChars = isWindowsOS ? WINDOWS_INVALID_FILE_CHARS : UNIX_INVALID_FILE_CHARS;
171
201 return true;
202 }
203 > extpath.ts
204 > /**
205 > * @deprecated please use `IUriIdentityService.extUri.isEqual` instead. If you are
206 > * in a context without services, consider to pass down the `extUri` from the outside
207 > * or use `extUriBiasedIgnorePathCase` if you know what you are doing.
208 > */
209 > export function isEqual(pathA: string, pathB: string, ignoreCase?: boolean): boolean {
210 const identityEquals = (pathA === pathB);
211 if (!ignoreCase || identityEquals) {
219 return equalsIgnoreCase(pathA, pathB);
220 }
221 > extpath.ts
222 > /**
223 > * @deprecated please use `IUriIdentityService.extUri.isEqualOrParent` instead. If
224 > * you are in a context without services, consider to pass down the `extUri` from the
225 > * outside, or use `extUriBiasedIgnorePathCase` if you know what you are doing.
226 > */
227 > export function isEqualOrParent(base: string, parentCandidate: string, ignoreCase?: boolean, forcePosixSemantics = false): boolean {
228 > const separator = forcePosixSemantics ? posix.sep : sep; extpath.ts
229 >
230 > if (base === parentCandidate) {
231 return true;
232 }
233 > extpath.ts
234 > if (!base || !parentCandidate) { extpath.ts
235 return false;
236 }
237 > extpath.ts
238 > if (
239 > base.indexOf('..') >= 0 ||
240 > parentCandidate.indexOf('..') >= 0 extpath.ts
241 > ) { extpath.ts
242 base = forcePosixSemantics ? posix.normalize(base) : normalize(base);
243 parentCandidate = forcePosixSemantics ? posix.normalize(parentCandidate) : normalize(parentCandidate);
244 }
245 > extpath.ts
246 > if (parentCandidate.length > base.length) {
247 return false;
248 }
249 > extpath.ts
250 > if (ignoreCase) {
251 const beginsWith = startsWithIgnoreCase(base, parentCandidate);
252 if (!beginsWith) {
265 return base.charAt(sepOffset) === separator;
266 }
267 > extpath.ts
268 > if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) {
269 > parentCandidate += separator; extpath.ts
270 > }
271 > extpath.ts
272 > return base.indexOf(parentCandidate) === 0;
273 > }
274 > extpath.ts
275 > export function isWindowsDriveLetter(char0: number): boolean {
276 return char0 >= CharCode.A && char0 <= CharCode.Z || char0 >= CharCode.a && char0 <= CharCode.z;
277 }
278 > extpath.ts
279 > export function sanitizeFilePath(candidate: string, cwd: string): string {
280
281 // Special case: allow to open a drive letter without trailing backslash
295 return removeTrailingPathSeparator(candidate);
296 }
297 > extpath.ts
298 > export function removeTrailingPathSeparator(candidate: string): string {
299 if (isWindows) {
300 candidate = rtrim(candidate, sep);
316 return candidate;
317 }
318 > extpath.ts
319 > export function isRootOrDriveLetter(path: string): boolean {
320 const pathNormalized = normalize(path);
321
331 return pathNormalized === posix.sep;
332 }
333 > extpath.ts
334 > export function hasDriveLetter(path: string, isWindowsOS: boolean = isWindows): boolean {
335 if (isWindowsOS) {
336 return isWindowsDriveLetter(path.charCodeAt(0)) && path.charCodeAt(1) === CharCode.Colon;
339 return false;
340 }
341 > extpath.ts
342 > export function getDriveLetter(path: string, isWindowsOS: boolean = isWindows): string | undefined {
343 return hasDriveLetter(path, isWindowsOS) ? path[0] : undefined;
344 }
345 > extpath.ts
346 > export function indexOfPath(path: string, candidate: string, ignoreCase?: boolean): number {
347 if (candidate.length > path.length) {
348 return -1;
360 return path.indexOf(candidate);
361 }
362 > extpath.ts
363 > export interface IPathWithLineAndColumn {
364 > path: string;
365 > line?: number;
366 > column?: number;
367 > }
368 >
369 > export function parseLineAndColumnAware(rawPath: string): IPathWithLineAndColumn {
370 const segments = rawPath.split(':'); // C:\file.txt:<line>:<column>
371
395 };
396 }
397 > extpath.ts
398 > const pathChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
399 > const windowsSafePathFirstChars = 'BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789';
400 >
401 > export function randomPath(parent?: string, prefix?: string, randomLength = 8): string {
402 let suffix = '';
403 for (let i = 0; i < randomLength; i++) {
src/vs/base/common/mime.ts 102 covered LOC · 5 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- mime.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { extname } from './path.js';
7 >
8 > export const Mimes = Object.freeze({
9 > text: 'text/plain',
10 > binary: 'application/octet-stream',
11 > unknown: 'application/unknown',
12 > markdown: 'text/markdown',
13 > latex: 'text/latex',
14 > uriList: 'text/uri-list',
15 > html: 'text/html',
16 > });
17 >
18 > interface MapExtToMediaMimes {
19 > [index: string]: string | string[];
20 > }
21 >
22 > const mapExtToTextMimes: Record<string, string> = {
23 > '.css': 'text/css',
24 > '.csv': 'text/csv',
25 > '.htm': 'text/html',
26 > '.html': 'text/html',
27 > '.ics': 'text/calendar',
28 > '.js': 'text/javascript',
29 > '.mjs': 'text/javascript',
30 > '.txt': 'text/plain',
31 > '.xml': 'text/xml'
32 > };
33 >
34 > // Known media mimes that we can handle
35 > const mapExtToMediaMimes: MapExtToMediaMimes = {
36 > '.aac': 'audio/x-aac',
37 > '.avi': 'video/x-msvideo',
38 > '.bmp': 'image/bmp',
39 > '.flv': 'video/x-flv',
40 > '.gif': 'image/gif',
41 > '.ico': 'image/x-icon',
42 > '.jpe': ['image/jpg', 'image/jpeg'],
43 > '.jpeg': ['image/jpg', 'image/jpeg'],
44 > '.jpg': ['image/jpg', 'image/jpeg'],
45 > '.m1v': 'video/mpeg',
46 > '.m2a': 'audio/mpeg',
47 > '.m2v': 'video/mpeg',
48 > '.m3a': 'audio/mpeg',
49 > '.mid': 'audio/midi',
50 > '.midi': 'audio/midi',
51 > '.mk3d': 'video/x-matroska',
52 > '.mks': 'video/x-matroska',
53 > '.mkv': 'video/x-matroska',
54 > '.mov': 'video/quicktime',
55 > '.movie': 'video/x-sgi-movie',
56 > '.mp2': 'audio/mpeg',
57 > '.mp2a': 'audio/mpeg',
58 > '.mp3': 'audio/mpeg',
59 > '.mp4': 'video/mp4',
60 > '.mp4a': 'audio/mp4',
61 > '.mp4v': 'video/mp4',
62 > '.mpe': 'video/mpeg',
63 > '.mpeg': 'video/mpeg',
64 > '.mpg': 'video/mpeg',
65 > '.mpg4': 'video/mp4',
66 > '.mpga': 'audio/mpeg',
67 > '.oga': 'audio/ogg',
68 > '.ogg': 'audio/ogg',
69 > '.opus': 'audio/opus',
70 > '.ogv': 'video/ogg',
71 > '.png': 'image/png',
72 > '.psd': 'image/vnd.adobe.photoshop',
73 > '.qt': 'video/quicktime',
74 > '.spx': 'audio/ogg',
75 > '.svg': 'image/svg+xml',
76 > '.tga': 'image/x-tga',
77 > '.tif': 'image/tiff',
78 > '.tiff': 'image/tiff',
79 > '.wav': 'audio/x-wav',
80 > '.webm': 'video/webm',
81 > '.webp': 'image/webp',
82 > '.wma': 'audio/x-ms-wma',
83 > '.wmv': 'video/x-ms-wmv',
84 > '.woff': 'application/font-woff',
85 > };
86 >
87 > export function getMediaOrTextMime(path: string): string | undefined {
88 const ext = extname(path);
89 const textMime = mapExtToTextMimes[ext.toLowerCase()];
94 }
95 }
96 > mime.ts
97 > export function getMediaMime(path: string): string | undefined {
98 const ext = extname(path);
99 const mimeType = mapExtToMediaMimes[ext.toLowerCase()];
100 return Array.isArray(mimeType) ? mimeType[0] : mimeType;
101 }
102 > mime.ts
103 > export function getExtensionForMimeType(mimeType: string): string | undefined {
104 for (const extension in mapExtToMediaMimes) {
105 const value = mapExtToMediaMimes[extension];
111 return undefined;
112 }
113 > mime.ts
114 > const _simplePattern = /^(.+)\/(.+?)(;.+)?$/;
115 >
116 > export function normalizeMimeType(mimeType: string): string;
117 > export function normalizeMimeType(mimeType: string, strict: true): string | undefined;
118 > export function normalizeMimeType(mimeType: string, strict?: true): string | undefined {
119
120 const match = _simplePattern.exec(mimeType);
128 return `${match[1].toLowerCase()}/${match[2].toLowerCase()}${match[3] ?? ''}`;
129 }
130 > mime.ts
131 > /**
132 > * Whether the provided mime type is a text stream like `stdout`, `stderr`.
133 > */
134 > export function isTextStreamMime(mimeType: string) {
135 return ['application/vnd.code.notebook.stdout', 'application/vnd.code.notebook.stderr'].includes(mimeType);
136 }
src/vs/platform/userDataSync/common/userDataSyncMachines.ts 102 covered LOC · 15 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSyncMachines.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { Disposable } from '../../../base/common/lifecycle.js';
8 > import { isAndroid, isChrome, isEdge, isFirefox, isSafari, isWeb, Platform, platform, PlatformToString } from '../../../base/common/platform.js';
9 > import { escapeRegExpCharacters } from '../../../base/common/strings.js';
10 > import { localize } from '../../../nls.js';
11 > import { IEnvironmentService } from '../../environment/common/environment.js';
12 > import { IFileService } from '../../files/common/files.js';
13 > import { createDecorator } from '../../instantiation/common/instantiation.js';
14 > import { IProductService } from '../../product/common/productService.js';
15 > import { getServiceMachineId } from '../../externalServices/common/serviceMachineId.js';
16 > import { IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
17 > import { IUserData, IUserDataManifest, IUserDataSyncLogService, IUserDataSyncStoreService } from './userDataSync.js';
18 >
19 > export interface IMachineData {
20 > id: string;
21 > name: string;
22 > disabled?: boolean;
23 > platform?: string;
24 > }
25 >
26 > export interface IMachinesData {
27 > version: number;
28 > machines: IMachineData[];
29 > }
30 >
31 > export type IUserDataSyncMachine = Readonly<IMachineData> & { readonly isCurrent: boolean };
32 >
33 > export const IUserDataSyncMachinesService = createDecorator<IUserDataSyncMachinesService>('IUserDataSyncMachinesService');
34 > export interface IUserDataSyncMachinesService {
35 > _serviceBrand: undefined;
36 >
37 > readonly onDidChange: Event<void>;
38 >
39 > getMachines(manifest?: IUserDataManifest): Promise<IUserDataSyncMachine[]>;
40 >
41 > addCurrentMachine(manifest?: IUserDataManifest): Promise<void>;
42 > removeCurrentMachine(manifest?: IUserDataManifest): Promise<void>;
43 > renameMachine(machineId: string, name: string): Promise<void>;
44 > setEnablements(enbalements: [string, boolean][]): Promise<void>;
45 > }
46 >
47 > const currentMachineNameKey = 'sync.currentMachineName';
48 >
49 > const Safari = 'Safari';
50 > const Chrome = 'Chrome';
51 > const Edge = 'Edge';
52 > const Firefox = 'Firefox';
53 > const Android = 'Android';
54 >
55 > export function isWebPlatform(platform: string) {
56 switch (platform) {
57 case Safari:
65 return false;
66 }
68 function getPlatformName(): string {
69 if (isSafari) { return Safari; }
74 return PlatformToString(isWeb ? Platform.Web : platform);
75 }
77 > export class UserDataSyncMachinesService extends Disposable implements IUserDataSyncMachinesService {
78 >
79 > private static readonly VERSION = 1;
80 > private static readonly RESOURCE = 'machines';
81 >
82 > _serviceBrand: undefined;
83 >
84 > private readonly _onDidChange = this._register(new Emitter<void>());
85 > readonly onDidChange = this._onDidChange.event;
86 >
87 > private readonly currentMachineIdPromise: Promise<string>;
88 > private userData: IUserData | null = null;
89 >
90 > constructor(
91 > @IEnvironmentService environmentService: IEnvironmentService, userDataSyncMachines.ts
92 > @IFileService fileService: IFileService,
93 > @IStorageService private readonly storageService: IStorageService,
94 > @IUserDataSyncStoreService private readonly userDataSyncStoreService: IUserDataSyncStoreService,
95 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
96 > @IProductService private readonly productService: IProductService,
97 > ) {
98 > super();
99 > this.currentMachineIdPromise = getServiceMachineId(environmentService, fileService, storageService);
100 > }
102 > async getMachines(manifest?: IUserDataManifest): Promise<IUserDataSyncMachine[]> {
103 const currentMachineId = await this.currentMachineIdPromise;
104 const machineData = await this.readMachinesData(manifest);
105 return machineData.machines.map<IUserDataSyncMachine>(machine => ({ ...machine, ...{ isCurrent: machine.id === currentMachineId } }));
106 }
108 > async addCurrentMachine(manifest?: IUserDataManifest): Promise<void> {
109 const currentMachineId = await this.currentMachineIdPromise;
110 const machineData = await this.readMachinesData(manifest);
114 }
115 }
117 > async removeCurrentMachine(manifest?: IUserDataManifest): Promise<void> {
118 const currentMachineId = await this.currentMachineIdPromise;
119 const machineData = await this.readMachinesData(manifest);
124 }
125 }
127 > async renameMachine(machineId: string, name: string, manifest?: IUserDataManifest): Promise<void> {
128 const machineData = await this.readMachinesData(manifest);
129 const machine = machineData.machines.find(({ id }) => id === machineId);
137 }
138 }
140 > async setEnablements(enablements: [string, boolean][]): Promise<void> {
141 const machineData = await this.readMachinesData();
142 for (const [machineId, enabled] of enablements) {
148 await this.writeMachinesData(machineData);
149 }
151 > private computeCurrentMachineName(machines: IMachineData[]): string {
152 const previousName = this.storageService.get(currentMachineNameKey, StorageScope.APPLICATION);
153 if (previousName) {
168 return `${namePrefix} #${nameIndex + 1}`;
169 }
171 > private async readMachinesData(manifest?: IUserDataManifest): Promise<IMachinesData> {
172 this.userData = await this.readUserData(manifest);
173 const machinesData = this.parse(this.userData);
177 return machinesData;
178 }
180 > private async writeMachinesData(machinesData: IMachinesData): Promise<void> {
181 const content = JSON.stringify(machinesData);
182 const ref = await this.userDataSyncStoreService.writeResource(UserDataSyncMachinesService.RESOURCE, content, this.userData?.ref || null);
184 this._onDidChange.fire();
185 }
187 > private async readUserData(manifest?: IUserDataManifest): Promise<IUserData> {
188 if (this.userData) {
189
203 return this.userDataSyncStoreService.readResource(UserDataSyncMachinesService.RESOURCE, this.userData);
204 }
206 > private parse(userData: IUserData): IMachinesData {
207 if (userData.content !== null) {
208 try {
src/vs/platform/extensionManagement/common/extensionStorage.ts 100 covered LOC · 20 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensionStorage.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { createDecorator } from '../../instantiation/common/instantiation.js';
7 > import { Emitter, Event } from '../../../base/common/event.js';
8 > import { Disposable } from '../../../base/common/lifecycle.js';
9 > import { IProfileStorageValueChangeEvent, IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
10 > import { adoptToGalleryExtensionId, areSameExtensions, getExtensionId } from './extensionManagementUtil.js';
11 > import { IProductService } from '../../product/common/productService.js';
12 > import { distinct } from '../../../base/common/arrays.js';
13 > import { ILogService } from '../../log/common/log.js';
14 > import { IExtension } from '../../extensions/common/extensions.js';
15 > import { isString } from '../../../base/common/types.js';
16 > import { IStringDictionary } from '../../../base/common/collections.js';
17 > import { IExtensionManagementService, IGalleryExtension } from './extensionManagement.js';
18 >
19 > export interface IExtensionIdWithVersion {
20 > id: string;
21 > version: string;
22 > }
23 >
24 > export const IExtensionStorageService = createDecorator<IExtensionStorageService>('IExtensionStorageService');
25 >
26 > export interface IExtensionStorageService {
27 > readonly _serviceBrand: undefined;
28 >
29 > getExtensionState(extension: IExtension | IGalleryExtension | string, global: boolean): IStringDictionary<unknown> | undefined;
30 > getExtensionStateRaw(extension: IExtension | IGalleryExtension | string, global: boolean): string | undefined;
31 > setExtensionState(extension: IExtension | IGalleryExtension | string, state: object | undefined, global: boolean): void;
32 >
33 > readonly onDidChangeExtensionStorageToSync: Event<void>;
34 > setKeysForSync(extensionIdWithVersion: IExtensionIdWithVersion, keys: string[]): void;
35 > getKeysForSync(extensionIdWithVersion: IExtensionIdWithVersion): string[] | undefined;
36 >
37 > addToMigrationList(from: string, to: string): void;
38 > getSourceExtensionToMigrate(target: string): string | undefined;
39 > }
40 >
41 > const EXTENSION_KEYS_ID_VERSION_REGEX = /^extensionKeys\/([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;
42 >
43 > export class ExtensionStorageService extends Disposable implements IExtensionStorageService {
44 >
45 > readonly _serviceBrand: undefined;
46 >
47 > private static LARGE_STATE_WARNING_THRESHOLD = 512 * 1024;
48 >
49 > private static toKey(extension: IExtensionIdWithVersion): string {
50 return `extensionKeys/${adoptToGalleryExtensionId(extension.id)}@${extension.version}`;
51 }
53 > private static fromKey(key: string): IExtensionIdWithVersion | undefined {
54 const matches = EXTENSION_KEYS_ID_VERSION_REGEX.exec(key);
55 if (matches && matches[1]) {
58 return undefined;
59 }
61 > /* TODO @sandy081: This has to be done across all profiles */
62 > static async removeOutdatedExtensionVersions(extensionManagementService: IExtensionManagementService, storageService: IStorageService): Promise<void> {
63 const extensions = await extensionManagementService.getInstalled();
64 const extensionVersionsToRemove: string[] = [];
75 }
76 }
78 > private static readAllExtensionsWithKeysForSync(storageService: IStorageService): Map<string, string[]> {
79 > const extensionsWithKeysForSync = new Map<string, string[]>(); extensionStorage.ts
80 > const keys = storageService.keys(StorageScope.PROFILE, StorageTarget.MACHINE);
81 > for (const key of keys) {
82 const extensionIdWithVersion = ExtensionStorageService.fromKey(key);
83 if (extensionIdWithVersion) {
89 }
90 }
91 > return extensionsWithKeysForSync; extensionStorage.ts
92 > }
94 > private readonly _onDidChangeExtensionStorageToSync = this._register(new Emitter<void>());
95 > readonly onDidChangeExtensionStorageToSync = this._onDidChangeExtensionStorageToSync.event;
96 >
97 > private readonly extensionsWithKeysForSync: Map<string, string[]>;
98 >
99 > constructor(
100 > @IStorageService private readonly storageService: IStorageService, extensionStorage.ts
101 > @IProductService private readonly productService: IProductService,
102 > @ILogService private readonly logService: ILogService,
103 > ) {
104 > super();
105 > this.extensionsWithKeysForSync = ExtensionStorageService.readAllExtensionsWithKeysForSync(storageService);
106 > this._register(this.storageService.onDidChangeValue(StorageScope.PROFILE, undefined, this._store)(e => this.onDidChangeStorageValue(e)));
107 > }
109 > private onDidChangeStorageValue(e: IProfileStorageValueChangeEvent): void {
110
111 // State of extension with keys for sync has changed
131 }
132 }
134 > private getExtensionId(extension: IExtension | IGalleryExtension | string): string {
135 if (isString(extension)) {
136 return extension;
140 return getExtensionId(publisher, name);
141 }
143 > getExtensionState(extension: IExtension | IGalleryExtension | string, global: boolean): IStringDictionary<unknown> | undefined {
144 const extensionId = this.getExtensionId(extension);
145 const jsonValue = this.getExtensionStateRaw(extension, global);
156 return undefined;
157 }
159 > getExtensionStateRaw(extension: IExtension | IGalleryExtension | string, global: boolean): string | undefined {
160 const extensionId = this.getExtensionId(extension);
161 const rawState = this.storageService.get(extensionId, global ? StorageScope.PROFILE : StorageScope.WORKSPACE);
167 return rawState;
168 }
170 > setExtensionState(extension: IExtension | IGalleryExtension | string, state: IStringDictionary<unknown> | undefined, global: boolean): void {
171 const extensionId = this.getExtensionId(extension);
172 if (state === undefined) {
176 }
177 }
179 > setKeysForSync(extensionIdWithVersion: IExtensionIdWithVersion, keys: string[]): void {
180 this.storageService.store(ExtensionStorageService.toKey(extensionIdWithVersion), JSON.stringify(keys), StorageScope.PROFILE, StorageTarget.MACHINE);
181 }
183 > getKeysForSync(extensionIdWithVersion: IExtensionIdWithVersion): string[] | undefined {
184 const extensionKeysForSyncFromProduct = this.productService.extensionSyncedKeys?.[extensionIdWithVersion.id.toLowerCase()];
185 const extensionKeysForSyncFromStorageValue = this.storageService.get(ExtensionStorageService.toKey(extensionIdWithVersion), StorageScope.PROFILE);
190 : (extensionKeysForSyncFromStorage || extensionKeysForSyncFromProduct);
191 }
193 > addToMigrationList(from: string, to: string): void {
194 if (from !== to) {
195 // remove the duplicates
199 }
200 }
202 > getSourceExtensionToMigrate(toExtensionId: string): string | undefined {
203 const entry = this.migrationList.find(([, to]) => toExtensionId === to);
204 return entry ? entry[0] : undefined;
205 }
207 > private get migrationList(): [string, string][] {
208 const value = this.storageService.get('extensionStorage.migrationList', StorageScope.APPLICATION, '[]');
209 try {
215 return [];
216 }
218 > private set migrationList(migrationList: [string, string][]) {
219 if (migrationList.length) {
220 this.storageService.store('extensionStorage.migrationList', JSON.stringify(migrationList), StorageScope.APPLICATION, StorageTarget.MACHINE);
src/vs/platform/jsonschemas/common/jsonContributionRegistry.ts 100 covered LOC · 9 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- jsonContributionRegistry.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { getCompressedContent, IJSONSchema } from '../../../base/common/jsonSchema.js';
8 > import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../base/common/lifecycle.js';
9 > import * as platform from '../../registry/common/platform.js';
10 >
11 > export const Extensions = {
12 > JSONContribution: 'base.contributions.json'
13 > };
14 >
15 > export interface ISchemaContributions {
16 > schemas: { [id: string]: IJSONSchema };
17 > }
18 >
19 > export interface IJSONContributionRegistry {
20 >
21 > readonly onDidChangeSchema: Event<string>;
22 > readonly onDidChangeSchemaAssociations: Event<void>;
23 >
24 > /**
25 > * Register a schema to the registry.
26 > */
27 > registerSchema(uri: string, unresolvedSchemaContent: IJSONSchema, store?: DisposableStore): void;
28 >
29 > registerSchemaAssociation(uri: string, glob: string): IDisposable;
30 >
31 > /**
32 > * Notifies all listeners that the content of the given schema has changed.
33 > * @param uri The id of the schema
34 > */
35 > notifySchemaChanged(uri: string): void;
36 >
37 > /**
38 > * Get all schemas
39 > */
40 > getSchemaContributions(): ISchemaContributions;
41 >
42 > getSchemaAssociations(): { [uri: string]: string[] };
43 >
44 > /**
45 > * Gets the (compressed) content of the schema with the given schema ID (if any)
46 > * @param uri The id of the schema
47 > */
48 > getSchemaContent(uri: string): string | undefined;
49 >
50 > /**
51 > * Returns true if there's a schema that matches the given schema ID
52 > * @param uri The id of the schema
53 > */
54 > hasSchemaContent(uri: string): boolean;
55 > }
56 >
57 >
58 >
59 > function normalizeId(id: string) {
60 > if (id.length > 0 && id.charAt(id.length - 1) === '#') {
61 return id.substring(0, id.length - 1);
62 }
63 > return id; jsonContributionRegistry.ts
64 > }
65 >
66 >
67 >
68 > class JSONContributionRegistry extends Disposable implements IJSONContributionRegistry {
69 >
70 > private readonly schemasById: { [id: string]: IJSONSchema } = {};
71 > private readonly schemaAssociations: { [uri: string]: string[] } = {};
72 >
73 > private readonly _onDidChangeSchema = this._register(new Emitter<string>());
74 > readonly onDidChangeSchema: Event<string> = this._onDidChangeSchema.event;
75 >
76 > private readonly _onDidChangeSchemaAssociations = this._register(new Emitter<void>());
77 > readonly onDidChangeSchemaAssociations: Event<void> = this._onDidChangeSchemaAssociations.event;
78 >
79 > public registerSchema(uri: string, unresolvedSchemaContent: IJSONSchema, store?: DisposableStore): void {
80 > const normalizedUri = normalizeId(uri);
81 > this.schemasById[normalizedUri] = unresolvedSchemaContent;
82 > this._onDidChangeSchema.fire(uri);
83 >
84 > if (store) {
85 store.add(toDisposable(() => {
86 delete this.schemasById[normalizedUri];
88 }));
89 }
91 >
92 > public registerSchemaAssociation(uri: string, glob: string): IDisposable {
93 const normalizedUri = normalizeId(uri);
94 if (!this.schemaAssociations[normalizedUri]) {
114 });
115 }
117 > public notifySchemaChanged(uri: string): void {
118 this._onDidChangeSchema.fire(uri);
119 }
121 > public getSchemaContributions(): ISchemaContributions {
122 return {
123 schemas: this.schemasById,
124 };
125 }
127 > public getSchemaContent(uri: string): string | undefined {
128 const schema = this.schemasById[uri];
129 return schema ? getCompressedContent(schema) : undefined;
130 }
132 > public hasSchemaContent(uri: string): boolean {
133 return !!this.schemasById[uri];
134 }
136 > public getSchemaAssociations(): { [uri: string]: string[] } {
137 return this.schemaAssociations;
138 }
140 > }
141 >
142 > const jsonContributionRegistry = new JSONContributionRegistry();
143 > platform.Registry.add(Extensions.JSONContribution, jsonContributionRegistry);
src/vs/base/common/arraysFind.ts 95 covered LOC · 16 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- arraysFind.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Comparator } from './arrays.js';
7 >
8 > export function findLast<T, R extends T>(array: readonly T[], predicate: (item: T, index: number) => item is R, fromIndex?: number): R | undefined;
9 > export function findLast<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex?: number): T | undefined;
10 > export function findLast<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = array.length - 1): T | undefined {
11 const idx = findLastIdx(array, predicate, fromIndex);
12 if (idx === -1) {
15 return array[idx];
16 }
18 > export function findLastIdx<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = array.length - 1): number {
19 for (let i = fromIndex; i >= 0; i--) {
20 const element = array[i];
27 return -1;
28 }
30 > export function findFirst<T, R extends T>(array: readonly T[], predicate: (item: T, index: number) => item is R, fromIndex?: number): R | undefined;
31 > export function findFirst<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex?: number): T | undefined;
32 > export function findFirst<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = 0): T | undefined {
33 const idx = findFirstIdx(array, predicate, fromIndex);
34 if (idx === -1) {
37 return array[idx];
38 }
40 > export function findFirstIdx<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = 0): number {
41 for (let i = fromIndex; i < array.length; i++) {
42 const element = array[i];
49 return -1;
50 }
52 > /**
53 > * Finds the last item where predicate is true using binary search.
54 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
55 > *
56 > * @returns `undefined` if no item matches, otherwise the last item that matches the predicate.
57 > */
58 > export function findLastMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean): T | undefined {
59 const idx = findLastIdxMonotonous(array, predicate);
60 return idx === -1 ? undefined : array[idx];
61 }
63 > /**
64 > * Finds the last item where predicate is true using binary search.
65 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
66 > *
67 > * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate.
68 > */
69 > export function findLastIdxMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {
70 let i = startIdx;
71 let j = endIdxEx;
80 return i - 1;
81 }
83 > /**
84 > * Finds the first item where predicate is true using binary search.
85 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!
86 > *
87 > * @returns `undefined` if no item matches, otherwise the first item that matches the predicate.
88 > */
89 > export function findFirstMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean): T | undefined {
90 const idx = findFirstIdxMonotonousOrArrLen(array, predicate);
91 return idx === array.length ? undefined : array[idx];
92 }
94 > /**
95 > * Finds the first item where predicate is true using binary search.
96 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!
97 > *
98 > * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate.
99 > */
100 > export function findFirstIdxMonotonousOrArrLen<T>(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {
101 let i = startIdx;
102 let j = endIdxEx;
111 return i;
112 }
114 > export function findFirstIdxMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {
115 const idx = findFirstIdxMonotonousOrArrLen(array, predicate, startIdx, endIdxEx);
116 return idx === array.length ? -1 : idx;
117 }
119 > /**
120 > * Use this when
121 > * * You have a sorted array
122 > * * You query this array with a monotonous predicate to find the last item that has a certain property.
123 > * * You query this array multiple times with monotonous predicates that get weaker and weaker.
124 > */
125 > export class MonotonousArray<T> {
126 > public static assertInvariants = false;
127 >
128 > private _findLastMonotonousLastIdx = 0;
129 > private _prevFindLastPredicate: ((item: T) => boolean) | undefined;
130 >
131 > constructor(private readonly _array: readonly T[]) {
132 }
134 > /**
135 > * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
136 > * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.
137 > */
138 > findLastMonotonous(predicate: (item: T) => boolean): T | undefined {
139 if (MonotonousArray.assertInvariants) {
140 if (this._prevFindLastPredicate) {
152 return idx === -1 ? undefined : this._array[idx];
153 }
154 > } arraysFind.ts
155 >
156 > /**
157 > * Returns the first item that is equal to or greater than every other item.
158 > */
159 > export function findFirstMax<T>(array: readonly T[], comparator: Comparator<T>): T | undefined {
160 if (array.length === 0) {
161 return undefined;
171 return max;
172 }
174 > /**
175 > * Returns the last item that is equal to or greater than every other item.
176 > */
177 > export function findLastMax<T>(array: readonly T[], comparator: Comparator<T>): T | undefined {
178 if (array.length === 0) {
179 return undefined;
189 return max;
190 }
192 > /**
193 > * Returns the first item that is equal to or less than every other item.
194 > */
195 > export function findFirstMin<T>(array: readonly T[], comparator: Comparator<T>): T | undefined {
196 return findFirstMax(array, (a, b) => -comparator(a, b));
197 }
199 > export function findMaxIdx<T>(array: readonly T[], comparator: Comparator<T>): number {
200 if (array.length === 0) {
201 return -1;
211 return maxIdx;
212 }
214 > /**
215 > * Returns the first mapped value of the array which is not undefined.
216 > */
217 > export function mapFindFirst<T, R>(items: Iterable<T>, mapFn: (value: T) => R | undefined): R | undefined {
218 for (const value of items) {
219 const mapped = mapFn(value);
src/vs/base/test/common/virtualScheduling/virtualClock.ts 94 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- virtualClock.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { compareBy, numberComparator, tieBreakComparators } from '../../../common/arrays.js';
7 > import { Emitter } from '../../../common/event.js';
8 > import { IDisposable } from '../../../common/lifecycle.js';
9 > import { Trace } from './trace.js';
10 >
11 > export type VirtualTime = number;
12 >
13 > /** Debug source description for an event. */
14 > export interface EventSource {
15 > toString(): string;
16 > readonly stackTrace?: string;
17 > }
18 >
19 > /**
20 > * A unit of work scheduled at a point in virtual time.
21 > *
22 > * Timer callbacks are events. External completions (e.g. fake fs reads) can
23 > * also be modelled as events whose virtual completion time is chosen by a
24 > * scheduling policy — to the {@link VirtualClock} they are indistinguishable.
25 > */
26 > export interface VirtualEvent {
27 > readonly time: VirtualTime;
28 > readonly source: EventSource;
29 > readonly trace?: Trace;
30 > /**
31 > * Hint for the {@link Embedding}: this event prefers to run on a real
32 > * animation frame (e.g. so DOM measurements after it observe a real
33 > * reflow). Pure-time tests can ignore the hint.
34 > */
35 > readonly preferRealAnimationFrame?: boolean;
36 > run(): void;
37 > }
38 >
39 > interface QueuedEvent extends VirtualEvent { readonly id: number }
40 >
41 > const eventComparator = tieBreakComparators<QueuedEvent>(
42 > compareBy(e => e.time, numberComparator),
43 > compareBy(e => e.id, numberComparator),
44 > );
45 >
46 > /**
47 > * A pure data structure: a virtual clock + a priority queue of events.
48 > *
49 > * The clock has no concept of "real time". It is advanced exclusively by
50 > * {@link runNext}, which sets `now` to the next event's `time` before running
51 > * it. The {@link VirtualTimeProcessor} is the only intended driver, but the
52 > * clock is useful in isolation (e.g. for unit-testing a scheduler or for
53 > * stepping a scenario manually).
54 > */
55 > export class VirtualClock {
56 > private _now: VirtualTime;
57 > private _idCounter = 0;
58 > private readonly _queue = new SimplePriorityQueue<QueuedEvent>(eventComparator);
59 > private readonly _onEventScheduled = new Emitter<VirtualEvent>();
60 >
61 > public readonly onEventScheduled = this._onEventScheduled.event;
62 >
63 > constructor(startTime: VirtualTime = 0) {
64 this._now = startTime;
65 }
67 > get now(): VirtualTime { return this._now; }
68 > get hasEvents(): boolean { return this._queue.length > 0; }
69 >
70 > schedule(event: VirtualEvent): IDisposable {
71 if (event.time < this._now) {
72 throw new Error(`Scheduled time (${event.time}) must be >= now (${this._now}).`);
77 return { dispose: () => this._queue.remove(queued) };
78 }
80 > peekNext(): VirtualEvent | undefined { return this._queue.getMin(); }
81 >
82 > runNext(): VirtualEvent | undefined {
83 const e = this._queue.removeMin();
84 if (e) {
88 return e;
89 }
91 > getEvents(): readonly VirtualEvent[] { return this._queue.toSortedArray(); }
92 > }
93 >
94 > class SimplePriorityQueue<T> {
95 > private _items: T[] = [];
96 > private _sorted = true;
97 >
98 > constructor(private readonly _compare: (a: T, b: T) => number) { }
99 >
100 > get length(): number { return this._items.length; }
101 >
102 > add(value: T): void {
103 this._items.push(value);
104 this._sorted = false;
105 }
107 > remove(value: T): void {
108 const i = this._items.indexOf(value);
109 if (i !== -1) { this._items.splice(i, 1); }
110 }
112 > getMin(): T | undefined { this._ensureSorted(); return this._items[0]; }
113 > removeMin(): T | undefined { this._ensureSorted(); return this._items.shift(); }
114 > toSortedArray(): T[] { this._ensureSorted(); return [...this._items]; }
115 >
116 > private _ensureSorted(): void {
117 if (this._sorted) { return; }
118 this._items.sort(this._compare);
119 this._sorted = true;
120 }
121 > } virtualClock.ts
src/vs/base/common/cache.ts 88 covered LOC · 9 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- cache.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken, CancellationTokenSource } from './cancellation.js';
7 > import { IDisposable } from './lifecycle.js';
8 >
9 > export interface CacheResult<T> extends IDisposable {
10 > promise: Promise<T>;
11 > }
12 >
13 > export class Cache<T> {
14 >
15 > private result: CacheResult<T> | null = null;
16 > constructor(private task: (ct: CancellationToken) => Promise<T>) { }
17 >
18 > get(): CacheResult<T> {
19 if (this.result) {
20 return this.result;
35 return this.result;
36 }
37 > } cache.ts
38 >
39 > export function identity<T>(t: T): T {
40 return t;
41 }
42 > cache.ts
43 > interface ICacheOptions<TArg> {
44 > /**
45 > * The cache key is used to identify the cache entry.
46 > * Strict equality is used to compare cache keys.
47 > */
48 > getCacheKey: (arg: TArg) => unknown;
49 > }
50 >
51 > /**
52 > * Uses a LRU cache to make a given parametrized function cached.
53 > * Caches just the last key/value.
54 > */
55 > export class LRUCachedFunction<TArg, TComputed> {
56 > private lastCache: TComputed | undefined = undefined;
57 > private lastArgKey: unknown | undefined = undefined;
58 >
59 > private readonly _fn: (arg: TArg) => TComputed;
60 > private readonly _computeKey: (arg: TArg) => unknown;
61 >
62 > constructor(fn: (arg: TArg) => TComputed);
63 > constructor(options: ICacheOptions<TArg>, fn: (arg: TArg) => TComputed);
64 > constructor(arg1: ICacheOptions<TArg> | ((arg: TArg) => TComputed), arg2?: (arg: TArg) => TComputed) {
65 > if (typeof arg1 === 'function') {
66 > this._fn = arg1;
67 > this._computeKey = identity;
68 > } else {
69 this._fn = arg2!;
70 this._computeKey = arg1.getCacheKey;
71 }
72 > } cache.ts
73 >
74 > public get(arg: TArg): TComputed {
75 const key = this._computeKey(arg);
76 if (this.lastArgKey !== key) {
80 return this.lastCache!;
81 }
82 > } cache.ts
83 >
84 > /**
85 > * Uses an unbounded cache to memoize the results of the given function.
86 > */
87 > export class CachedFunction<TArg, TComputed> {
88 > private readonly _map = new Map<TArg, TComputed>();
89 > private readonly _map2 = new Map<unknown, TComputed>();
90 > public get cachedValues(): ReadonlyMap<TArg, TComputed> {
91 > return this._map;
92 > }
93 >
94 > private readonly _fn: (arg: TArg) => TComputed;
95 > private readonly _computeKey: (arg: TArg) => unknown;
96 >
97 > constructor(fn: (arg: TArg) => TComputed);
98 > constructor(options: ICacheOptions<TArg>, fn: (arg: TArg) => TComputed);
99 > constructor(arg1: ICacheOptions<TArg> | ((arg: TArg) => TComputed), arg2?: (arg: TArg) => TComputed) {
100 if (typeof arg1 === 'function') {
101 this._fn = arg1;
106 }
107 }
108 > cache.ts
109 > public get(arg: TArg): TComputed {
110 const key = this._computeKey(arg);
111 if (this._map2.has(key)) {
118 return value;
119 }
120 > } cache.ts
121 >
122 > /**
123 > * Uses an unbounded cache to memoize the results of the given function.
124 > */
125 > export class WeakCachedFunction<TArg, TComputed> {
126 > private readonly _map = new WeakMap<WeakKey, TComputed>();
127 >
128 > private readonly _fn: (arg: TArg) => TComputed;
129 > private readonly _computeKey: (arg: TArg) => unknown;
130 >
131 > constructor(fn: (arg: TArg) => TComputed);
132 > constructor(options: ICacheOptions<TArg>, fn: (arg: TArg) => TComputed);
133 > constructor(arg1: ICacheOptions<TArg> | ((arg: TArg) => TComputed), arg2?: (arg: TArg) => TComputed) {
134 if (typeof arg1 === 'function') {
135 this._fn = arg1;
140 }
141 }
142 > cache.ts
143 > public get(arg: TArg): TComputed {
144 const key = this._computeKey(arg) as WeakKey;
145 if (this._map.has(key)) {
151 return value;
152 }
153 > } cache.ts
src/vs/platform/extensionManagement/common/extensionEnablementService.ts 88 covered LOC · 25 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensionEnablementService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { Disposable } from '../../../base/common/lifecycle.js';
8 > import { isUndefinedOrNull } from '../../../base/common/types.js';
9 > import { DISABLED_EXTENSIONS_STORAGE_PATH, IExtensionIdentifier, IExtensionManagementService, IGlobalExtensionEnablementService, InstallOperation } from './extensionManagement.js';
10 > import { areSameExtensions } from './extensionManagementUtil.js';
11 > import { IProfileStorageValueChangeEvent, IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
12 >
13 > export class GlobalExtensionEnablementService extends Disposable implements IGlobalExtensionEnablementService {
14 >
15 > declare readonly _serviceBrand: undefined;
16 >
17 > private _onDidChangeEnablement = this._register(new Emitter<{ readonly extensions: IExtensionIdentifier[]; readonly source?: string }>());
18 > readonly onDidChangeEnablement: Event<{ readonly extensions: IExtensionIdentifier[]; readonly source?: string }> = this._onDidChangeEnablement.event;
19 > private readonly storageManager: StorageManager;
20 >
21 > constructor(
22 > @IStorageService storageService: IStorageService, extensionEnablementService.ts
23 > @IExtensionManagementService extensionManagementService: IExtensionManagementService,
24 > ) {
25 > super();
26 > this.storageManager = this._register(new StorageManager(storageService));
27 > this._register(this.storageManager.onDidChange(extensions => this._onDidChangeEnablement.fire({ extensions, source: 'storage' })));
28 > this._register(extensionManagementService.onDidInstallExtensions(e => e.forEach(({ local, operation }) => {
29 if (local && operation === InstallOperation.Migrate) {
30 this._removeFromDisabledExtensions(local.identifier); /* Reset migrated extensions */
31 }
33 > }
35 > async enableExtension(extension: IExtensionIdentifier, source?: string): Promise<boolean> {
36 if (this._removeFromDisabledExtensions(extension)) {
37 this._onDidChangeEnablement.fire({ extensions: [extension], source });
40 return false;
41 }
43 > async disableExtension(extension: IExtensionIdentifier, source?: string): Promise<boolean> {
44 if (this._addToDisabledExtensions(extension)) {
45 this._onDidChangeEnablement.fire({ extensions: [extension], source });
48 return false;
49 }
51 > getDisabledExtensions(): IExtensionIdentifier[] {
52 > return this._getExtensions(DISABLED_EXTENSIONS_STORAGE_PATH); extensionEnablementService.ts
53 > }
55 > async getDisabledExtensionsAsync(): Promise<IExtensionIdentifier[]> {
56 return this.getDisabledExtensions();
57 }
59 > private _addToDisabledExtensions(identifier: IExtensionIdentifier): boolean {
60 const disabledExtensions = this.getDisabledExtensions();
61 if (disabledExtensions.every(e => !areSameExtensions(e, identifier))) {
66 return false;
67 }
69 > private _removeFromDisabledExtensions(identifier: IExtensionIdentifier): boolean {
70 const disabledExtensions = this.getDisabledExtensions();
71 for (let index = 0; index < disabledExtensions.length; index++) {
79 return false;
80 }
82 > private _setDisabledExtensions(disabledExtensions: IExtensionIdentifier[]): void {
83 this._setExtensions(DISABLED_EXTENSIONS_STORAGE_PATH, disabledExtensions);
84 }
86 > private _getExtensions(storageId: string): IExtensionIdentifier[] {
87 > return this.storageManager.get(storageId, StorageScope.PROFILE); extensionEnablementService.ts
88 > }
90 > private _setExtensions(storageId: string, extensions: IExtensionIdentifier[]): void {
91 this.storageManager.set(storageId, extensions, StorageScope.PROFILE);
92 }
94 > }
95 >
96 > export class StorageManager extends Disposable {
97 >
98 > private storage: { [key: string]: string } = Object.create(null);
99 >
100 > private _onDidChange: Emitter<IExtensionIdentifier[]> = this._register(new Emitter<IExtensionIdentifier[]>());
101 > readonly onDidChange: Event<IExtensionIdentifier[]> = this._onDidChange.event;
102 >
103 > constructor(private storageService: IStorageService) {
105 > this._register(storageService.onDidChangeValue(StorageScope.PROFILE, undefined, this._store)(e => this.onDidStorageChange(e)));
106 > }
108 > get(key: string, scope: StorageScope): IExtensionIdentifier[] {
109 > let value: string; extensionEnablementService.ts
110 > if (scope === StorageScope.PROFILE) {
111 > if (isUndefinedOrNull(this.storage[key])) {
112 > this.storage[key] = this._get(key, scope);
113 > }
114 > value = this.storage[key];
115 > } else {
116 value = this._get(key, scope);
117 }
118 > return JSON.parse(value); extensionEnablementService.ts
119 > }
121 > set(key: string, value: IExtensionIdentifier[], scope: StorageScope): void {
122 const newValue: string = JSON.stringify(value.map(({ id, uuid }): IExtensionIdentifier => ({ id, uuid })));
123 const oldValue = this._get(key, scope);
133 }
134 }
136 > private onDidStorageChange(storageChangeEvent: IProfileStorageValueChangeEvent): void {
137 if (!isUndefinedOrNull(this.storage[storageChangeEvent.key])) {
138 const newValue = this._get(storageChangeEvent.key, storageChangeEvent.scope);
src/vs/base/common/performance.ts 86 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- performance.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import type { INodeProcess } from './platform.js';
7 >
8 > function _definePolyfillMarks(timeOrigin?: number) {
9 > const _data: [string?, number?] = [];
10 > if (typeof timeOrigin === 'number') {
11 > _data.push('code/timeOrigin', timeOrigin);
12 > }
13 >
14 > function mark(name: string, markOptions?: { startTime?: number }) {
15 > _data.push(name, markOptions?.startTime ?? Date.now()); performance.ts
16 > }
17 > function getMarks() { performance.ts
18 const result = [];
19 for (let i = 0; i < _data.length; i += 2) {
25 return result;
26 }
27 > function clearMarks(name?: string) { performance.ts
28 if (typeof name === 'undefined') {
29 const hasTimeOrigin = _data.length >= 2 && _data[0] === 'code/timeOrigin';
41 }
42 }
43 > return { mark, getMarks, clearMarks }; performance.ts
44 > }
45 >
46 > declare const process: INodeProcess;
47 >
48 > interface IPerformanceEntry {
49 > readonly name: string;
50 > readonly startTime: number;
51 > }
52 >
53 > interface IPerformanceTiming {
54 > readonly navigationStart?: number;
55 > readonly redirectStart?: number;
56 > readonly fetchStart?: number;
57 > }
58 >
59 > interface IPerformance {
60 > mark(name: string, markOptions?: { startTime?: number }): void;
61 > clearMarks(name?: string): void;
62 > getEntriesByType(type: string): IPerformanceEntry[];
63 > readonly timeOrigin: number;
64 > readonly timing: IPerformanceTiming;
65 > readonly nodeTiming?: any;
66 > }
67 >
68 > declare const performance: IPerformance;
69 >
70 > function _define() {
71 >
72 > // Identify browser environment when following property is not present
73 > // https://nodejs.org/dist/latest-v16.x/docs/api/perf_hooks.html#performancenodetiming
74 > // @ts-ignore
75 > if (typeof performance === 'object' && typeof performance.mark === 'function' && !performance.nodeTiming) {
76 // in a browser context, reuse performance-util
77
109 }
110
111 > } else if (typeof process === 'object') { performance.ts
112 > // node.js: use the normal polyfill but add the timeOrigin
113 > // from the node perf_hooks API as very first mark
114 > const timeOrigin = performance?.timeOrigin;
115 > return _definePolyfillMarks(timeOrigin);
116 >
117 > } else {
118 // unknown environment
119 console.trace('perf-util loaded in UNKNOWN environment');
120 return _definePolyfillMarks();
121 }
122 > } performance.ts
123 >
124 > function _factory(sharedObj: any) {
125 > if (!sharedObj.MonacoPerformanceMarks) {
126 > sharedObj.MonacoPerformanceMarks = _define();
127 > }
128 > return sharedObj.MonacoPerformanceMarks;
129 > }
130 >
131 > const perf = _factory(globalThis);
132 >
133 > export const mark: (name: string, markOptions?: { startTime?: number }) => void = perf.mark;
134 >
135 > /**
136 > * Clears performance marks. If a name is given, only marks with that exact
137 > * name are removed. If no name is given, all marks are removed.
138 > */
139 > export const clearMarks: (name?: string) => void = perf.clearMarks;
140 >
141 > export interface PerformanceMark {
142 > readonly name: string;
143 > readonly startTime: number;
144 > }
145 >
146 > /**
147 > * Returns all marks, sorted by `startTime`.
148 > */
149 > export const getMarks: () => PerformanceMark[] = perf.getMarks;
src/vs/platform/meteredConnection/common/meteredConnection.ts 86 covered LOC · 9 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- meteredConnection.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { Disposable } from '../../../base/common/lifecycle.js';
8 > import { IConfigurationService } from '../../configuration/common/configuration.js';
9 > import { createDecorator } from '../../instantiation/common/instantiation.js';
10 >
11 > export const IMeteredConnectionService = createDecorator<IMeteredConnectionService>('meteredConnectionService');
12 >
13 > /**
14 > * Service to report on metered connection status.
15 > */
16 > export interface IMeteredConnectionService {
17 > readonly _serviceBrand: undefined;
18 >
19 > /**
20 > * Whether the current network connection is metered.
21 > * Always returns `false` if the `network.meteredConnection` setting is `off`.
22 > * Always returns `true` if the `network.meteredConnection` setting is `on`.
23 > */
24 > readonly isConnectionMetered: boolean;
25 >
26 > /**
27 > * Event that fires when the metered connection status changes.
28 > */
29 > readonly onDidChangeIsConnectionMetered: Event<boolean>;
30 > }
31 >
32 > export const METERED_CONNECTION_SETTING_KEY = 'network.meteredConnection';
33 >
34 > export type MeteredConnectionSettingValue = 'on' | 'off' | 'auto';
35 >
36 > /**
37 > * Network Information API
38 > * See https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API
39 > */
40 > export interface NetworkInformation {
41 > saveData?: boolean;
42 > metered?: boolean;
43 > effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';
44 > addEventListener(type: 'change', listener: () => void): void;
45 > removeEventListener(type: 'change', listener: () => void): void;
46 > }
47 >
48 > /**
49 > * Extended Navigator interface for Network Information API
50 > */
51 > export interface NavigatorWithConnection {
52 > readonly connection?: NetworkInformation;
53 > }
54 >
55 > /**
56 > * Check if the current network connection is metered according to the Network Information API.
57 > */
58 > export function getIsBrowserConnectionMetered() {
59 const connection = (navigator as NavigatorWithConnection).connection;
60 if (!connection) {
69 return effectiveType === '2g' || effectiveType === 'slow-2g';
70 }
72 > /**
73 > * Abstract base class for metered connection services.
74 > */
75 > export abstract class AbstractMeteredConnectionService extends Disposable implements IMeteredConnectionService {
76 > declare readonly _serviceBrand: undefined;
77 >
78 > private readonly _onDidChangeIsConnectionMetered = this._register(new Emitter<boolean>());
79 > public readonly onDidChangeIsConnectionMetered = this._onDidChangeIsConnectionMetered.event;
80 >
81 > private _isConnectionMetered: boolean;
82 > private _isBrowserConnectionMetered: boolean;
83 > private _meteredConnectionSetting: MeteredConnectionSettingValue;
84 >
85 > constructor(configurationService: IConfigurationService, isBrowserConnectionMetered: boolean) {
86 super();
87
100 }));
101 }
103 > public get isConnectionMetered(): boolean {
104 return this._isConnectionMetered;
105 }
107 > protected get isBrowserConnectionMetered(): boolean {
108 return this._isBrowserConnectionMetered;
109 }
111 > public setIsBrowserConnectionMetered(value: boolean) {
112 if (value !== this._isBrowserConnectionMetered) {
113 this._isBrowserConnectionMetered = value;
115 }
116 }
118 > protected onChangeBrowserConnection() {
119 this.onUpdated();
120 }
122 > protected onUpdated() {
123 const value = this._meteredConnectionSetting === 'on' || (this._meteredConnectionSetting !== 'off' && this._isBrowserConnectionMetered);
124 if (value !== this._isConnectionMetered) {
src/vs/platform/extensionManagement/common/extensionManagementUtil.ts 82 covered LOC · 17 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensionManagementUtil.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { compareIgnoreCase } from '../../../base/common/strings.js';
7 > import { IExtensionIdentifier, IGalleryExtension, ILocalExtension, MaliciousExtensionInfo, getTargetPlatform } from './extensionManagement.js';
8 > import { ExtensionIdentifier, IExtension, TargetPlatform, UNDEFINED_PUBLISHER } from '../../extensions/common/extensions.js';
9 > import { IFileService } from '../../files/common/files.js';
10 > import { isLinux, platform } from '../../../base/common/platform.js';
11 > import { URI } from '../../../base/common/uri.js';
12 > import { getErrorMessage } from '../../../base/common/errors.js';
13 > import { ILogService } from '../../log/common/log.js';
14 > import { arch } from '../../../base/common/process.js';
15 > import { TelemetryTrustedValue } from '../../telemetry/common/telemetryUtils.js';
16 > import { isString } from '../../../base/common/types.js';
17 >
18 > export function areSameExtensions(a: IExtensionIdentifier, b: IExtensionIdentifier): boolean {
19 if (a.uuid && b.uuid) {
20 return a.uuid === b.uuid;
25 return compareIgnoreCase(a.id, b.id) === 0;
26 }
28 > const ExtensionKeyRegex = /^([^.]+\..+)-(\d+\.\d+\.\d+)(-(.+))?$/;
29 >
30 > export class ExtensionKey {
31 >
32 > static create(extension: IExtension | IGalleryExtension): ExtensionKey {
33 > const version = (extension as IExtension).manifest ? (extension as IExtension).manifest.version : (extension as IGalleryExtension).version;
34 > const targetPlatform = (extension as IExtension).manifest ? (extension as IExtension).targetPlatform : (extension as IGalleryExtension).properties.targetPlatform;
35 > return new ExtensionKey(extension.identifier, version, targetPlatform);
36 > }
37 >
38 > static parse(key: string): ExtensionKey | null {
39 const matches = ExtensionKeyRegex.exec(key);
40 return matches && matches[1] && matches[2] ? new ExtensionKey({ id: matches[1] }, matches[2], matches[4] as TargetPlatform || undefined) : null;
41 }
43 > readonly id: string;
44 >
45 > constructor(
46 readonly identifier: IExtensionIdentifier,
47 readonly version: string,
50 this.id = identifier.id;
51 }
53 > toString(): string {
54 return `${this.id}-${this.version}${this.targetPlatform !== TargetPlatform.UNDEFINED ? `-${this.targetPlatform}` : ''}`;
55 }
57 > equals(o: unknown): boolean {
58 if (!(o instanceof ExtensionKey)) {
59 return false;
61 return areSameExtensions(this, o) && this.version === o.version && this.targetPlatform === o.targetPlatform;
62 }
64 >
65 > const EXTENSION_IDENTIFIER_WITH_VERSION_REGEX = /^([^.]+\..+)@((prerelease)|(\d+\.\d+\.\d+(-.*)?))$/;
66 > export function getIdAndVersion(id: string): [string, string | undefined] {
67 const matches = EXTENSION_IDENTIFIER_WITH_VERSION_REGEX.exec(id);
68 if (matches && matches[1]) {
71 return [adoptToGalleryExtensionId(id), undefined];
72 }
74 > export function getExtensionId(publisher: string, name: string): string {
75 return `${publisher}.${name}`;
76 }
78 > export function adoptToGalleryExtensionId(id: string): string {
79 return id.toLowerCase();
80 }
82 > export function getGalleryExtensionId(publisher: string | undefined, name: string): string {
83 return adoptToGalleryExtensionId(getExtensionId(publisher ?? UNDEFINED_PUBLISHER, name));
84 }
86 > export function groupByExtension<T>(extensions: T[], getExtensionIdentifier: (t: T) => IExtensionIdentifier): T[][] {
87 const byExtension: T[][] = [];
88 const findGroup = (extension: T) => {
104 return byExtension;
105 }
107 > export function getLocalExtensionTelemetryData(extension: ILocalExtension) {
108 return {
109 id: extension.identifier.id,
116 };
117 }
119 >
120 > /* __GDPR__FRAGMENT__
121 > "GalleryExtensionTelemetryData" : {
122 > "id" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
123 > "name": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
124 > "extensionVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
125 > "galleryId": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
126 > "publisherId": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
127 > "publisherName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
128 > "publisherDisplayName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
129 > "isPreReleaseVersion": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
130 > "dependencies": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
131 > "isSigned": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
132 > "${include}": [
133 > "${GalleryExtensionTelemetryData2}"
134 > ]
135 > }
136 > */
137 > export function getGalleryExtensionTelemetryData(extension: IGalleryExtension) {
138 return {
139 id: new TelemetryTrustedValue(extension.identifier.id),
150 };
151 }
153 > export const BetterMergeId = new ExtensionIdentifier('pprice.better-merge');
154 >
155 > export function getExtensionDependencies(installedExtensions: ReadonlyArray<IExtension>, extension: IExtension): IExtension[] {
156 const dependencies: IExtension[] = [];
157 const extensions = extension.manifest.extensionDependencies?.slice(0) ?? [];
171 return dependencies;
172 }
174 async function isAlpineLinux(fileService: IFileService, logService: ILogService): Promise<boolean> {
175 if (!isLinux) {
191 return !!content && (content.match(/^ID=([^\u001b\r\n]*)/m) || [])[1] === 'alpine';
192 }
194 export async function computeTargetPlatform(fileService: IFileService, logService: ILogService): Promise<TargetPlatform> {
195 const alpineLinux = await isAlpineLinux(fileService, logService);
198 return targetPlatform;
199 }
201 > export function isMalicious(identifier: IExtensionIdentifier, malicious: ReadonlyArray<MaliciousExtensionInfo>): boolean {
202 return findMatchingMaliciousEntry(identifier, malicious) !== undefined;
203 }
205 > export function findMatchingMaliciousEntry(identifier: IExtensionIdentifier, malicious: ReadonlyArray<MaliciousExtensionInfo>): MaliciousExtensionInfo | undefined {
206 return malicious.find(({ extensionOrPublisher }) => {
207 if (isString(extensionOrPublisher)) {
src/vs/base/common/linkedList.ts 81 covered LOC · 26 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- linkedList.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > class Node<E> {
7 >
8 > static readonly Undefined = new Node<unknown>(undefined);
9 >
10 > element: E;
11 > next: Node<E> | typeof Node.Undefined;
12 > prev: Node<E> | typeof Node.Undefined;
13 >
14 > constructor(element: E) {
15 > this.element = element;
16 > this.next = Node.Undefined;
17 > this.prev = Node.Undefined;
18 > }
19 > }
20 >
21 > export class LinkedList<E> {
23 > private _first: Node<E> | typeof Node.Undefined = Node.Undefined;
24 > private _last: Node<E> | typeof Node.Undefined = Node.Undefined;
25 > private _size: number = 0;
27 > get size(): number {
28 > return this._size; linkedList.ts
29 > }
31 > isEmpty(): boolean {
32 return this._first === Node.Undefined;
33 }
35 > clear(): void {
36 let node = this._first;
37 while (node !== Node.Undefined) {
46 this._size = 0;
47 }
49 > unshift(element: E): () => void {
50 return this._insert(element, false);
51 }
53 > push(element: E): () => void {
54 > return this._insert(element, true); linkedList.ts
55 > }
57 > private _insert(element: E, atTheEnd: boolean): () => void {
58 > const newNode = new Node(element); linkedList.ts
59 > if (this._first === Node.Undefined) {
60 > this._first = newNode;
61 > this._last = newNode;
62 >
63 > } else if (atTheEnd) {
64 // push
65 const oldLast = this._last;
75 oldFirst.prev = newNode;
76 }
77 > this._size += 1; linkedList.ts
78 >
79 > let didRemove = false;
80 > return () => {
81 if (!didRemove) {
82 didRemove = true;
84 }
85 };
86 > } linkedList.ts
88 > shift(): E | undefined {
89 > if (this._first === Node.Undefined) { linkedList.ts
90 return undefined;
91 > } else { linkedList.ts
92 > const res = this._first.element;
93 > this._remove(this._first);
94 > return res as E;
95 > }
96 > }
98 > pop(): E | undefined {
99 if (this._last === Node.Undefined) {
100 return undefined;
105 }
106 }
108 > peek(): E | undefined {
109 if (this._last === Node.Undefined) {
110 return undefined;
114 }
115 }
117 > private _remove(node: Node<E> | typeof Node.Undefined): void {
118 > if (node.prev !== Node.Undefined && node.next !== Node.Undefined) { linkedList.ts
119 // middle
120 const anchor = node.prev;
122 node.next.prev = anchor;
123
124 > } else if (node.prev === Node.Undefined && node.next === Node.Undefined) { linkedList.ts
125 > // only node linkedList.ts
126 > this._first = Node.Undefined;
127 > this._last = Node.Undefined;
128 >
129 > } else if (node.next === Node.Undefined) { linkedList.ts
130 // last
131 this._last = this._last.prev!;
137 this._first.prev = Node.Undefined;
138 }
140 > // done
141 > this._size -= 1;
142 > }
144 > *[Symbol.iterator](): Iterator<E> {
145 let node = this._first;
146 while (node !== Node.Undefined) {
src/vs/base/test/common/virtualScheduling/embedding.ts 76 covered LOC · 2 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- embedding.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { setTimeout0, setTimeout0IsFaster } from '../../../common/platform.js';
7 > import { TimeApi } from './timeApi.js';
8 > import { VirtualEvent } from './virtualClock.js';
9 >
10 > /**
11 > * # The processor/host embedding
12 > *
13 > * An {@link Embedding} is the contract between the processor's pure state
14 > * machine and the host event loop. It is invoked once per virtual step that
15 > * produced progress, and decides *how* the processor reaches the host before
16 > * the next step.
17 > *
18 > * ## Contract
19 > *
20 > * On each invocation the embedding MUST do exactly one of:
21 > *
22 > * 1. Return `'continueSync'` **without** calling `then`. The processor will
23 > * loop in place on the same host stack frame.
24 > *
25 > * 2. Schedule `then` on a host primitive (microtask, macrotask, paint frame)
26 > * and return `'cbScheduled'`. The processor will return and wait for the
27 > * callback to re-enter the trampoline.
28 > *
29 > * The embedding MUST NOT call `then` synchronously and also return
30 > * `'cbScheduled'` (that would re-enter the trampoline before this call
31 > * completed). Likewise, returning `'continueSync'` while having scheduled
32 > * `then` async would cause `then` to fire after the trampoline already
33 > * looped — also a bug.
34 > *
35 > * ## Why a callback contract instead of async/await
36 > *
37 > * Every `await` is an implicit microtask hop. For code whose job is to
38 > * decide host hops, that's the wrong abstraction: the reader has to mentally
39 > * compile the `await` to a boundary. With this contract, every host hop is
40 > * a named call to a single primitive (`api.setTimeout`, `setTimeout0`,
41 > * `api.requestAnimationFrame`, …) at exactly one site in this file.
42 > */
43 > export type Embedding = (
44 > nextEvent: VirtualEvent,
45 > then: () => void,
46 > ) => 'continueSync' | 'cbScheduled';
47 >
48 > /**
49 > * Tasks never schedule via promise chains. The processor runs virtual events
50 > * back-to-back on a single host stack frame — fastest possible, but starves
51 > * the host event loop for the duration of the run.
52 > *
53 > * Use only for tests where no `await` / `.then` chains are involved between
54 > * scheduling and execution of virtual events.
55 > */
56 > export const syncEmbedding: Embedding = () => 'continueSync';
57 >
58 > /**
59 > * Tasks may schedule via `await` / `.then`. Between virtual events, yield to
60 > * the host so the *microtask closure* — the current microtask plus every
61 > * microtask it transitively enqueues — drains before the next event runs.
62 > *
63 > * This is the embedding to use for almost all integration-style tests.
64 > */
65 > export function drainMicrotasksEmbedding(realApi: TimeApi): Embedding {
66 return (next, then) => {
67 if (next.preferRealAnimationFrame && realApi.requestAnimationFrame) {
73 };
74 }
76 > /**
77 > * Schedule `cb` after the closure of the current microtask queue: `cb`
78 > * fires only after the current microtask AND every microtask it
79 > * (recursively, transitively) enqueues has settled.
80 > *
81 > * Per the HTML spec, a macrotask runs only when the microtask queue is
82 > * empty, so any macrotask primitive achieves this. We pick the fastest
83 > * one available on the host.
84 > */
85 > export function nextMacrotask(api: TimeApi, cb: () => void): void {
86 if (setTimeout0IsFaster) { setTimeout0(cb); return; }
87 if (api.setImmediate) { api.setImmediate(cb); return; }
src/vs/base/common/objects.ts 75 covered LOC · 19 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- objects.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { isTypedArray, isObject, isUndefinedOrNull } from './types.js';
7 >
8 > export function deepClone<T>(obj: T): T {
9 > if (!obj || typeof obj !== 'object') { objects.ts
10 > return obj; objects.ts
11 > }
12 > if (obj instanceof RegExp) { objects.ts
13 return obj;
14 }
15 > const result: any = Array.isArray(obj) ? [] : {}; objects.ts
16 > Object.entries(obj).forEach(([key, value]) => {
17 > result[key] = value && typeof value === 'object' ? deepClone(value) : value; objects.ts
18 > }); objects.ts
19 > return result;
20 > }
21 > objects.ts
22 > export function deepFreeze<T>(obj: T): T {
23 if (!obj || typeof obj !== 'object') {
24 return obj;
39 return obj;
40 }
41 > objects.ts
42 > const _hasOwnProperty = Object.prototype.hasOwnProperty;
43 >
44 >
45 > export function cloneAndChange(obj: any, changer: (orig: any) => any): any {
46 return _cloneAndChange(obj, changer, new Set());
47 }
48 > objects.ts
49 function _cloneAndChange(obj: any, changer: (orig: any) => any, seen: Set<any>): any {
50 if (isUndefinedOrNull(obj)) {
82 return obj;
83 }
84 > objects.ts
85 > /**
86 > * Copies all properties of source into destination. The optional parameter "overwrite" allows to control
87 > * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
88 > */
89 > export function mixin(destination: any, source: any, overwrite: boolean = true): any {
90 if (!isObject(destination)) {
91 return source;
109 return destination;
110 }
111 > objects.ts
112 > export function equals(one: any, other: any): boolean {
113 if (one === other) {
114 return true;
162 return true;
163 }
164 > objects.ts
165 > /**
166 > * Calls `JSON.Stringify` with a replacer to break apart any circular references.
167 > * This prevents `JSON`.stringify` from throwing the exception
168 > * "Uncaught TypeError: Converting circular structure to JSON"
169 > */
170 > export function safeStringify(obj: any): string {
171 const seen = new Set<any>();
172 return JSON.stringify(obj, (key, value) => {
184 });
185 }
186 > objects.ts
187 > /**
188 > * Like `JSON.stringify`, but with deterministic ordering of object keys so that
189 > * structurally equal inputs always produce the same string. Useful for cache
190 > * keys derived from arbitrary object payloads.
191 > *
192 > * - Object keys are sorted at every level of nesting.
193 > * - Properties whose value is `undefined` are omitted (matching `JSON.stringify`).
194 > * - Circular references are replaced with the string `"[Circular]"` to avoid
195 > * throwing.
196 > * - A top-level `undefined` returns the string `'undefined'`; any other
197 > * stringification failure returns the empty string.
198 > */
199 > export function stableStringify(value: unknown): string {
200 if (value === undefined) {
201 return 'undefined';
207 }
208 }
209 > objects.ts
210 function _stableStringify(value: unknown, seen: WeakSet<object>): string {
211 if (value === null || typeof value !== 'object') {
230 return '{' + parts.join(',') + '}';
231 }
232 > objects.ts
233 > type obj = { [key: string]: any };
234 > /**
235 > * Returns an object that has keys for each value that is different in the base object. Keys
236 > * that do not exist in the target but in the base object are not considered.
237 > *
238 > * Note: This is not a deep-diffing method, so the values are strictly taken into the resulting
239 > * object if they differ.
240 > *
241 > * @param base the object to diff against
242 > * @param obj the object to use for diffing
243 > */
244 > export function distinct(base: obj, target: obj): obj {
245 const result = Object.create(null);
246
261 return result;
262 }
263 > objects.ts
264 > export function getCaseInsensitive(target: obj, key: string): unknown {
265 const lowercaseKey = key.toLowerCase();
266 const equivalentKey = Object.keys(target).find(k => k.toLowerCase() === lowercaseKey);
267 return equivalentKey ? target[equivalentKey] : target[key];
268 }
269 > objects.ts
270 > export function filter(obj: obj, predicate: (key: string, value: any) => boolean): obj {
271 const result = Object.create(null);
272 for (const [key, value] of Object.entries(obj)) {
277 return result;
278 }
279 > objects.ts
280 > export function mapValues<T extends {}, R>(obj: T, fn: (value: T[keyof T], key: string) => R): { [K in keyof T]: R } {
281 const result: { [key: string]: R } = {};
282 for (const [key, value] of Object.entries(obj)) {
src/vs/base/common/collections.ts 74 covered LOC · 18 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- collections.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > /**
7 > * An interface for a JavaScript object that
8 > * acts a dictionary. The keys are strings.
9 > */
10 > export type IStringDictionary<V> = Record<string, V>;
11 >
12 > /**
13 > * An interface for a JavaScript object that
14 > * acts a dictionary. The keys are numbers.
15 > */
16 > export type INumberDictionary<V> = Record<number, V>;
17 >
18 > /**
19 > * Groups the collection into a dictionary based on the provided
20 > * group function.
21 > */
22 > export function groupBy<K extends string | number | symbol, V>(data: readonly V[], groupFn: (element: V) => K): Partial<Record<K, V[]>> {
23 const result: Partial<Record<K, V[]>> = Object.create(null);
24 for (const element of data) {
32 return result;
33 }
35 > export function groupByMap<K, V>(data: V[], groupFn: (element: V) => K): Map<K, V[]> {
36 const result = new Map<K, V[]>();
37 for (const element of data) {
46 return result;
47 }
49 > export function diffSets<T>(before: ReadonlySet<T>, after: ReadonlySet<T>): { removed: T[]; added: T[] } {
50 const removed: T[] = [];
51 const added: T[] = [];
62 return { removed, added };
63 }
65 > /**
66 > * Checks whether two sets contain exactly the same elements.
67 > *
68 > * @param a - The first set.
69 > * @param b - The second set.
70 > * @returns `true` if both sets have the same size and every element of `a` is also in `b`.
71 > */
72 > export function equalSets<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean {
73 if (a === b) {
74 return true;
84 return true;
85 }
87 > export function diffMaps<K, V>(before: Map<K, V>, after: Map<K, V>): { removed: V[]; added: V[] } {
88 const removed: V[] = [];
89 const added: V[] = [];
100 return { removed, added };
101 }
103 > /**
104 > * Computes the intersection of two sets.
105 > *
106 > * @param setA - The first set.
107 > * @param setB - The second iterable.
108 > * @returns A new set containing the elements that are in both `setA` and `setB`.
109 > */
110 > export function intersection<T>(setA: Set<T>, setB: Iterable<T>): Set<T> {
111 const result = new Set<T>();
112 for (const elem of setB) {
117 return result;
118 }
120 > export class SetWithKey<T> implements Set<T> {
121 > private _map = new Map<unknown, T>();
122 >
123 > constructor(values: T[], private toKey: (t: T) => unknown) {
124 for (const value of values) {
125 this.add(value);
126 }
127 }
129 > get size(): number {
130 return this._map.size;
131 }
133 > add(value: T): this {
134 const key = this.toKey(value);
135 this._map.set(key, value);
136 return this;
137 }
139 > delete(value: T): boolean {
140 return this._map.delete(this.toKey(value));
141 }
143 > has(value: T): boolean {
144 return this._map.has(this.toKey(value));
145 }
147 > *entries(): SetIterator<[T, T]> {
148 for (const entry of this._map.values()) {
149 yield [entry, entry];
150 }
151 }
153 > keys(): SetIterator<T> {
154 return this.values();
155 }
157 > *values(): SetIterator<T> {
158 for (const entry of this._map.values()) {
159 yield entry;
160 }
161 }
163 > clear(): void {
164 this._map.clear();
165 }
167 > forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: unknown): void {
168 this._map.forEach(entry => callbackfn.call(thisArg, entry, entry, this));
169 }
171 > [Symbol.iterator](): SetIterator<T> {
172 return this.values();
173 }
175 > [Symbol.toStringTag]: string = 'SetWithKey';
176 > }
src/vs/platform/userDataSync/common/extensionsMerge.ts 72 covered LOC · 18 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensionsMerge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IStringDictionary } from '../../../base/common/collections.js';
7 > import { deepClone, equals } from '../../../base/common/objects.js';
8 > import * as semver from '../../../base/common/semver/semver.js';
9 > import { assertReturnsDefined } from '../../../base/common/types.js';
10 > import { IExtensionIdentifier } from '../../extensions/common/extensions.js';
11 > import { ILocalSyncExtension, IRemoteSyncExtension, ISyncExtension } from './userDataSync.js';
12 >
13 > export interface IMergeResult {
14 > readonly local: { added: ISyncExtension[]; removed: IExtensionIdentifier[]; updated: ISyncExtension[] };
15 > readonly remote: { added: ISyncExtension[]; removed: ISyncExtension[]; updated: ISyncExtension[]; all: ISyncExtension[] } | null;
16 > }
17 >
18 > export function merge(localExtensions: ILocalSyncExtension[], remoteExtensions: IRemoteSyncExtension[] | null, lastSyncExtensions: IRemoteSyncExtension[] | null, skippedExtensions: ISyncExtension[], ignoredExtensions: string[], lastSyncBuiltinExtensions: IExtensionIdentifier[] | null): IMergeResult {
19 > const added: ISyncExtension[] = []; extensionsMerge.ts
20 > const removed: IExtensionIdentifier[] = [];
21 > const updated: ISyncExtension[] = [];
22 >
23 > if (!remoteExtensions) {
24 > const remote = localExtensions.filter(({ identifier }) => ignoredExtensions.every(id => id.toLowerCase() !== identifier.id.toLowerCase())); extensionsMerge.ts
25 > return {
26 > local: {
27 > added,
28 > removed,
29 > updated,
30 > },
31 > remote: remote.length > 0 ? {
32 added: remote,
33 updated: [],
34 removed: [],
35 all: remote
36 > } : null extensionsMerge.ts
37 > };
38 > }
39
40 localExtensions = localExtensions.map(massageIncomingExtension) as ILocalSyncExtension[];
41 remoteExtensions = remoteExtensions.map(massageIncomingExtension);
42 > lastSyncExtensions = lastSyncExtensions ? lastSyncExtensions.map(massageIncomingExtension) : null; extensionsMerge.ts
43 >
44 > const uuids: Map<string, string> = new Map<string, string>();
45 > const addUUID = (identifier: IExtensionIdentifier) => { if (identifier.uuid) { uuids.set(identifier.id.toLowerCase(), identifier.uuid); } };
46 > localExtensions.forEach(({ identifier }) => addUUID(identifier));
47 > remoteExtensions.forEach(({ identifier }) => addUUID(identifier));
48 > lastSyncExtensions?.forEach(({ identifier }) => addUUID(identifier));
49 > skippedExtensions?.forEach(({ identifier }) => addUUID(identifier));
50 > lastSyncBuiltinExtensions?.forEach(identifier => addUUID(identifier));
51 >
52 > const getKey = (extension: ISyncExtension): string => {
53 const uuid = extension.identifier.uuid || uuids.get(extension.identifier.id.toLowerCase());
54 return uuid ? `uuid:${uuid}` : `id:${extension.identifier.id.toLowerCase()}`;
55 };
56 > const addExtensionToMap = (map: Map<string, ISyncExtension>, extension: ISyncExtension) => { extensionsMerge.ts
57 map.set(getKey(extension), extension);
58 return map;
59 };
60 > const localExtensionsMap: Map<string, ISyncExtension> = localExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>()); extensionsMerge.ts
61 > const remoteExtensionsMap = remoteExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>());
62 > const newRemoteExtensionsMap = remoteExtensions.reduce((map: Map<string, ISyncExtension>, extension: ISyncExtension) => addExtensionToMap(map, deepClone(extension)), new Map<string, ISyncExtension>());
63 > const lastSyncExtensionsMap = lastSyncExtensions ? lastSyncExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>()) : null;
64 > const skippedExtensionsMap = skippedExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>());
65 > const ignoredExtensionsSet = ignoredExtensions.reduce((set, id) => {
66 const uuid = uuids.get(id.toLowerCase());
67 return set.add(uuid ? `uuid:${uuid}` : `id:${id.toLowerCase()}`);
68 > }, new Set<string>()); extensionsMerge.ts
69 > const lastSyncBuiltinExtensionsSet = lastSyncBuiltinExtensions ? lastSyncBuiltinExtensions.reduce((set, { id, uuid }) => {
70 uuid = uuid ?? uuids.get(id.toLowerCase());
71 return set.add(uuid ? `uuid:${uuid}` : `id:${id.toLowerCase()}`);
72 > }, new Set<string>()) : null; extensionsMerge.ts
73 >
74 > const localToRemote = compare(localExtensionsMap, remoteExtensionsMap, ignoredExtensionsSet, false);
75 > if (localToRemote.added.size > 0 || localToRemote.removed.size > 0 || localToRemote.updated.size > 0) {
76
77 const baseToLocal = compare(lastSyncExtensionsMap, localExtensionsMap, ignoredExtensionsSet, false);
238 const remote: ISyncExtension[] = [];
239 const remoteChanges = compare(remoteExtensionsMap, newRemoteExtensionsMap, new Set<string>(), true);
240 > const hasRemoteChanges = remoteChanges.added.size > 0 || remoteChanges.updated.size > 0 || remoteChanges.removed.size > 0; extensionsMerge.ts
241 > if (hasRemoteChanges) {
242 newRemoteExtensionsMap.forEach((value, key) => remote.push(massageOutgoingExtension(value, key)));
243 }
250 removed: [...remoteChanges.removed].map(id => remoteExtensionsMap.get(id)!),
251 all: remote
252 > } : null extensionsMerge.ts
253 > };
254 > }
256 function compare(from: Map<string, ISyncExtension> | null, to: Map<string, ISyncExtension>, ignoredExtensions: Set<string>, checkVersionProperty: boolean): { added: Set<string>; removed: Set<string>; updated: Set<string> } {
257 const fromKeys = from ? [...from.keys()].filter(key => !ignoredExtensions.has(key)) : [];
274 return { added, removed, updated };
275 }
277 function areSame(fromExtension: ISyncExtension, toExtension: ISyncExtension, checkVersionProperty: boolean, checkInstalledProperty: boolean): boolean {
278 if (fromExtension.disabled !== toExtension.disabled) {
321 return true;
322 }
324 function mergeExtensionState(localExtension: ISyncExtension, remoteExtension: ISyncExtension, lastSyncExtension: ISyncExtension | undefined): IStringDictionary<any> | undefined {
325 const localState = localExtension.state;
369 return mergedState;
370 }
372 function compareExtensionState(from: IStringDictionary<any>, to: IStringDictionary<any>): { added: Set<string>; removed: Set<string>; updated: Set<string> } {
373 const fromKeys = Object.keys(from);
390 return { added, removed, updated };
391 }
393 function isSameExtensionState(a: IStringDictionary<any> = {}, b: IStringDictionary<any> = {}): boolean {
394 const { added, removed, updated } = compareExtensionState(a, b);
395 return added.size === 0 && removed.size === 0 && updated.size === 0;
396 }
398 > // massage incoming extension - add optional properties
399 function massageIncomingExtension(extension: ISyncExtension): ISyncExtension {
400 return { ...extension, ...{ disabled: !!extension.disabled, installed: !!extension.installed } };
401 }
403 > // massage outgoing extension - remove optional properties
404 function massageOutgoingExtension(extension: ISyncExtension, key: string): ISyncExtension {
405 const massagedExtension: ISyncExtension = {
src/vs/platform/userDataSync/common/userDataSyncEnablementService.ts 72 covered LOC · 18 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSyncEnablementService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { Disposable } from '../../../base/common/lifecycle.js';
8 > import { isWeb } from '../../../base/common/platform.js';
9 > import { IEnvironmentService } from '../../environment/common/environment.js';
10 > import { IApplicationStorageValueChangeEvent, IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
11 > import { ALL_SYNC_RESOURCES, getEnablementKey, IUserDataSyncEnablementService, IUserDataSyncStoreManagementService, SyncResource } from './userDataSync.js';
12 >
13 > const enablementKey = 'sync.enable';
14 >
15 > export class UserDataSyncEnablementService extends Disposable implements IUserDataSyncEnablementService {
16 >
17 > _serviceBrand: undefined;
18 >
19 > private _onDidChangeEnablement = this._register(new Emitter<boolean>());
20 > readonly onDidChangeEnablement: Event<boolean> = this._onDidChangeEnablement.event;
21 >
22 > private _onDidChangeResourceEnablement = this._register(new Emitter<[SyncResource, boolean]>());
23 > readonly onDidChangeResourceEnablement: Event<[SyncResource, boolean]> = this._onDidChangeResourceEnablement.event;
24 >
25 > constructor(
26 > @IStorageService private readonly storageService: IStorageService, userDataSyncEnablementService.ts
27 > @IEnvironmentService protected readonly environmentService: IEnvironmentService,
28 > @IUserDataSyncStoreManagementService private readonly userDataSyncStoreManagementService: IUserDataSyncStoreManagementService,
29 > ) {
30 > super();
31 > this._register(storageService.onDidChangeValue(StorageScope.APPLICATION, undefined, this._store)(e => this.onDidStorageChange(e)));
32 > }
34 > isEnabled(): boolean {
35 switch (this.environmentService.sync) {
36 case 'on':
41 return this.storageService.getBoolean(enablementKey, StorageScope.APPLICATION, false);
42 }
44 > canToggleEnablement(): boolean {
45 return this.userDataSyncStoreManagementService.userDataSyncStore !== undefined && this.environmentService.sync === undefined;
46 }
48 > setEnablement(enabled: boolean): void {
49 if (enabled && !this.canToggleEnablement()) {
50 return;
52 this.storageService.store(enablementKey, enabled, StorageScope.APPLICATION, StorageTarget.MACHINE);
53 }
55 > isResourceEnabled(resource: SyncResource, defaultValue?: boolean): boolean {
56 > const storedValue = this.storageService.getBoolean(getEnablementKey(resource), StorageScope.APPLICATION); userDataSyncEnablementService.ts
57 > defaultValue = defaultValue ?? resource !== SyncResource.Prompts;
58 > return storedValue ?? defaultValue;
59 > }
61 > isResourceEnablementConfigured(resource: SyncResource): boolean {
62 const storedValue = this.storageService.getBoolean(getEnablementKey(resource), StorageScope.APPLICATION);
63
64 return (storedValue !== undefined);
65 }
67 > setResourceEnablement(resource: SyncResource, enabled: boolean): void {
68 > if (this.isResourceEnabled(resource) !== enabled) { userDataSyncEnablementService.ts
69 > const resourceEnablementKey = getEnablementKey(resource);
70 > this.storeResourceEnablement(resourceEnablementKey, enabled);
71 > }
72 > }
74 > getResourceSyncStateVersion(resource: SyncResource): string | undefined {
75 > return undefined; userDataSyncEnablementService.ts
76 > }
78 > private storeResourceEnablement(resourceEnablementKey: string, enabled: boolean): void {
79 > this.storageService.store(resourceEnablementKey, enabled, StorageScope.APPLICATION, isWeb ? StorageTarget.USER /* sync in web */ : StorageTarget.MACHINE); userDataSyncEnablementService.ts
80 > }
82 > private onDidStorageChange(storageChangeEvent: IApplicationStorageValueChangeEvent): void {
83 > if (enablementKey === storageChangeEvent.key) { userDataSyncEnablementService.ts
84 this._onDidChangeEnablement.fire(this.isEnabled());
85 return;
86 }
88 > const resourceKey = ALL_SYNC_RESOURCES.filter(resourceKey => getEnablementKey(resourceKey) === storageChangeEvent.key)[0];
89 > if (resourceKey) {
90 > this._onDidChangeResourceEnablement.fire([resourceKey, this.isResourceEnabled(resourceKey)]);
91 > return;
92 > }
93 > }
src/vs/platform/userDataSync/common/userDataSyncLocalStoreService.ts 72 covered LOC · 18 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSyncLocalStoreService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Promises } from '../../../base/common/async.js';
7 > import { VSBuffer } from '../../../base/common/buffer.js';
8 > import { toLocalISOString } from '../../../base/common/date.js';
9 > import { Disposable } from '../../../base/common/lifecycle.js';
10 > import { joinPath } from '../../../base/common/resources.js';
11 > import { URI } from '../../../base/common/uri.js';
12 > import { IConfigurationService } from '../../configuration/common/configuration.js';
13 > import { IEnvironmentService } from '../../environment/common/environment.js';
14 > import { FileOperationResult, IFileService, IFileStat, toFileOperationResult } from '../../files/common/files.js';
15 > import { IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
16 > import { ALL_SYNC_RESOURCES, IResourceRefHandle, IUserDataSyncLocalStoreService, IUserDataSyncLogService, SyncResource } from './userDataSync.js';
17 >
18 > export class UserDataSyncLocalStoreService extends Disposable implements IUserDataSyncLocalStoreService {
19 >
20 > _serviceBrand: undefined;
21 >
22 > constructor(
23 > @IEnvironmentService private readonly environmentService: IEnvironmentService, userDataSyncLocalStoreService.ts
24 > @IFileService private readonly fileService: IFileService,
25 > @IConfigurationService private readonly configurationService: IConfigurationService,
26 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
27 > @IUserDataProfilesService private readonly userDataProfilesService: IUserDataProfilesService,
28 > ) {
29 > super();
30 > this.cleanUp();
31 > }
33 > private async cleanUp(): Promise<void> {
34 > for (const profile of this.userDataProfilesService.profiles) { userDataSyncLocalStoreService.ts
35 > for (const resource of ALL_SYNC_RESOURCES) {
36 > try {
37 > await this.cleanUpBackup(this.getResourceBackupHome(resource, profile.isDefault ? undefined : profile.id));
38 > } catch (error) {
39 this.logService.error(error);
40 }
42 > }
43 >
44 > let stat: IFileStat;
45 > try {
46 > stat = await this.fileService.resolve(this.environmentService.userDataSyncHome);
47 > } catch (error) {
48 > if (toFileOperationResult(error) !== FileOperationResult.FILE_NOT_FOUND) {
49 this.logService.error(error);
50 }
52 > }
53
54 if (stat.children) {
84 return [];
85 }
87 > async resolveResourceContent(resourceKey: SyncResource, ref: string, collection?: string, root?: URI): Promise<string | null> {
88 const folder = this.getResourceBackupHome(resourceKey, collection, root);
89 const file = joinPath(folder, ref);
96 }
97 }
99 > async writeResource(resourceKey: SyncResource, content: string, cTime: Date, collection?: string, root?: URI): Promise<void> {
100 const folder = this.getResourceBackupHome(resourceKey, collection, root);
101 const resource = joinPath(folder, `${toLocalISOString(cTime).replace(/-|:|\.\d+Z$/g, '')}.json`);
106 }
107 }
109 > private getResourceBackupHome(resource: SyncResource, collection?: string, root: URI = this.environmentService.userDataSyncHome): URI {
110 > return joinPath(root, ...(collection ? [collection, resource] : [resource])); userDataSyncLocalStoreService.ts
111 > }
113 > private async cleanUpBackup(folder: URI): Promise<void> {
115 > try {
116 > if (!(await this.fileService.exists(folder))) {
117 > return;
118 > }
119 > } catch (e) {
120 return;
121 }
src/vs/platform/uriIdentity/common/uriIdentityService.ts 70 covered LOC · 11 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- uriIdentityService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IUriIdentityService } from './uriIdentity.js';
7 > import { URI } from '../../../base/common/uri.js';
8 > import { InstantiationType, registerSingleton } from '../../instantiation/common/extensions.js';
9 > import { IFileService, FileSystemProviderCapabilities, IFileSystemProviderCapabilitiesChangeEvent, IFileSystemProviderRegistrationEvent } from '../../files/common/files.js';
10 > import { ExtUri, IExtUri, normalizePath } from '../../../base/common/resources.js';
11 > import { Event } from '../../../base/common/event.js';
12 > import { DisposableStore } from '../../../base/common/lifecycle.js';
13 > import { quickSelect } from '../../../base/common/arrays.js';
14 >
15 > class Entry {
16 > static _clock = 0;
17 > time: number = Entry._clock++;
18 > constructor(readonly uri: URI) { }
19 > touch() {
20 this.time = Entry._clock++;
21 return this;
22 }
24 >
25 > export class UriIdentityService implements IUriIdentityService {
26 >
27 > declare readonly _serviceBrand: undefined;
28 >
29 > readonly extUri: IExtUri;
30 >
31 > private readonly _dispooables = new DisposableStore();
32 > private readonly _canonicalUris: Map<string, Entry>;
33 > private readonly _limit = 2 ** 16;
34 >
35 > constructor(@IFileService private readonly _fileService: IFileService) {
37 > const schemeIgnoresPathCasingCache = new Map<string, boolean>();
38 >
39 > // assume path casing matters unless the file system provider spec'ed the opposite.
40 > // for all other cases path casing matters, e.g for
41 > // * virtual documents
42 > // * in-memory uris
43 > // * all kind of "private" schemes
44 > const ignorePathCasing = (uri: URI): boolean => {
45 > let ignorePathCasing = schemeIgnoresPathCasingCache.get(uri.scheme); uriIdentityService.ts
46 > if (ignorePathCasing === undefined) {
47 > // retrieve once and then case per scheme until a change happens
48 > ignorePathCasing = _fileService.hasProvider(uri) && !this._fileService.hasCapability(uri, FileSystemProviderCapabilities.PathCaseSensitive);
49 > schemeIgnoresPathCasingCache.set(uri.scheme, ignorePathCasing);
50 > }
51 > return ignorePathCasing;
52 > };
53 > this._dispooables.add(Event.any<IFileSystemProviderCapabilitiesChangeEvent | IFileSystemProviderRegistrationEvent>( uriIdentityService.ts
54 > _fileService.onDidChangeFileSystemProviderRegistrations,
55 > _fileService.onDidChangeFileSystemProviderCapabilities
56 > )(e => {
57 const oldIgnorePathCasingValue = schemeIgnoresPathCasingCache.get(e.scheme);
58 if (oldIgnorePathCasingValue === undefined) {
101 return uri;
102 }
104 > private _checkTrim(): void {
105 if (this._canonicalUris.size < this._limit) {
106 return;
124 }
125 }
127 >
128 > registerSingleton(IUriIdentityService, UriIdentityService, InstantiationType.Delayed);
src/vs/base/common/jsonFormatter.ts 69 covered LOC · 6 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- jsonFormatter.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { createScanner, ScanError, SyntaxKind } from './json.js';
7 >
8 > export interface FormattingOptions {
9 > /**
10 > * If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?
11 > */
12 > tabSize?: number;
13 > /**
14 > * Is indentation based on spaces?
15 > */
16 > insertSpaces?: boolean;
17 > /**
18 > * The default 'end of line' character. If not set, '\n' is used as default.
19 > */
20 > eol?: string;
21 > }
22 >
23 > /**
24 > * Represents a text modification
25 > */
26 > export interface Edit {
27 > /**
28 > * The start offset of the modification.
29 > */
30 > offset: number;
31 > /**
32 > * The length of the modification. Must not be negative. Empty length represents an *insert*.
33 > */
34 > length: number;
35 > /**
36 > * The new content. Empty content represents a *remove*.
37 > */
38 > content: string;
39 > }
40 >
41 > /**
42 > * A text range in the document
43 > */
44 > export interface Range {
45 > /**
46 > * The start offset of the range.
47 > */
48 > offset: number;
49 > /**
50 > * The length of the range. Must not be negative.
51 > */
52 > length: number;
53 > }
54 >
55 >
56 > export function format(documentText: string, range: Range | undefined, options: FormattingOptions): Edit[] {
57 let initialIndentLevel: number;
58 let formatText: string;
202 return editOperations;
203 }
205 > /**
206 > * Creates a formatted string out of the object passed as argument, using the given formatting options
207 > * @param any The object to stringify and format
208 > * @param options The formatting options to use
209 > */
210 > export function toFormattedString(obj: unknown, options: FormattingOptions) {
211 const content = JSON.stringify(obj, undefined, options.insertSpaces ? options.tabSize || 4 : '\t');
212 if (options.eol !== undefined) {
215 return content;
216 }
218 function repeat(s: string, count: number): string {
219 let result = '';
223 return result;
224 }
226 function computeIndentLevel(content: string, options: FormattingOptions): number {
227 let i = 0;
241 return Math.floor(nChars / tabSize);
242 }
244 > export function getEOL(options: FormattingOptions, text: string): string {
245 for (let i = 0; i < text.length; i++) {
246 const ch = text.charAt(i);
256 return (options && options.eol) || '\n';
257 }
259 > export function isEOL(text: string, offset: number) {
260 return '\r\n'.indexOf(text.charAt(offset)) !== -1;
261 }
src/vs/base/common/iterator.ts 65 covered LOC · 23 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- iterator.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { isIterable } from './types.js';
7 >
8 > export namespace Iterable {
9 >
10 > export function is<T = unknown>(thing: unknown): thing is Iterable<T> {
11 > return !!thing && typeof thing === 'object' && typeof (thing as Iterable<T>)[Symbol.iterator] === 'function'; iterator.ts
12 > }
14 > const _empty: Iterable<never> = Object.freeze([]);
15 > export function empty<T = never>(): readonly never[] {
16 return _empty as readonly never[];
17 }
19 > export function* single<T>(element: T): Iterable<T> {
20 yield element;
21 }
23 > export function wrap<T>(iterableOrElement: Iterable<T> | T): Iterable<T> {
24 if (is(iterableOrElement)) {
25 return iterableOrElement;
28 }
29 }
31 > export function from<T>(iterable: Iterable<T> | undefined | null): Iterable<T> {
32 return iterable ?? (_empty as Iterable<T>);
33 }
35 > export function* reverse<T>(array: ReadonlyArray<T>): Iterable<T> {
36 for (let i = array.length - 1; i >= 0; i--) {
37 yield array[i];
38 }
39 }
41 > export function isEmpty<T>(iterable: Iterable<T> | undefined | null): boolean {
42 return !iterable || iterable[Symbol.iterator]().next().done === true;
43 }
45 > export function first<T>(iterable: Iterable<T>): T | undefined {
46 return iterable[Symbol.iterator]().next().value;
47 }
49 > export function some<T>(iterable: Iterable<T>, predicate: (t: T, i: number) => unknown): boolean {
50 let i = 0;
51 for (const element of iterable) {
56 return false;
57 }
59 > export function every<T>(iterable: Iterable<T>, predicate: (t: T, i: number) => unknown): boolean {
60 let i = 0;
61 for (const element of iterable) {
66 return true;
67 }
69 > export function find<T, R extends T>(iterable: Iterable<T>, predicate: (t: T) => t is R): R | undefined;
70 > export function find<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): T | undefined;
71 > export function find<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): T | undefined {
72 for (const element of iterable) {
73 if (predicate(element)) {
78 return undefined;
79 }
81 > export function filter<T, R extends T>(iterable: Iterable<T>, predicate: (t: T) => t is R): Iterable<R>;
82 > export function filter<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): Iterable<T>;
83 > export function* filter<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): Iterable<T> {
84 for (const element of iterable) {
85 if (predicate(element)) {
88 }
89 }
91 > export function* map<T, R>(iterable: Iterable<T>, fn: (t: T, index: number) => R): Iterable<R> {
92 let index = 0;
93 for (const element of iterable) {
95 }
96 }
98 > export function* flatMap<T, R>(iterable: Iterable<T>, fn: (t: T, index: number) => Iterable<R>): Iterable<R> {
99 let index = 0;
100 for (const element of iterable) {
102 }
103 }
104 > iterator.ts
105 > export function* concat<T>(...iterables: (Iterable<T> | T)[]): Iterable<T> {
106 for (const item of iterables) {
107 if (isIterable(item)) {
112 }
113 }
114 > iterator.ts
115 > export function reduce<T, R>(iterable: Iterable<T>, reducer: (previousValue: R, currentValue: T) => R, initialValue: R): R {
116 let value = initialValue;
117 for (const element of iterable) {
120 return value;
121 }
122 > iterator.ts
123 > export function length<T>(iterable: Iterable<T>): number {
124 let count = 0;
125 for (const _ of iterable) {
128 return count;
129 }
130 > iterator.ts
131 > /**
132 > * Returns an iterable slice of the array, with the same semantics as `array.slice()`.
133 > */
134 > export function* slice<T>(arr: ReadonlyArray<T>, from: number, to = arr.length): Iterable<T> {
135 if (from < -arr.length) {
136 from = 0;
150 }
151 }
152 > iterator.ts
153 > /**
154 > * Consumes `atMost` elements from iterable and returns the consumed elements,
155 > * and an iterable for the rest of the elements.
156 > */
157 > export function consume<T>(iterable: Iterable<T>, atMost: number = Number.POSITIVE_INFINITY): [T[], Iterable<T>] {
158 const consumed: T[] = [];
159
176 return [consumed, { [Symbol.iterator]() { return iterator; } }];
177 }
178 > iterator.ts
179 > export async function asyncToArray<T>(iterable: AsyncIterable<T>): Promise<T[]> {
180 const result: T[] = [];
181 for await (const item of iterable) {
184 return result;
185 }
186 > iterator.ts
187 > export async function asyncToArrayFlat<T>(iterable: AsyncIterable<T[]>): Promise<T[]> {
188 let result: T[] = [];
189 for await (const item of iterable) {
src/vs/platform/policy/common/policy.ts 62 covered LOC · 9 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- policy.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IStringDictionary } from '../../../base/common/collections.js';
7 > import { IPolicyData } from '../../../base/common/defaultAccount.js';
8 > import { Emitter, Event } from '../../../base/common/event.js';
9 > import { Iterable } from '../../../base/common/iterator.js';
10 > import { Disposable } from '../../../base/common/lifecycle.js';
11 > import { IManagedSettingsPolicyDefinitions, PolicyName } from '../../../base/common/policy.js';
12 > import { createDecorator } from '../../instantiation/common/instantiation.js';
13 >
14 > export type PolicyValue = string | number | boolean;
15 > export type PolicyDefinition = {
16 > type: 'string' | 'number' | 'boolean';
17 > value?: (policyData: IPolicyData) => string | number | boolean | undefined;
18 > managedSettings?: IManagedSettingsPolicyDefinitions;
19 > restrictedValue?: PolicyValue;
20 > };
21 >
22 > /** Returns a structured-clone-safe copy of `definition`, dropping the non-cloneable `value` callback. */
23 > export function toSerializablePolicyDefinition(definition: PolicyDefinition): PolicyDefinition {
24 return { type: definition.type, managedSettings: definition.managedSettings, restrictedValue: definition.restrictedValue };
25 }
26 > policy.ts
27 > /**
28 > * Returns the value to apply for `definition` when the account-policy gate is active
29 > * but not satisfied. Uses `definition.restrictedValue` when specified, otherwise falls
30 > * back to a type-driven safe default.
31 > */
32 > export function getRestrictedPolicyValue(definition: PolicyDefinition): PolicyValue {
33 if (definition.restrictedValue !== undefined) {
34 return definition.restrictedValue;
40 }
41 }
42 > policy.ts
43 > export const IPolicyService = createDecorator<IPolicyService>('policy');
44 >
45 > export interface IPolicyService {
46 > readonly _serviceBrand: undefined;
47 >
48 > readonly onDidChange: Event<readonly PolicyName[]>;
49 > updatePolicyDefinitions(policyDefinitions: IStringDictionary<PolicyDefinition>): Promise<IStringDictionary<PolicyValue>>;
50 > getPolicyValue(name: PolicyName): PolicyValue | undefined;
51 > serialize(): IStringDictionary<{ definition: PolicyDefinition; value: PolicyValue }> | undefined;
52 > readonly policyDefinitions: IStringDictionary<PolicyDefinition>;
53 > }
54 >
55 > export abstract class AbstractPolicyService extends Disposable implements IPolicyService {
56 readonly _serviceBrand: undefined;
57
61 protected readonly _onDidChange = this._register(new Emitter<readonly PolicyName[]>());
62 readonly onDidChange = this._onDidChange.event;
63 > policy.ts
64 > async updatePolicyDefinitions(policyDefinitions: IStringDictionary<PolicyDefinition>): Promise<IStringDictionary<PolicyValue>> {
65 // Replace existing definitions; identity comparison avoids redundant watcher churn.
66 let changed = false;
78 return Iterable.reduce(this.policies.entries(), (r, [name, value]) => ({ ...r, [name]: value }), {});
79 }
80 > policy.ts
81 > getPolicyValue(name: PolicyName): PolicyValue | undefined {
82 return this.policies.get(name);
83 }
84 > policy.ts
85 > serialize(): IStringDictionary<{ definition: PolicyDefinition; value: PolicyValue }> {
86 return Iterable.reduce<[PolicyName, PolicyDefinition], IStringDictionary<{ definition: PolicyDefinition; value: PolicyValue }>>(Object.entries(this.policyDefinitions), (r, [name, definition]) => ({ ...r, [name]: { definition: toSerializablePolicyDefinition(definition), value: this.policies.get(name)! } }), {});
87 }
88 > policy.ts
89 > protected abstract _updatePolicyDefinitions(policyDefinitions: IStringDictionary<PolicyDefinition>): Promise<void>;
90 > }
91 >
92 > export class NullPolicyService implements IPolicyService {
93 > readonly _serviceBrand: undefined; policy.ts
94 > readonly onDidChange = Event.None;
95 > async updatePolicyDefinitions() { return {}; }
96 > getPolicyValue() { return undefined; }
97 > serialize() { return undefined; }
98 > policyDefinitions: IStringDictionary<PolicyDefinition> = {};
99 > } policy.ts
src/vs/platform/userDataSync/common/tasksSync.ts 61 covered LOC · 10 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- tasksSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer } from '../../../base/common/buffer.js';
7 > import { IConfigurationService } from '../../configuration/common/configuration.js';
8 > import { IEnvironmentService } from '../../environment/common/environment.js';
9 > import { IFileService } from '../../files/common/files.js';
10 > import { ILogService } from '../../log/common/log.js';
11 > import { IStorageService } from '../../storage/common/storage.js';
12 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
13 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
14 > import { IUserDataProfile, IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
15 > import { AbstractJsonSynchronizer } from './abstractJsonSynchronizer.js';
16 > import { AbstractInitializer } from './abstractSynchronizer.js';
17 > import { IRemoteUserData, IUserDataSyncLocalStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource } from './userDataSync.js';
18 >
19 > interface ITasksSyncContent {
20 > tasks?: string;
21 > }
22 >
23 > export function getTasksContentFromSyncContent(syncContent: string, logService: ILogService): string | null {
24 try {
25 const parsed = <ITasksSyncContent>JSON.parse(syncContent);
30 }
31 }
33 > export class TasksSynchroniser extends AbstractJsonSynchronizer implements IUserDataSynchroniser {
34 >
35 > constructor(
36 > profile: IUserDataProfile, tasksSync.ts
37 > collection: string | undefined,
38 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
39 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
40 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
41 > @IConfigurationService configurationService: IConfigurationService,
42 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
43 > @IFileService fileService: IFileService,
44 > @IEnvironmentService environmentService: IEnvironmentService,
45 > @IStorageService storageService: IStorageService,
46 > @ITelemetryService telemetryService: ITelemetryService,
47 > @IUriIdentityService uriIdentityService: IUriIdentityService,
48 > ) {
49 > super(profile.tasksResource, { syncResource: SyncResource.Tasks, profile }, collection, 'tasks.json', fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
50 > }
52 > protected getContentFromSyncContent(syncContent: string): string | null {
53 return getTasksContentFromSyncContent(syncContent, this.logService);
54 }
56 > protected toSyncContent(tasks: string | null): ITasksSyncContent {
57 > return tasks ? { tasks } : {}; tasksSync.ts
58 > }
59 > } tasksSync.ts
60 >
61 > export class TasksInitializer extends AbstractInitializer {
62 >
63 > private tasksResource = this.userDataProfilesService.defaultProfile.tasksResource;
64 >
65 > constructor(
66 @IFileService fileService: IFileService,
67 @IUserDataProfilesService userDataProfilesService: IUserDataProfilesService,
73 super(SyncResource.Tasks, userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
74 }
76 > protected async doInitialize(remoteUserData: IRemoteUserData): Promise<void> {
77 const tasksContent = remoteUserData.syncData ? getTasksContentFromSyncContent(remoteUserData.syncData.content, this.logService) : null;
78 if (!tasksContent) {
91 await this.updateLastSyncUserData(remoteUserData);
92 }
94 > private async isEmpty(): Promise<boolean> {
95 return this.fileService.exists(this.tasksResource);
96 }
98 > }
src/vs/platform/userDataSync/common/userDataSyncAccount.ts 61 covered LOC · 6 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataSyncAccount.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { Disposable } from '../../../base/common/lifecycle.js';
8 > import { createDecorator } from '../../instantiation/common/instantiation.js';
9 > import { IUserDataSyncLogService, IUserDataSyncStoreService, UserDataSyncErrorCode } from './userDataSync.js';
10 >
11 > export interface IUserDataSyncAccount {
12 > readonly authenticationProviderId: string;
13 > readonly token: string;
14 > }
15 >
16 > export const IUserDataSyncAccountService = createDecorator<IUserDataSyncAccountService>('IUserDataSyncAccountService');
17 > export interface IUserDataSyncAccountService {
18 > readonly _serviceBrand: undefined;
19 >
20 > readonly onTokenFailed: Event<boolean/*bail out*/>;
21 > readonly account: IUserDataSyncAccount | undefined;
22 > readonly onDidChangeAccount: Event<IUserDataSyncAccount | undefined>;
23 > updateAccount(account: IUserDataSyncAccount | undefined): Promise<void>;
24 >
25 > }
26 >
27 > export class UserDataSyncAccountService extends Disposable implements IUserDataSyncAccountService {
28 >
29 > _serviceBrand: undefined;
30 >
31 > private _account: IUserDataSyncAccount | undefined;
32 > get account(): IUserDataSyncAccount | undefined { return this._account; }
33 > private _onDidChangeAccount = this._register(new Emitter<IUserDataSyncAccount | undefined>());
34 > readonly onDidChangeAccount = this._onDidChangeAccount.event;
35 >
36 > private _onTokenFailed: Emitter<boolean> = this._register(new Emitter<boolean>());
37 > readonly onTokenFailed: Event<boolean> = this._onTokenFailed.event;
38 >
39 > private wasTokenFailed: boolean = false;
40 >
41 > constructor(
42 > @IUserDataSyncStoreService private readonly userDataSyncStoreService: IUserDataSyncStoreService, userDataSyncAccount.ts
43 > @IUserDataSyncLogService private readonly logService: IUserDataSyncLogService,
44 > ) {
45 > super();
46 > this._register(userDataSyncStoreService.onTokenFailed(code => {
47 this.logService.info('Settings Sync auth token failed', this.account?.authenticationProviderId, this.wasTokenFailed, code);
48 this.updateAccount(undefined);
53 }
54 this.wasTokenFailed = true;
56 > this._register(userDataSyncStoreService.onTokenSucceed(() => this.wasTokenFailed = false));
57 > }
59 > async updateAccount(account: IUserDataSyncAccount | undefined): Promise<void> {
60 > if (account && this._account ? account.token !== this._account.token || account.authenticationProviderId !== this._account.authenticationProviderId : account !== this._account) { userDataSyncAccount.ts
61 > this._account = account;
62 > if (this._account) {
63 > this.userDataSyncStoreService.setAuthToken(this._account.token, this._account.authenticationProviderId);
64 > }
65 > this._onDidChangeAccount.fire(account);
66 > }
67 > }
69 > }
70
src/vs/base/test/common/utils.ts 58 covered LOC · 14 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- utils.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { DisposableStore, DisposableTracker, IDisposable, setDisposableTracker } from '../../common/lifecycle.js';
7 > import { join } from '../../common/path.js';
8 > import { isWindows } from '../../common/platform.js';
9 > import { URI } from '../../common/uri.js';
10 >
11 > export type ValueCallback<T = any> = (value: T | Promise<T>) => void;
12 >
13 > export function toResource(this: any, path: string): URI {
14 if (isWindows) {
15 return URI.file(join('C:\\', btoa(this.test.fullTitle()), path));
18 return URI.file(join('/', btoa(this.test.fullTitle()), path));
19 }
20 > utils.ts
21 > export function suiteRepeat(n: number, description: string, callback: (this: any) => void): void {
22 for (let i = 0; i < n; i++) {
23 suite(`${description} (iteration ${i})`, callback);
24 }
25 }
26 > utils.ts
27 > export function testRepeat(n: number, description: string, callback: (this: any) => any): void {
28 for (let i = 0; i < n; i++) {
29 test(`${description} (iteration ${i})`, callback);
30 }
31 }
32 > utils.ts
33 export async function assertThrowsAsync(block: () => any, message: string | Error = 'Missing expected exception'): Promise<void> {
34 try {
41 throw err;
42 }
43 > utils.ts
44 > /**
45 > * Use this function to ensure that all disposables are cleaned up at the end of each test in the current suite.
46 > *
47 > * Use `markAsSingleton` if disposable singletons are created lazily that are allowed to outlive the test.
48 > * Make sure that the singleton properly registers all child disposables so that they are excluded too.
49 > *
50 > * @returns A {@link DisposableStore} that can optionally be used to track disposables in the test.
51 > * This will be automatically disposed on test teardown.
52 > */
53 > export function ensureNoDisposablesAreLeakedInTestSuite(): Pick<DisposableStore, 'add'> {
54 > let tracker: DisposableTracker | undefined;
55 > let store: DisposableStore;
56 > setup(() => {
57 > store = new DisposableStore(); utils.ts
58 > tracker = new DisposableTracker();
59 > setDisposableTracker(tracker);
60 > }); utils.ts
61 >
62 > teardown(function (this: import('mocha').Context) {
63 > store.dispose(); utils.ts
64 > setDisposableTracker(null);
65 > if (this.currentTest?.state !== 'failed') {
66 > const result = tracker!.computeLeakingDisposables();
67 > if (result) {
68 console.error(result.details);
69 throw new Error(`There are ${result.leaks.length} undisposed disposables!${result.details}`);
70 }
71 > } utils.ts
72 > }); utils.ts
73 >
74 > // Wrap store as the suite function is called before it's initialized
75 > const testContext = {
76 > add<T extends IDisposable>(o: T): T {
77 > return store.add(o); utils.ts
78 > }
79 > }; utils.ts
80 > return testContext;
81 > }
82 >
83 > export function throwIfDisposablesAreLeaked(body: () => void, logToConsole = true): void {
84 const tracker = new DisposableTracker();
85 setDisposableTracker(tracker);
88 computeLeakingDisposables(tracker, logToConsole);
89 }
90 > utils.ts
91 export async function throwIfDisposablesAreLeakedAsync(body: () => Promise<void>): Promise<void> {
92 const tracker = new DisposableTracker();
96 computeLeakingDisposables(tracker);
97 }
98 > utils.ts
99 function computeLeakingDisposables(tracker: DisposableTracker, logToConsole = true) {
100 const result = tracker.computeLeakingDisposables();
src/vs/platform/registry/common/platform.ts 54 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- platform.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as Assert from '../../../base/common/assert.js';
7 > import * as Types from '../../../base/common/types.js';
8 >
9 > export interface IRegistry {
10 >
11 > /**
12 > * Adds the extension functions and properties defined by data to the
13 > * platform. The provided id must be unique.
14 > * @param id a unique identifier
15 > * @param data a contribution
16 > */
17 > add(id: string, data: any): void;
18 >
19 > /**
20 > * Returns true iff there is an extension with the provided id.
21 > * @param id an extension identifier
22 > */
23 > knows(id: string): boolean;
24 >
25 > /**
26 > * Returns the extension functions and properties defined by the specified key or null.
27 > * @param id an extension identifier
28 > */
29 > as<T>(id: string): T;
30 > }
31 >
32 > class RegistryImpl implements IRegistry {
33 >
34 > private readonly data = new Map<string, any>();
35 >
36 > public add(id: string, data: any): void {
37 > Assert.ok(Types.isString(id)); platform.ts
38 > Assert.ok(Types.isObject(data));
39 > Assert.ok(!this.data.has(id), 'There is already an extension with this id');
40 >
41 > this.data.set(id, data);
42 > }
44 > public knows(id: string): boolean {
45 return this.data.has(id);
46 }
48 > public as(id: string): any {
49 > return this.data.get(id) || null; platform.ts
50 > }
52 > public dispose() {
53 this.data.forEach((value) => {
54 if (Types.isFunction(value.dispose)) {
58 this.data.clear();
59 }
61 > }
62 >
63 > export const Registry: IRegistry = new RegistryImpl();
src/vs/base/common/process.ts 53 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- process.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { INodeProcess, isMacintosh, isWindows } from './platform.js';
7 >
8 > let safeProcess: Omit<INodeProcess, 'arch'> & { arch: string | undefined };
9 > declare const process: INodeProcess;
10 >
11 > // Native sandbox environment
12 > const vscodeGlobal = (globalThis as { vscode?: { process?: INodeProcess } }).vscode;
13 > if (typeof vscodeGlobal !== 'undefined' && typeof vscodeGlobal.process !== 'undefined') {
14 const sandboxProcess: INodeProcess = vscodeGlobal.process;
15 safeProcess = {
20 };
21 }
22 > process.ts
23 > // Native node.js environment
24 > else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') {
25 > safeProcess = {
26 > get platform() { return process.platform; },
27 > get arch() { return process.arch; },
28 > get env() { return process.env; },
29 > cwd() { return process.env['VSCODE_CWD'] || process.cwd(); }
30 > };
31 }
32
44 };
45 }
46 > process.ts
47 > /**
48 > * Provides safe access to the `cwd` property in node.js, sandboxed or web
49 > * environments.
50 > *
51 > * Note: in web, this property is hardcoded to be `/`.
52 > *
53 > * @skipMangle
54 > */
55 > export const cwd = safeProcess.cwd;
56 >
57 > /**
58 > * Provides safe access to the `env` property in node.js, sandboxed or web
59 > * environments.
60 > *
61 > * Note: in web, this property is hardcoded to be `{}`.
62 > */
63 > export const env = safeProcess.env;
64 >
65 > /**
66 > * Provides safe access to the `platform` property in node.js, sandboxed or web
67 > * environments.
68 > */
69 > export const platform = safeProcess.platform;
70 >
71 > /**
72 > * Provides safe access to the `arch` method in node.js, sandboxed or web
73 > * environments.
74 > * Note: `arch` is `undefined` in web
75 > */
76 > export const arch = safeProcess.arch;
src/vs/platform/userDataSync/common/ignoredExtensions.ts 53 covered LOC · 12 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- ignoredExtensions.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { distinct } from '../../../base/common/arrays.js';
7 > import { ConfigurationTarget, IConfigurationService } from '../../configuration/common/configuration.js';
8 > import { ILocalExtension } from '../../extensionManagement/common/extensionManagement.js';
9 > import { createDecorator } from '../../instantiation/common/instantiation.js';
10 >
11 > export const IIgnoredExtensionsManagementService = createDecorator<IIgnoredExtensionsManagementService>('IIgnoredExtensionsManagementService');
12 > export interface IIgnoredExtensionsManagementService {
13 > readonly _serviceBrand: undefined;
14 >
15 > getIgnoredExtensions(installed: ILocalExtension[]): string[];
16 >
17 > hasToNeverSyncExtension(extensionId: string): boolean;
18 > hasToAlwaysSyncExtension(extensionId: string): boolean;
19 > updateIgnoredExtensions(ignoredExtensionId: string, ignore: boolean): Promise<void>;
20 > updateSynchronizedExtensions(ignoredExtensionId: string, sync: boolean): Promise<void>;
21 > }
22 >
23 > export class IgnoredExtensionsManagementService implements IIgnoredExtensionsManagementService {
24 >
25 > declare readonly _serviceBrand: undefined;
26 >
27 > constructor(
28 > @IConfigurationService private readonly configurationService: IConfigurationService, ignoredExtensions.ts
29 > ) {
30 > }
32 > hasToNeverSyncExtension(extensionId: string): boolean {
33 const configuredIgnoredExtensions = this.getConfiguredIgnoredExtensions();
34 return configuredIgnoredExtensions.includes(extensionId.toLowerCase());
35 }
37 > hasToAlwaysSyncExtension(extensionId: string): boolean {
38 const configuredIgnoredExtensions = this.getConfiguredIgnoredExtensions();
39 return configuredIgnoredExtensions.includes(`-${extensionId.toLowerCase()}`);
40 }
42 > updateIgnoredExtensions(ignoredExtensionId: string, ignore: boolean): Promise<void> {
43 // first remove the extension completely from ignored extensions
44 let currentValue = [...this.configurationService.getValue<string[]>('settingsSync.ignoredExtensions')].map(id => id.toLowerCase());
52 return this.configurationService.updateValue('settingsSync.ignoredExtensions', currentValue.length ? currentValue : undefined, ConfigurationTarget.USER);
53 }
55 > updateSynchronizedExtensions(extensionId: string, sync: boolean): Promise<void> {
56 // first remove the extension completely from ignored extensions
57 let currentValue = [...this.configurationService.getValue<string[]>('settingsSync.ignoredExtensions')].map(id => id.toLowerCase());
65 return this.configurationService.updateValue('settingsSync.ignoredExtensions', currentValue.length ? currentValue : undefined, ConfigurationTarget.USER);
66 }
68 > getIgnoredExtensions(installed: ILocalExtension[]): string[] {
69 > const defaultIgnoredExtensions = installed.filter(i => i.isMachineScoped).map(i => i.identifier.id.toLowerCase()); ignoredExtensions.ts
70 > const value = this.getConfiguredIgnoredExtensions().map(id => id.toLowerCase());
71 > const added: string[] = [], removed: string[] = [];
72 > if (Array.isArray(value)) {
73 > for (const key of value) {
74 if (key.startsWith('-')) {
75 removed.push(key.substring(1));
78 }
79 }
81 > return distinct([...defaultIgnoredExtensions, ...added,].filter(setting => !removed.includes(setting)));
82 > }
84 > private getConfiguredIgnoredExtensions(): ReadonlyArray<string> {
85 > return (this.configurationService.getValue<string[]>('settingsSync.ignoredExtensions') || []).map(id => id.toLowerCase()); ignoredExtensions.ts
86 > }
src/vs/platform/remote/common/remoteHosts.ts 52 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- remoteHosts.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Schemas } from '../../../base/common/network.js';
7 > import { URI } from '../../../base/common/uri.js';
8 >
9 > export function getRemoteAuthority(uri: URI): string | undefined {
10 return uri.scheme === Schemas.vscodeRemote ? uri.authority : undefined;
11 }
13 > export function getRemoteName(authority: string): string;
14 > export function getRemoteName(authority: undefined): undefined;
15 > export function getRemoteName(authority: string | undefined): string | undefined;
16 > export function getRemoteName(authority: string | undefined): string | undefined {
17 if (!authority) {
18 return undefined;
25 return authority.substr(0, pos);
26 }
28 > /**
29 > * Returns the suffix part of the authority after the '+' character.
30 > * For remote connections, this is typically the server/tunnel identifier.
31 > * Examples:
32 > * - For tunnels: `tunnel+myTunnel` returns `myTunnel`
33 > * - For SSH: `ssh+myserver` returns `myserver`
34 > * - For localhost: `localhost:8000` returns `undefined`
35 > * @param authority The remote authority string.
36 > * @returns The suffix after the '+' character, or undefined if there is no '+' character.
37 > */
38 > export function getRemoteServerRootPath(authority: string): string | undefined;
39 > export function getRemoteServerRootPath(authority: undefined): undefined;
40 > export function getRemoteServerRootPath(authority: string | undefined): string | undefined;
41 > export function getRemoteServerRootPath(authority: string | undefined): string | undefined {
42 if (!authority) {
43 return undefined;
49 return authority.substring(pos + 1);
50 }
52 > export function parseAuthorityWithPort(authority: string): { host: string; port: number } {
53 const { host, port } = parseAuthority(authority);
54 if (typeof port === 'undefined') {
57 return { host, port };
58 }
60 > export function parseAuthorityWithOptionalPort(authority: string, defaultPort: number): { host: string; port: number } {
61 let { host, port } = parseAuthority(authority);
62 if (typeof port === 'undefined') {
65 return { host, port };
66 }
68 function parseAuthority(authority: string): { host: string; port: number | undefined } {
69 // check for ipv6 with port
88 return { host: authority, port: undefined };
89 }
91 > const loopbackHosts = new Set([
92 > 'localhost',
93 > '127.0.0.1',
94 > '::1',
95 > '[::1]',
96 > '0000:0000:0000:0000:0000:0000:0000:0001',
97 > '[0000:0000:0000:0000:0000:0000:0000:0001]'
98 > ]);
99 >
100 > /**
101 > * Returns whether the given host (as found in a direct `<host>:<port>` remote
102 > * authority) refers to the local loopback interface. The check is intentionally
103 > * strict: only `localhost` and the IPv4/IPv6 loopback literals are considered
104 > * local. Any other host (a routable IP address or a hostname) is treated as a
105 > * connection that leaves the local machine.
106 > */
107 > export function isLoopbackHost(host: string): boolean {
108 return loopbackHosts.has(host.toLowerCase());
109 }
src/vs/platform/userDataSync/common/promptsSync/promptsMerge.ts 51 covered LOC · 8 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- promptsMerge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IStringDictionary } from '../../../../base/common/collections.js';
7 >
8 > export interface IMergeResult {
9 > local: {
10 > added: IStringDictionary<string>;
11 > updated: IStringDictionary<string>;
12 > removed: string[];
13 > };
14 > remote: {
15 > added: IStringDictionary<string>;
16 > updated: IStringDictionary<string>;
17 > removed: string[];
18 > };
19 > conflicts: string[];
20 > }
21 >
22 > export function merge(local: IStringDictionary<string>, remote: IStringDictionary<string> | null, base: IStringDictionary<string> | null): IMergeResult {
23 > const localAdded: IStringDictionary<string> = {}; promptsMerge.ts
24 > const localUpdated: IStringDictionary<string> = {};
25 > const localRemoved: Set<string> = new Set<string>();
26 >
27 > if (!remote) {
28 > return {
29 > local: { added: localAdded, updated: localUpdated, removed: [...localRemoved.values()] },
30 > remote: { added: local, updated: {}, removed: [] },
31 > conflicts: []
32 > };
33 > }
34
35 const localToRemote = compare(local, remote);
36 > if (localToRemote.added.size === 0 && localToRemote.removed.size === 0 && localToRemote.updated.size === 0) { promptsMerge.ts
37 // No changes found between local and remote.
38 return {
150 };
151 }
153 > function compare(from: IStringDictionary<string> | null, to: IStringDictionary<string> | null): { added: Set<string>; removed: Set<string>; updated: Set<string> } { promptsMerge.ts
154 > const fromKeys = from ? Object.keys(from) : [];
155 > const toKeys = to ? Object.keys(to) : [];
156 > const added = toKeys.filter(key => !fromKeys.includes(key)).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
157 > const removed = fromKeys.filter(key => !toKeys.includes(key)).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
158 > const updated: Set<string> = new Set<string>();
159 >
160 > for (const key of fromKeys) {
161 if (removed.has(key)) {
162 continue;
168 }
169 }
171 > return { added, removed, updated };
172 > }
174 > export function areSame(a: IStringDictionary<string>, b: IStringDictionary<string>): boolean {
175 > const { added, removed, updated } = compare(a, b); promptsMerge.ts
176 > return added.size === 0 && removed.size === 0 && updated.size === 0;
177 > }
src/vs/platform/userDataSync/common/snippetsMerge.ts 51 covered LOC · 9 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- snippetsMerge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IStringDictionary } from '../../../base/common/collections.js';
7 >
8 > export interface IMergeResult {
9 > local: {
10 > added: IStringDictionary<string>;
11 > updated: IStringDictionary<string>;
12 > removed: string[];
13 > };
14 > remote: {
15 > added: IStringDictionary<string>;
16 > updated: IStringDictionary<string>;
17 > removed: string[];
18 > };
19 > conflicts: string[];
20 > }
21 >
22 > export function merge(local: IStringDictionary<string>, remote: IStringDictionary<string> | null, base: IStringDictionary<string> | null): IMergeResult {
23 > const localAdded: IStringDictionary<string> = {}; snippetsMerge.ts
24 > const localUpdated: IStringDictionary<string> = {};
25 > const localRemoved: Set<string> = new Set<string>();
26 >
27 > if (!remote) {
28 > return { snippetsMerge.ts
29 > local: { added: localAdded, updated: localUpdated, removed: [...localRemoved.values()] },
30 > remote: { added: local, updated: {}, removed: [] },
31 > conflicts: []
32 > };
33 > }
34
35 const localToRemote = compare(local, remote);
36 > if (localToRemote.added.size === 0 && localToRemote.removed.size === 0 && localToRemote.updated.size === 0) { snippetsMerge.ts
37 // No changes found between local and remote.
38 return {
150 };
151 }
153 > function compare(from: IStringDictionary<string> | null, to: IStringDictionary<string> | null): { added: Set<string>; removed: Set<string>; updated: Set<string> } { snippetsMerge.ts
154 > const fromKeys = from ? Object.keys(from) : [];
155 > const toKeys = to ? Object.keys(to) : [];
156 > const added = toKeys.filter(key => !fromKeys.includes(key)).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
157 > const removed = fromKeys.filter(key => !toKeys.includes(key)).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
158 > const updated: Set<string> = new Set<string>();
159 >
160 > for (const key of fromKeys) {
161 if (removed.has(key)) {
162 continue;
168 }
169 }
171 > return { added, removed, updated };
172 > }
174 > export function areSame(a: IStringDictionary<string>, b: IStringDictionary<string>): boolean {
175 > const { added, removed, updated } = compare(a, b); snippetsMerge.ts
176 > return added.size === 0 && removed.size === 0 && updated.size === 0;
177 > }
src/vs/base/common/assert.ts 50 covered LOC · 9 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- assert.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { BugIndicatingError, onUnexpectedError } from './errors.js';
7 >
8 > /**
9 > * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
10 > *
11 > * @deprecated Use `assert(...)` instead.
12 > * This method is usually used like this:
13 > * ```ts
14 > * import * as assert from 'vs/base/common/assert';
15 > * assert.ok(...);
16 > * ```
17 > *
18 > * However, `assert` in that example is a user chosen name.
19 > * There is no tooling for generating such an import statement.
20 > * Thus, the `assert(...)` function should be used instead.
21 > */
22 > export function ok(value?: unknown, message?: string) {
23 > if (!value) { assert.ts
24 throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
25 }
26 > } assert.ts
27 > assert.ts
28 > export function assertNever(value: never, message = 'Unreachable'): never {
29 throw new Error(message);
30 }
31 > assert.ts
32 > export function softAssertNever(value: never): void {
33 // no-op
34 }
35 > assert.ts
36 > /**
37 > * Asserts that a condition is `truthy`.
38 > *
39 > * @throws provided {@linkcode messageOrError} if the {@linkcode condition} is `falsy`.
40 > *
41 > * @param condition The condition to assert.
42 > * @param messageOrError An error message or error object to throw if condition is `falsy`.
43 > */
44 > export function assert(
45 condition: boolean,
46 messageOrError: string | Error = 'unexpected state',
55 }
56 }
57 > assert.ts
58 > /**
59 > * Like assert, but doesn't throw.
60 > */
61 > export function softAssert(condition: boolean, message = 'Soft Assertion Failed'): void {
62 if (!condition) {
63 onUnexpectedError(new BugIndicatingError(message));
64 }
65 }
66 > assert.ts
67 > /**
68 > * condition must be side-effect free!
69 > */
70 > export function assertFn(condition: () => boolean): void {
71 if (!condition()) {
72 // eslint-disable-next-line no-debugger
77 }
78 }
79 > assert.ts
80 > export function checkAdjacentItems<T>(items: readonly T[], predicate: (item1: T, item2: T) => boolean): boolean {
81 let i = 0;
82 while (i < items.length - 1) {
src/vs/base/test/common/virtualScheduling/timeApi.ts 48 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- timeApi.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export interface TimeoutId { readonly _timeoutIdBrand: void }
7 > export interface IntervalId { readonly _intervalIdBrand: void }
8 > export interface ImmediateId { readonly _immediateIdBrand: void }
9 > export type AnimationFrameId = number & { readonly _animationFrameIdBrand: void };
10 >
11 > /**
12 > * The subset of host time APIs the processor and embeddings need.
13 > *
14 > * Used both for the real host API (captured via {@link captureGlobalTimeApi})
15 > * and for the virtual replacement that runs through a {@link VirtualClock}.
16 > *
17 > * Keeping this as a plain interface means the processor never reaches into
18 > * `globalThis` directly: the boundary between "real time" and "virtual time"
19 > * is exactly which `TimeApi` instance is in use.
20 > */
21 > export interface TimeApi {
22 > setTimeout(handler: () => void, timeout?: number): TimeoutId;
23 > clearTimeout(id: TimeoutId): void;
24 > setInterval(handler: () => void, interval: number): IntervalId;
25 > clearInterval(id: IntervalId): void;
26 > setImmediate?: ((handler: () => void) => ImmediateId);
27 > clearImmediate?: ((id: ImmediateId) => void);
28 > requestAnimationFrame?: ((cb: (time: number) => void) => AnimationFrameId);
29 > cancelAnimationFrame?: ((id: AnimationFrameId) => void);
30 > Date: DateConstructor;
31 > }
32 >
33 > export function captureGlobalTimeApi(): TimeApi {
34 > return {
35 > setTimeout: globalThis.setTimeout.bind(globalThis) as unknown as TimeApi['setTimeout'],
36 > clearTimeout: globalThis.clearTimeout.bind(globalThis) as unknown as TimeApi['clearTimeout'],
37 > setInterval: globalThis.setInterval.bind(globalThis) as unknown as TimeApi['setInterval'],
38 > clearInterval: globalThis.clearInterval.bind(globalThis) as unknown as TimeApi['clearInterval'],
39 > setImmediate: globalThis.setImmediate?.bind(globalThis) as unknown as TimeApi['setImmediate'],
40 > clearImmediate: globalThis.clearImmediate?.bind(globalThis) as unknown as TimeApi['clearImmediate'],
41 > requestAnimationFrame: globalThis.requestAnimationFrame?.bind(globalThis) as unknown as TimeApi['requestAnimationFrame'],
42 > cancelAnimationFrame: globalThis.cancelAnimationFrame?.bind(globalThis) as unknown as TimeApi['cancelAnimationFrame'],
43 > Date: globalThis.Date,
44 > };
45 > }
46 >
47 > /** A snapshot of the real host time API at module-load time. */
48 > export const realTimeApi: TimeApi = captureGlobalTimeApi();
src/vs/base/test/common/virtualScheduling/traceLogger.ts 47 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- traceLogger.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { LogEntryLike } from '../executionGraph.js';
7 > import { Trace, TraceContext } from './trace.js';
8 >
9 > /**
10 > * A minimal logger for tests that captures the active {@link Trace} at log
11 > * time so messages can later be woven into a swimlane diagram next to the
12 > * timer events that produced them.
13 > */
14 > export interface ITraceLogger {
15 > log(message: string): void;
16 > warn(message: string): void;
17 > error(message: string): void;
18 > /**
19 > * Run `fn` synchronously and log it as a marker in the trace. The
20 > * marker text is `fn.toString()` so call sites read naturally as e.g.
21 > * `logger.logRun(() => model.trigger())`. Returns whatever `fn`
22 > * returns.
23 > */
24 > logRun<T>(fn: () => T): T;
25 > }
26 >
27 > /**
28 > * One log entry produced by an {@link ITraceLogger}. Extends
29 > * {@link LogEntryLike} (consumed by `buildHistoryFromTasks`) with a level so
30 > * renderers can differentiate `log` / `warn` / `error`.
31 > */
32 > export interface ITraceLogEntry extends LogEntryLike {
33 > readonly trace: Trace;
34 > readonly level: 'log' | 'warn' | 'error';
35 > }
36 >
37 > /**
38 > * Build an {@link ITraceLogger} that pushes every call into `buffer`,
39 > * tagging each entry with the trace that's current at call time.
40 > *
41 > * Pass the same `buffer` to `buildHistoryFromTasks(history, startTime,
42 > * buffer)` to interleave log lines with the timer swimlane.
43 > */
44 > export function createTraceLogger(buffer: ITraceLogEntry[]): ITraceLogger {
45 const make = (level: 'log' | 'warn' | 'error') => (message: string) => {
46 buffer.push({
61 };
62 }
64 > /** Best-effort one-line description of `fn` for trace log markers. */
65 function _describeFn(fn: () => unknown): string {
66 const src = fn.toString();
72 return _collapseWhitespace(src);
73 }
75 function _collapseWhitespace(s: string): string {
76 return s.replace(/\s+/g, ' ').trim();
src/vs/base/common/date.ts 46 covered LOC · 10 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- date.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { localize } from '../../nls.js';
7 > import { Lazy } from './lazy.js';
8 > import { LANGUAGE_DEFAULT } from './platform.js';
9 >
10 > const minute = 60;
11 > const hour = minute * 60;
12 > const day = hour * 24;
13 > const week = day * 7;
14 > const month = day * 30;
15 > const year = day * 365;
16 >
17 > /**
18 > * Create a localized difference of the time between now and the specified date.
19 > * @param date The date to generate the difference from.
20 > * @param appendAgoLabel Whether to append the " ago" to the end.
21 > * @param useFullTimeWords Whether to use full words (eg. seconds) instead of
22 > * shortened (eg. secs).
23 > * @param disallowNow Whether to disallow the string "now" when the difference
24 > * is less than 30 seconds.
25 > */
26 > export function fromNow(date: number | Date, appendAgoLabel?: boolean, useFullTimeWords?: boolean, disallowNow?: boolean): string {
27 if (typeof date === 'undefined') {
28 return localize('date.fromNow.unknown', 'unknown');
205 }
206 }
207 > date.ts
208 > export function fromNowByDay(date: number | Date, appendAgoLabel?: boolean, useFullTimeWords?: boolean): string {
209 if (typeof date !== 'number') {
210 date = date.getTime();
226 return fromNow(date, appendAgoLabel, useFullTimeWords);
227 }
228 > date.ts
229 > /**
230 > * Gets a readable duration with intelligent/lossy precision. For example "40ms" or "3.040s")
231 > * @param ms The duration to get in milliseconds.
232 > * @param useFullTimeWords Whether to use full words (eg. seconds) instead of
233 > * shortened (eg. secs).
234 > */
235 > export function getDurationString(ms: number, useFullTimeWords?: boolean) {
236 const seconds = Math.abs(ms / 1000);
237 if (seconds < 1) {
257 return localize('duration.d', '{0} days', Math.round(ms / (1000 * day)));
258 }
259 > date.ts
260 > export function toLocalISOString(date: Date): string {
261 return date.getFullYear() +
262 '-' + String(date.getMonth() + 1).padStart(2, '0') +
268 'Z';
269 }
270 > date.ts
271 > export const safeIntl = {
272 > DateTimeFormat(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): Lazy<Intl.DateTimeFormat> {
273 return new Lazy(() => {
274 try {
279 });
280 },
281 > Collator(locales?: Intl.LocalesArgument, options?: Intl.CollatorOptions): Lazy<Intl.Collator> { date.ts
282 return new Lazy(() => {
283 try {
288 });
289 },
290 > Segmenter(locales?: Intl.LocalesArgument, options?: Intl.SegmenterOptions): Lazy<Intl.Segmenter> { date.ts
291 return new Lazy(() => {
292 try {
297 });
298 },
299 > Locale(tag: Intl.Locale | string, options?: Intl.LocaleOptions): Lazy<Intl.Locale> { date.ts
300 return new Lazy(() => {
301 try {
306 });
307 },
308 > NumberFormat(locales?: Intl.LocalesArgument, options?: Intl.NumberFormatOptions): Lazy<Intl.NumberFormat> { date.ts
309 return new Lazy(() => {
310 try {
src/vs/base/common/jsonEdit.ts 46 covered LOC · 15 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- jsonEdit.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { findNodeAtLocation, JSONPath, Node, ParseError, parseTree, Segment } from './json.js';
7 > import { Edit, format, FormattingOptions, isEOL } from './jsonFormatter.js';
8 >
9 >
10 > export function removeProperty(text: string, path: JSONPath, formattingOptions: FormattingOptions): Edit[] {
11 return setProperty(text, path, undefined, formattingOptions);
12 }
14 > export function setProperty(text: string, originalPath: JSONPath, value: unknown, formattingOptions: FormattingOptions, getInsertionIndex?: (properties: string[]) => number): Edit[] {
15 > const path = originalPath.slice(); jsonEdit.ts
16 > const errors: ParseError[] = [];
17 > const root = parseTree(text, errors);
18 > let parent: Node | undefined = undefined;
19 >
20 > let lastSegment: Segment | undefined = undefined;
21 > while (path.length > 0) {
22 > lastSegment = path.pop();
23 > parent = findNodeAtLocation(root, path);
24 > if (parent === undefined && value !== undefined) {
25 if (typeof lastSegment === 'string') {
26 value = { [lastSegment]: value };
28 value = [value];
29 }
30 > } else { jsonEdit.ts
31 > break;
32 > }
33 > }
34 >
35 > if (!parent) {
36 // empty document
37 if (value === undefined) { // delete
39 }
40 return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions);
41 > } else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { jsonEdit.ts
42 > const existing = findNodeAtLocation(parent, [lastSegment]); jsonEdit.ts
43 > if (existing !== undefined) {
44 if (value === undefined) { // delete
45 if (!existing.parent) {
66 return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions);
67 }
68 > } else { jsonEdit.ts
69 > if (value === undefined) { // delete jsonEdit.ts
70 > return []; // property does not exist, nothing to do jsonEdit.ts
71 > }
72 const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
73 > const index = getInsertionIndex ? getInsertionIndex(parent.children.map(p => p.children![0].value)) : parent.children.length; jsonEdit.ts
74 > let edit: Edit;
75 > if (index > 0) {
76 const previous = parent.children[index - 1];
77 edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };
83 return withFormatting(text, edit, formattingOptions);
84 }
85 > } else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { jsonEdit.ts
86 if (value !== undefined) {
87 // Insert
118 throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);
119 }
120 > } jsonEdit.ts
121 > jsonEdit.ts
122 > export function withFormatting(text: string, edit: Edit, formattingOptions: FormattingOptions): Edit[] {
123 // apply the edit
124 let newText = applyEdit(text, edit);
150 return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
151 }
152 > jsonEdit.ts
153 > export function applyEdit(text: string, edit: Edit): string {
154 return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
155 }
156 > jsonEdit.ts
157 > export function applyEdits(text: string, edits: Edit[]): string {
158 const sortedEdits = edits.slice(0).sort((a, b) => {
159 const diff = a.offset - b.offset;
src/vs/platform/uriIdentity/common/uriIdentity.ts 46 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- uriIdentity.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { URI } from '../../../base/common/uri.js';
7 > import { createDecorator } from '../../instantiation/common/instantiation.js';
8 > import { IExtUri } from '../../../base/common/resources.js';
9 >
10 >
11 > export const IUriIdentityService = createDecorator<IUriIdentityService>('IUriIdentityService');
12 >
13 > export interface IUriIdentityService {
14 >
15 > readonly _serviceBrand: undefined;
16 >
17 > /**
18 > * Uri extensions that are aware of casing.
19 > */
20 > readonly extUri: IExtUri;
21 >
22 > /**
23 > * Returns a canonical uri for the given resource. Different uris can point to the same
24 > * resource. That's because of casing or missing normalization, e.g the following uris
25 > * are different but refer to the same document (because windows paths are not case-sensitive)
26 > *
27 > * ```txt
28 > * file:///c:/foo/bar.txt
29 > * file:///c:/FOO/BAR.txt
30 > * ```
31 > *
32 > * This function should be invoked when feeding uris into the system that represent the truth,
33 > * e.g document uris or marker-to-document associations etc. This function should NOT be called
34 > * to pretty print a label nor to sanitize a uri.
35 > *
36 > * Samples:
37 > *
38 > * | in | out | |
39 > * |---|---|---|
40 > * | `file:///foo/bar/../bar` | `file:///foo/bar` | n/a |
41 > * | `file:///foo/bar/../bar#frag` | `file:///foo/bar#frag` | keep fragment |
42 > * | `file:///foo/BAR` | `file:///foo/bar` | assume ignore case |
43 > * | `file:///foo/bar/../BAR?q=2` | `file:///foo/BAR?q=2` | query makes it a different document |
44 > */
45 > asCanonicalUri(uri: URI): URI;
46 > }
src/vs/base/test/common/virtualScheduling/virtualTimeApi.ts 45 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- virtualTimeApi.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IDisposable } from '../../../common/lifecycle.js';
7 > import { realTimeApi, TimeApi } from './timeApi.js';
8 > import { ROOT_TRACE, TraceContext } from './trace.js';
9 > import { VirtualClock } from './virtualClock.js';
10 >
11 > // V8 default `Error.stackTraceLimit` of 10 swallows everything past the
12 > // first async boundary in the stacks we capture for trace diagnostics.
13 > // Bump it so swimlane callers actually see the user code that scheduled a
14 > // timer rather than just the Promise wrapper.
15 > if (typeof Error.stackTraceLimit === 'number' && Error.stackTraceLimit < 50) {
16 > Error.stackTraceLimit = 50;
17 > }
18 >
19 > /** Virtual timer IDs are `IDisposable`s. Recover one from an opaque id. */
20 function asDisposable(id: unknown): IDisposable | undefined {
21 if (id === null || typeof id !== 'object') { return undefined; }
23 return typeof maybe.dispose === 'function' ? id as IDisposable : undefined;
24 }
26 > export interface CreateVirtualTimeApiOptions {
27 > /**
28 > * If `true`, `requestAnimationFrame` is faked: callbacks are scheduled
29 > * onto the virtual queue at `now + 16ms` and the resulting event hints
30 > * the embedding to use a real `requestAnimationFrame` so the host can
31 > * reflow before the callback runs. Useful for fixtures that need DOM
32 > * measurements after rAF callbacks.
33 > *
34 > * If `false` (default), `requestAnimationFrame` is left to the host.
35 > */
36 > readonly fakeRequestAnimationFrame?: boolean;
37 > }
38 >
39 > /**
40 > * Build a {@link TimeApi} that schedules every timer call into `clock`'s
41 > * virtual queue, capturing the current trace at schedule time so that
42 > * causal chains (`setTimeout` → `setTimeout`, etc.) are preserved.
43 > *
44 > * The returned API is suitable to install with {@link pushGlobalTimeApi},
45 > * which is what {@link runWithFakedTimers} does internally.
46 > */
47 > export function createVirtualTimeApi(
48 clock: VirtualClock,
49 options?: CreateVirtualTimeApiOptions,
190 return api;
191 }
193 > // Re-exported for convenience: many tests want to install both at once.
194 > export { pushGlobalTimeApi } from './globalTimeApi.js';
src/vs/platform/userDataSync/common/mcpSync.ts 45 covered LOC · 6 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- mcpSync.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IConfigurationService } from '../../configuration/common/configuration.js';
7 > import { IEnvironmentService } from '../../environment/common/environment.js';
8 > import { IFileService } from '../../files/common/files.js';
9 > import { ILogService } from '../../log/common/log.js';
10 > import { IStorageService } from '../../storage/common/storage.js';
11 > import { ITelemetryService } from '../../telemetry/common/telemetry.js';
12 > import { IUriIdentityService } from '../../uriIdentity/common/uriIdentity.js';
13 > import { IUserDataProfile } from '../../userDataProfile/common/userDataProfile.js';
14 > import { AbstractJsonSynchronizer } from './abstractJsonSynchronizer.js';
15 > import { IUserDataSyncLocalStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource } from './userDataSync.js';
16 >
17 > interface IMcpSyncContent {
18 > mcp?: string;
19 > }
20 >
21 > export function getMcpContentFromSyncContent(syncContent: string, logService: ILogService): string | null {
22 try {
23 const parsed = <IMcpSyncContent>JSON.parse(syncContent);
28 }
29 }
30 > mcpSync.ts
31 > export class McpSynchroniser extends AbstractJsonSynchronizer implements IUserDataSynchroniser {
32 >
33 > constructor(
34 > profile: IUserDataProfile, mcpSync.ts
35 > collection: string | undefined,
36 > @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
37 > @IUserDataSyncLocalStoreService userDataSyncLocalStoreService: IUserDataSyncLocalStoreService,
38 > @IUserDataSyncLogService logService: IUserDataSyncLogService,
39 > @IConfigurationService configurationService: IConfigurationService,
40 > @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
41 > @IFileService fileService: IFileService,
42 > @IEnvironmentService environmentService: IEnvironmentService,
43 > @IStorageService storageService: IStorageService,
44 > @ITelemetryService telemetryService: ITelemetryService,
45 > @IUriIdentityService uriIdentityService: IUriIdentityService,
46 > ) {
47 > super(profile.mcpResource, { syncResource: SyncResource.Mcp, profile }, collection, 'mcp.json', fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
48 > }
49 > mcpSync.ts
50 > protected getContentFromSyncContent(syncContent: string): string | null {
51 return getMcpContentFromSyncContent(syncContent, this.logService);
52 }
53 > mcpSync.ts
54 > protected toSyncContent(mcp: string | null): IMcpSyncContent {
55 return mcp ? { mcp } : {};
56 }
57 > } mcpSync.ts
src/vs/base/test/common/virtualScheduling/runWithFakedTimers.ts 44 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- runWithFakedTimers.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationTokenSource } from '../../../common/cancellation.js';
7 > import { drainMicrotasksEmbedding } from './embedding.js';
8 > import { pushGlobalTimeApi } from './globalTimeApi.js';
9 > import { realTimeApi } from './timeApi.js';
10 > import { untilToken, VirtualTimeProcessor } from './processor.js';
11 > import { createRecordingRealTimeApi, RecordedTimerEvent } from './recordingTimeApi.js';
12 > import { VirtualClock } from './virtualClock.js';
13 > import { createVirtualTimeApi } from './virtualTimeApi.js';
14 >
15 > export interface RunWithFakedTimersOptions {
16 > readonly startTime?: number;
17 > /** Default `true`. Set `false` to bypass virtual time entirely (for
18 > * cases where the same test is parameterised over real/virtual time). */
19 > readonly useFakeTimers?: boolean;
20 > /** No effect in the new processor; accepted for legacy compatibility.
21 > * The drain-microtasks embedding picks the fastest available macrotask
22 > * primitive automatically. */
23 > readonly useSetImmediate?: boolean;
24 > /** Maximum number of virtual events the run is allowed to execute
25 > * before being rejected. Default 100. */
26 > readonly maxTaskCount?: number;
27 > /**
28 > * If set, called once `fn` resolves with the recorded timer events.
29 > * In virtual mode the events come from the {@link VirtualTimeProcessor}'s
30 > * own history; in real mode a recording wrapper around the host time
31 > * API is installed for the duration of `fn`. Useful for swimlane
32 > * diagnostics.
33 > */
34 > readonly onHistory?: (history: readonly RecordedTimerEvent[]) => void;
35 > }
36 >
37 > /**
38 > * Run `fn` with a virtual clock installed as the global time API.
39 > *
40 > * After `fn` resolves, the virtual queue is drained (so any timers `fn`
41 > * scheduled and `await`ed for, transitively, complete deterministically).
42 > * If `fn` throws, the queue is *not* drained — the original error is
43 > * re-thrown immediately.
44 > */
45 export async function runWithFakedTimers<T>(
46 options: RunWithFakedTimersOptions,
src/vs/base/common/uint.ts 43 covered LOC · 2 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- uint.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export const enum Constants {
7 > /**
8 > * MAX SMI (SMall Integer) as defined in v8.
9 > * one bit is lost for boxing/unboxing flag.
10 > * one bit is lost for sign flag.
11 > * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values
12 > */
13 > MAX_SAFE_SMALL_INTEGER = 1 << 30,
14 >
15 > /**
16 > * MIN SMI (SMall Integer) as defined in v8.
17 > * one bit is lost for boxing/unboxing flag.
18 > * one bit is lost for sign flag.
19 > * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values
20 > */
21 > MIN_SAFE_SMALL_INTEGER = -(1 << 30),
22 >
23 > /**
24 > * Max unsigned integer that fits on 8 bits.
25 > */
26 > MAX_UINT_8 = 255, // 2^8 - 1
27 >
28 > /**
29 > * Max unsigned integer that fits on 16 bits.
30 > */
31 > MAX_UINT_16 = 65535, // 2^16 - 1
32 >
33 > /**
34 > * Max unsigned integer that fits on 32 bits.
35 > */
36 > MAX_UINT_32 = 4294967295, // 2^32 - 1
37 >
38 > UNICODE_SUPPLEMENTARY_PLANE_BEGIN = 0x010000
39 > }
40 >
41 > export function toUint8(v: number): number {
42 if (v < 0) {
43 return 0;
48 return v | 0;
49 }
50 > uint.ts
51 > export function toUint32(v: number): number {
52 if (v < 0) {
53 return 0;
src/vs/platform/userDataSync/common/keybindingsMerge.ts 43 covered LOC · 13 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- keybindingsMerge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { equals } from '../../../base/common/arrays.js';
7 > import { IStringDictionary } from '../../../base/common/collections.js';
8 > import { parse } from '../../../base/common/json.js';
9 > import { FormattingOptions } from '../../../base/common/jsonFormatter.js';
10 > import * as objects from '../../../base/common/objects.js';
11 > import { ContextKeyExpr } from '../../contextkey/common/contextkey.js';
12 > import { IUserFriendlyKeybinding } from '../../keybinding/common/keybinding.js';
13 > import * as contentUtil from './content.js';
14 > import { IUserDataSyncUtilService } from './userDataSync.js';
15 >
16 > interface ICompareResult {
17 > added: Set<string>;
18 > removed: Set<string>;
19 > updated: Set<string>;
20 > }
21 >
22 > interface IMergeResult {
23 > hasLocalForwarded: boolean;
24 > hasRemoteForwarded: boolean;
25 > added: Set<string>;
26 > removed: Set<string>;
27 > updated: Set<string>;
28 > conflicts: Set<string>;
29 > }
30 >
31 function parseKeybindings(content: string): IUserFriendlyKeybinding[] {
32 return parse(content) || [];
33 }
35 export async function merge(localContent: string, remoteContent: string, baseContent: string | null, formattingOptions: FormattingOptions, userDataSyncUtilService: IUserDataSyncUtilService): Promise<{ mergeContent: string; hasChanges: boolean; hasConflicts: boolean }> {
36 const local = parseKeybindings(localContent);
105 return { mergeContent, hasChanges: true, hasConflicts: commandsMergeResult.conflicts.size > 0 };
106 }
108 function computeMergeResult(localToRemote: ICompareResult, baseToLocal: ICompareResult, baseToRemote: ICompareResult): { added: Set<string>; removed: Set<string>; updated: Set<string>; conflicts: Set<string> } {
109 const added: Set<string> = new Set<string>();
196 return { added, removed, updated, conflicts };
197 }
199 function computeMergeResultByKeybinding(local: IUserFriendlyKeybinding[], remote: IUserFriendlyKeybinding[], base: IUserFriendlyKeybinding[] | null, normalizedKeys: IStringDictionary<string>): IMergeResult {
200 const empty = new Set<string>();
222 return { hasLocalForwarded: true, hasRemoteForwarded: true, added, removed, updated, conflicts };
223 }
225 function byKeybinding(keybindings: IUserFriendlyKeybinding[], keys: IStringDictionary<string>) {
226 const map: Map<string, IUserFriendlyKeybinding[]> = new Map<string, IUserFriendlyKeybinding[]>();
237 return map;
238 }
240 function byCommand(keybindings: IUserFriendlyKeybinding[]): Map<string, IUserFriendlyKeybinding[]> {
241 const map: Map<string, IUserFriendlyKeybinding[]> = new Map<string, IUserFriendlyKeybinding[]>();
251 return map;
252 }
254 >
255 function compareByKeybinding(from: Map<string, IUserFriendlyKeybinding[]>, to: Map<string, IUserFriendlyKeybinding[]>): ICompareResult {
256 const fromKeys = [...from.keys()];
273 return { added, removed, updated };
274 }
276 function compareByCommand(from: Map<string, IUserFriendlyKeybinding[]>, to: Map<string, IUserFriendlyKeybinding[]>, normalizedKeys: IStringDictionary<string>): ICompareResult {
277 const fromKeys = [...from.keys()];
294 return { added, removed, updated };
295 }
297 function areSameKeybindingsWithSameCommand(value1: IUserFriendlyKeybinding[], value2: IUserFriendlyKeybinding[]): boolean {
298 // Compare entries adding keybindings
306 return true;
307 }
309 function isSameKeybinding(a: IUserFriendlyKeybinding, b: IUserFriendlyKeybinding): boolean {
310 if (a.command !== b.command) {
327 return true;
328 }
330 function addKeybindings(content: string, keybindings: IUserFriendlyKeybinding[], formattingOptions: FormattingOptions): string {
331 for (const keybinding of keybindings) {
334 return content;
335 }
337 function removeKeybindings(content: string, command: string, formattingOptions: FormattingOptions): string {
338 const keybindings = parseKeybindings(content);
344 return content;
345 }
347 function updateKeybindings(content: string, command: string, keybindings: IUserFriendlyKeybinding[], formattingOptions: FormattingOptions): string {
348 const allKeybindings = parseKeybindings(content);
src/vs/base/test/common/virtualScheduling/globalTimeApi.ts 42 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- globalTimeApi.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IDisposable } from '../../../common/lifecycle.js';
7 > import { captureGlobalTimeApi, realTimeApi, TimeApi } from './timeApi.js';
8 >
9 > /** Cast through `unknown` so we don't widen our typed `TimeApi` shapes to `any`. */
10 > type AsGlobal<K extends keyof typeof globalThis> = (typeof globalThis)[K];
11 >
12 > /**
13 > * Ensure `fn` carries an `originalFn` back-door pointing at the real
14 > * (non-virtual) `setTimeout`. We prefer the existing tag on `fn`, then a tag
15 > * inherited from `previousFn` (which may itself be a wrapper that already
16 > * carried the back-door), and finally fall back to `realTimeApi.setTimeout`
17 > * — which has its own `originalFn` set at module load.
18 > */
19 function ensureSetTimeoutOriginalFn(fn: TimeApi['setTimeout'], previousFn: TimeApi['setTimeout']): TimeApi['setTimeout'] {
20 const tagged = fn as TimeApi['setTimeout'] & { originalFn?: TimeApi['setTimeout'] };
26 return tagged;
27 }
29 > /**
30 > * Replace the global time APIs (`setTimeout`, `setInterval`, …, `Date`,
31 > * optionally `requestAnimationFrame`) with the ones from `api`. Returns a
32 > * disposable that restores the previous globals.
33 > *
34 > * The previous globals are captured *at install time*, so nested installs
35 > * compose correctly (the disposable restores to whatever was current when
36 > * this call was made, not to the original real values).
37 > *
38 > * `setTimeout.originalFn` is preserved on the installed function so callers
39 > * like the component-explorer host can escape virtual time when polling.
40 > * If `api.setTimeout` does not already carry `originalFn`, it is copied from
41 > * the previous global (or defaulted to the real `setTimeout`) so wrapping
42 > * APIs such as a logging wrapper don't drop the back-door.
43 > */
44 > export function pushGlobalTimeApi(api: TimeApi): IDisposable {
45 const previous = captureGlobalTimeApi();
46
74 };
75 }
77 > // One-shot tag on the *real* setTimeout: lets callers (e.g. the
78 > // component-explorer host's polling loop) escape virtual time even after
79 > // pushGlobalTimeApi has installed a virtual version on top. The `originalFn`
80 > // property is not on the `setTimeout` signature by design — it's a back-door
81 > // convention shared with the polling code.
82 > (realTimeApi.setTimeout as unknown as { originalFn: TimeApi['setTimeout'] }).originalFn = realTimeApi.setTimeout;
src/vs/platform/instantiation/common/graph.ts 42 covered LOC · 12 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- graph.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export class Node<T> {
7 >
8 >
9 > readonly incoming = new Map<string, Node<T>>();
10 > readonly outgoing = new Map<string, Node<T>>();
11 >
12 > constructor(
13 readonly key: string,
14 readonly data: T
15 ) { }
16 > } graph.ts
17 >
18 > export class Graph<T> {
19 >
20 > private readonly _nodes = new Map<string, Node<T>>();
21 >
22 > constructor(private readonly _hashFn: (element: T) => string) {
23 // empty
24 }
25 > graph.ts
26 > roots(): Node<T>[] {
27 const ret: Node<T>[] = [];
28 for (const node of this._nodes.values()) {
33 return ret;
34 }
35 > graph.ts
36 > insertEdge(from: T, to: T): void {
37 const fromNode = this.lookupOrInsertNode(from);
38 const toNode = this.lookupOrInsertNode(to);
41 toNode.incoming.set(fromNode.key, fromNode);
42 }
43 > graph.ts
44 > removeNode(data: T): void {
45 const key = this._hashFn(data);
46 this._nodes.delete(key);
50 }
51 }
52 > graph.ts
53 > lookupOrInsertNode(data: T): Node<T> {
54 const key = this._hashFn(data);
55 let node = this._nodes.get(key);
62 return node;
63 }
64 > graph.ts
65 > lookup(data: T): Node<T> | undefined {
66 return this._nodes.get(this._hashFn(data));
67 }
68 > graph.ts
69 > isEmpty(): boolean {
70 return this._nodes.size === 0;
71 }
72 > graph.ts
73 > toString(): string {
74 const data: string[] = [];
75 for (const [key, value] of this._nodes) {
79 return data.join('\n');
80 }
81 > graph.ts
82 > /**
83 > * This is brute force and slow and **only** be used
84 > * to trouble shoot.
85 > */
86 > findCycleSlow() {
87 for (const [id, node] of this._nodes) {
88 const seen = new Set<string>([id]);
94 return undefined;
95 }
96 > graph.ts
97 > private _findCycle(node: Node<T>, seen: Set<string>): string | undefined {
98 for (const [id, outgoing] of node.outgoing) {
99 if (seen.has(id)) {
109 return undefined;
110 }
111 > } graph.ts
src/vs/platform/userDataSync/common/userDataProfilesManifestMerge.ts 41 covered LOC · 9 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataProfilesManifestMerge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { equals } from '../../../base/common/objects.js';
7 > import { IUserDataProfile, UseDefaultProfileFlags } from '../../userDataProfile/common/userDataProfile.js';
8 > import { ISyncUserDataProfile } from './userDataSync.js';
9 >
10 > interface IRelaxedMergeResult {
11 > local: { added: ISyncUserDataProfile[]; removed: IUserDataProfile[]; updated: ISyncUserDataProfile[] };
12 > remote: { added: IUserDataProfile[]; removed: ISyncUserDataProfile[]; updated: IUserDataProfile[] } | null;
13 > }
14 >
15 > export type IMergeResult = Required<IRelaxedMergeResult>;
16 >
17 > interface IUserDataProfileInfo {
18 > readonly id: string;
19 > readonly name: string;
20 > readonly icon?: string;
21 > readonly useDefaultFlags?: UseDefaultProfileFlags;
22 > }
23 >
24 > export function merge(local: IUserDataProfile[], remote: ISyncUserDataProfile[] | null, lastSync: ISyncUserDataProfile[] | null, ignored: string[]): IMergeResult {
25 > const localResult: { added: ISyncUserDataProfile[]; removed: IUserDataProfile[]; updated: ISyncUserDataProfile[] } = { added: [], removed: [], updated: [] }; userDataProfilesManifestMerge.ts
26 > let remoteResult: { added: IUserDataProfile[]; removed: ISyncUserDataProfile[]; updated: IUserDataProfile[] } | null = { added: [], removed: [], updated: [] };
27 >
28 > if (!remote) {
29 > const added = local.filter(({ id }) => !ignored.includes(id)); userDataProfilesManifestMerge.ts
30 > if (added.length) {
31 remoteResult.added = added;
33 > remoteResult = null; userDataProfilesManifestMerge.ts
34 > }
36 > local: localResult,
37 > remote: remoteResult
38 > };
39 > }
40
41 const localToRemote = compare(local, remote, ignored);
42 > if (localToRemote.added.length > 0 || localToRemote.removed.length > 0 || localToRemote.updated.length > 0) { userDataProfilesManifestMerge.ts
43
44 const baseToLocal = compare(lastSync, local, ignored);
104 }
105
106 > if (remoteResult.added.length === 0 && remoteResult.removed.length === 0 && remoteResult.updated.length === 0) { userDataProfilesManifestMerge.ts
107 remoteResult = null;
108 }
110 return { local: localResult, remote: remoteResult };
111 }
113 function compare(from: IUserDataProfileInfo[] | null, to: IUserDataProfileInfo[], ignoredProfiles: string[]): { added: string[]; removed: string[]; updated: string[] } {
114 from = from ? from.filter(({ id }) => !ignoredProfiles.includes(id)) : [];
src/vs/base/common/lazy.ts 39 covered LOC · 4 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- lazy.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > enum LazyValueState {
7 > Uninitialized,
8 > Running,
9 > Completed,
10 > }
11 >
12 > export class Lazy<T> {
13 >
14 > private _state = LazyValueState.Uninitialized;
15 > private _value?: T;
16 > private _error: Error | undefined;
17 >
18 > constructor(
19 > private readonly executor: () => T, lazy.ts
20 > ) { }
21 > lazy.ts
22 > /**
23 > * True if the lazy value has been resolved.
24 > */
25 > get hasValue(): boolean { return this._state === LazyValueState.Completed; }
26 >
27 > /**
28 > * Get the wrapped value.
29 > *
30 > * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
31 > * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
32 > */
33 > get value(): T {
34 if (this._state === LazyValueState.Uninitialized) {
35 this._state = LazyValueState.Running;
50 return this._value!;
51 }
52 > lazy.ts
53 > /**
54 > * Get the wrapped value without forcing evaluation.
55 > */
56 > get rawValue(): T | undefined { return this._value; }
57 > }
src/vs/platform/product/common/product.ts 39 covered LOC · 4 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- product.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { env } from '../../../base/common/process.js';
7 > import { IProductConfiguration } from '../../../base/common/product.js';
8 > import { ISandboxConfiguration } from '../../../base/parts/sandbox/common/sandboxTypes.js';
9 >
10 > /**
11 > * @deprecated It is preferred that you use `IProductService` if you can. This
12 > * allows web embedders to override our defaults. But for things like `product.quality`,
13 > * the use is fine because that property is not overridable.
14 > */
15 > let product: IProductConfiguration;
16 >
17 > // Native sandbox environment
18 > const vscodeGlobal = (globalThis as { vscode?: { context?: { configuration(): ISandboxConfiguration | undefined } } }).vscode;
19 > if (typeof vscodeGlobal !== 'undefined' && typeof vscodeGlobal.context !== 'undefined') {
20 const configuration: ISandboxConfiguration | undefined = vscodeGlobal.context.configuration();
21 if (configuration) {
25 }
26 }
27 > // _VSCODE environment product.ts
28 > else if (globalThis._VSCODE_PRODUCT_JSON && globalThis._VSCODE_PACKAGE_JSON) {
29 > // Obtain values from product.json and package.json-data
30 > product = globalThis._VSCODE_PRODUCT_JSON as unknown as IProductConfiguration;
31 >
32 > // Running out of sources
33 > if (env['VSCODE_DEV']) {
34 Object.assign(product, {
35 nameShort: `${product.nameShort} Dev`,
39 });
40 }
41 > product.ts
42 > // Version is added during built time, but we still
43 > // want to have it running out of sources so we
44 > // read it from package.json only when we need it.
45 > if (!product.version) {
46 > const pkg = globalThis._VSCODE_PACKAGE_JSON as { version: string };
47 >
48 > Object.assign(product, {
49 > version: pkg.version
50 > });
51 > }
52 }
53
90 }
91 }
92 > product.ts
93 > export default product;
src/vs/base/test/common/virtualScheduling/index.ts 36 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- index.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // Greenfield virtual scheduling primitives.
7 > //
8 > // This folder is the new home for virtual-time scheduling. It supersedes
9 > // `timeTravelScheduler.ts` and `traceableTimeApi.ts`, both of which are
10 > // retained as @deprecated re-export shims.
11 >
12 > export type { TimeApi } from './timeApi.js';
13 > export { captureGlobalTimeApi, realTimeApi } from './timeApi.js';
14 >
15 > export type { EventSource, VirtualEvent, VirtualTime } from './virtualClock.js';
16 > export { VirtualClock } from './virtualClock.js';
17 >
18 > export type { RunAsHandlerOptions } from './trace.js';
19 > export { ROOT_TRACE, Trace, TraceContext, createTraceRoot } from './trace.js';
20 >
21 > export type { Embedding } from './embedding.js';
22 > export { drainMicrotasksEmbedding, nextMacrotask, syncEmbedding } from './embedding.js';
23 >
24 > export type { RunOptions, TerminationPolicy, VirtualTimeProcessorOptions } from './processor.js';
25 > export { VirtualTimeProcessor, untilIdle, untilTime, untilToken } from './processor.js';
26 >
27 > export { pushGlobalTimeApi } from './globalTimeApi.js';
28 > export type { CreateVirtualTimeApiOptions } from './virtualTimeApi.js';
29 > export { createVirtualTimeApi } from './virtualTimeApi.js';
30 > export { createLoggingTimeApi } from './loggingTimeApi.js';
31 > export type { RecordedTimerEvent } from './recordingTimeApi.js';
32 > export { createRecordingRealTimeApi } from './recordingTimeApi.js';
33 > export type { ITraceLogEntry, ITraceLogger } from './traceLogger.js';
34 > export { createTraceLogger } from './traceLogger.js';
35 > export type { RunWithFakedTimersOptions } from './runWithFakedTimers.js';
36 > export { runWithFakedTimers } from './runWithFakedTimers.js';
src/vs/platform/externalServices/common/serviceMachineId.ts 36 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- serviceMachineId.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer } from '../../../base/common/buffer.js';
7 > import { generateUuid, isUUID } from '../../../base/common/uuid.js';
8 > import { IEnvironmentService } from '../../environment/common/environment.js';
9 > import { IFileService } from '../../files/common/files.js';
10 > import { IStorageService, StorageScope, StorageTarget } from '../../storage/common/storage.js';
11 >
12 > export async function getServiceMachineId(environmentService: IEnvironmentService, fileService: IFileService, storageService: IStorageService | undefined): Promise<string> { serviceMachineId.ts
13 > let uuid: string | null = storageService ? storageService.get('storage.serviceMachineId', StorageScope.APPLICATION) || null : null;
14 > if (uuid) {
15 > return uuid; serviceMachineId.ts
16 > }
17 > try { serviceMachineId.ts
18 > const contents = await fileService.readFile(environmentService.serviceMachineIdResource);
19 const value = contents.value.toString();
20 > uuid = isUUID(value) ? value : null; serviceMachineId.ts
21 > } catch (e) {
22 > uuid = null;
23 > }
24 >
25 > if (!uuid) {
26 > uuid = generateUuid();
27 > try {
28 > await fileService.writeFile(environmentService.serviceMachineIdResource, VSBuffer.fromString(uuid));
29 > } catch (error) {
30 > //noop serviceMachineId.ts
31 > }
33 >
34 > storageService?.store('storage.serviceMachineId', uuid, StorageScope.APPLICATION, StorageTarget.MACHINE);
35 >
36 > return uuid;
37 > }
src/vs/base/test/common/timeTravelScheduler.ts 35 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- timeTravelScheduler.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > /**
7 > * @deprecated The contents of this file have moved to
8 > * `./virtualScheduling/index.js`. This re-export is kept for backwards
9 > * compatibility and will be removed once all callers have migrated.
10 > *
11 > * Notes for migration:
12 > * - `TimeTravelScheduler` is now {@link VirtualClock} (same constructor).
13 > * - `AsyncSchedulerProcessor` is now {@link VirtualTimeProcessor}; its
14 > * constructor takes an explicit {@link Embedding}, and {@link Run.options}
15 > * use `until` (a {@link TerminationPolicy}) instead of the implicit
16 > * "drain queue" behaviour. See {@link runWithFakedTimers} for a
17 > * drop-in helper.
18 > * - `originalGlobalValues` is now {@link realTimeApi}.
19 > */
20 >
21 > export {
22 > captureGlobalTimeApi,
23 > createLoggingTimeApi,
24 > createVirtualTimeApi,
25 > pushGlobalTimeApi,
26 > realTimeApi as originalGlobalValues,
27 > runWithFakedTimers,
28 > VirtualClock as TimeTravelScheduler,
29 > } from './virtualScheduling/index.js';
30 >
31 > export type {
32 > CreateVirtualTimeApiOptions,
33 > RunWithFakedTimersOptions,
34 > TimeApi,
35 > } from './virtualScheduling/index.js';
src/vs/platform/instantiation/common/extensions.ts 35 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- extensions.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { SyncDescriptor } from './descriptors.js';
7 > import { BrandedService, ServiceIdentifier } from './instantiation.js';
8 >
9 > const _registry: [ServiceIdentifier<any>, SyncDescriptor<any>][] = [];
10 >
11 > export const enum InstantiationType {
12 > /**
13 > * Instantiate this service as soon as a consumer depends on it. _Note_ that this
14 > * is more costly as some upfront work is done that is likely not needed
15 > */
16 > Eager = 0,
17 >
18 > /**
19 > * Instantiate this service as soon as a consumer uses it. This is the _better_
20 > * way of registering a service.
21 > */
22 > Delayed = 1
23 > }
24 >
25 > export function registerSingleton<T, Services extends BrandedService[]>(id: ServiceIdentifier<T>, ctor: new (...services: Services) => T, supportsDelayedInstantiation: InstantiationType): void;
26 > export function registerSingleton<T, Services extends BrandedService[]>(id: ServiceIdentifier<T>, descriptor: SyncDescriptor<any>): void;
27 > export function registerSingleton<T, Services extends BrandedService[]>(id: ServiceIdentifier<T>, ctorOrDescriptor: { new(...services: Services): T } | SyncDescriptor<any>, supportsDelayedInstantiation?: boolean | InstantiationType): void {
28 > if (!(ctorOrDescriptor instanceof SyncDescriptor)) {
29 > ctorOrDescriptor = new SyncDescriptor<T>(ctorOrDescriptor as new (...args: unknown[]) => T, [], Boolean(supportsDelayedInstantiation));
30 > }
31 >
32 > _registry.push([id, ctorOrDescriptor]);
33 > }
34 >
35 > export function getSingletonServiceDescriptors(): [ServiceIdentifier<any>, SyncDescriptor<any>][] {
36 return _registry;
37 }
src/vs/base/common/marshallingIds.ts 33 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- marshallingIds.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export const enum MarshalledId {
7 > Uri = 1,
8 > Regexp,
9 > ScmResource,
10 > ScmResourceGroup,
11 > ScmProvider,
12 > CommentController,
13 > CommentThread,
14 > CommentThreadInstance,
15 > CommentThreadReply,
16 > CommentNode,
17 > CommentThreadNode,
18 > TimelineActionContext,
19 > NotebookCellActionContext,
20 > NotebookActionContext,
21 > TerminalContext,
22 > TestItemContext,
23 > Date,
24 > TestMessageMenuArgs,
25 > ChatViewContext,
26 > LanguageModelToolResult,
27 > LanguageModelTextPart,
28 > LanguageModelThinkingPart,
29 > LanguageModelPromptTsxPart,
30 > LanguageModelDataPart,
31 > AgentSessionContext,
32 > ChatResponsePullRequestPart,
33 > }
src/vs/base/test/common/virtualScheduling/recordingTimeApi.ts 33 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- recordingTimeApi.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { realTimeApi, TimeApi } from './timeApi.js';
7 > import { Trace, TraceContext } from './trace.js';
8 > import { EventSource } from './virtualClock.js';
9 >
10 > /**
11 > * One entry in a real-time trace recording. Structurally compatible with
12 > * `VirtualEvent` (and `ScheduledTaskLike` consumed by
13 > * `buildHistoryFromTasks`), so the same swimlane renderer can plot both.
14 > */
15 > export interface RecordedTimerEvent {
16 > readonly time: number;
17 > readonly source: EventSource;
18 > readonly trace?: Trace;
19 > }
20 >
21 > /**
22 > * Wrap the real host time API so every `setTimeout` / `setInterval` /
23 > * `requestAnimationFrame` call is tagged with a child {@link Trace} and
24 > * pushes a {@link RecordedTimerEvent} into `history` when the handler
25 > * actually runs.
26 > *
27 > * Handlers are invoked through {@link TraceContext.runAsHandler} so causal
28 > * chains carry across awaits inside a handler. Note: because each handler's
29 > * deferred trace-reset fires as its own real macrotask, attribution can
30 > * drift slightly when many handlers fire in quick succession — accurate
31 > * enough for diagnostics, not for assertions.
32 > */
33 > export function createRecordingRealTimeApi(history: RecordedTimerEvent[]): TimeApi {
34 const realSetTimeout = realTimeApi.setTimeout;
35
src/vs/platform/userDataSync/common/globalStateMerge.ts 33 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- globalStateMerge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IStringDictionary } from '../../../base/common/collections.js';
7 > import * as objects from '../../../base/common/objects.js';
8 > import { ILogService } from '../../log/common/log.js';
9 > import { IStorageValue, SYNC_SERVICE_URL_TYPE } from './userDataSync.js';
10 >
11 > export interface IMergeResult {
12 > local: { added: IStringDictionary<IStorageValue>; removed: string[]; updated: IStringDictionary<IStorageValue> };
13 > remote: { added: string[]; removed: string[]; updated: string[]; all: IStringDictionary<IStorageValue> | null };
14 > }
15 >
16 > export function merge(localStorage: IStringDictionary<IStorageValue>, remoteStorage: IStringDictionary<IStorageValue> | null, baseStorage: IStringDictionary<IStorageValue> | null, storageKeys: { machine: ReadonlyArray<string>; unregistered: ReadonlyArray<string> }, logService: ILogService): IMergeResult {
17 > if (!remoteStorage) { globalStateMerge.ts
18 > return { remote: { added: Object.keys(localStorage), removed: [], updated: [], all: Object.keys(localStorage).length > 0 ? localStorage : null }, local: { added: {}, removed: [], updated: {} } }; globalStateMerge.ts
19 > }
20
21 const localToRemote = compare(localStorage, remoteStorage);
22 > if (localToRemote.added.size === 0 && localToRemote.removed.size === 0 && localToRemote.updated.size === 0) { globalStateMerge.ts
23 // No changes found between local and remote.
24 return { remote: { added: [], removed: [], updated: [], all: null }, local: { added: {}, removed: [], updated: {} } };
25 }
26
27 > const baseToRemote = baseStorage ? compare(baseStorage, remoteStorage) : { added: Object.keys(remoteStorage).reduce((r, k) => { r.add(k); return r; }, new Set<string>()), removed: new Set<string>(), updated: new Set<string>() }; globalStateMerge.ts
28 > const baseToLocal = baseStorage ? compare(baseStorage, localStorage) : { added: Object.keys(localStorage).reduce((r, k) => { r.add(k); return r; }, new Set<string>()), removed: new Set<string>(), updated: new Set<string>() };
29 >
30 > const local: { added: IStringDictionary<IStorageValue>; removed: string[]; updated: IStringDictionary<IStorageValue> } = { added: {}, removed: [], updated: {} };
31 > const remote: IStringDictionary<IStorageValue> = objects.deepClone(remoteStorage);
32 >
33 > const isFirstTimeSync = !baseStorage;
34 >
35 > // Added in local
36 > for (const key of baseToLocal.added.values()) {
37 // If syncing for first time remote value gets precedence always,
38 // except for sync service type key - local value takes precedence for this key
118
119 const result = compare(remoteStorage, remote);
120 > return { local, remote: { added: [...result.added], updated: [...result.updated], removed: [...result.removed], all: result.added.size === 0 && result.removed.size === 0 && result.updated.size === 0 ? null : remote } }; globalStateMerge.ts
121 > }
123 function compare(from: IStringDictionary<any>, to: IStringDictionary<any>): { added: Set<string>; removed: Set<string>; updated: Set<string> } {
124 const fromKeys = Object.keys(from);
src/vs/platform/files/common/io.ts 32 covered LOC · 4 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- io.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer } from '../../../base/common/buffer.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { canceled } from '../../../base/common/errors.js';
9 > import { IDataTransformer, IErrorTransformer, WriteableStream } from '../../../base/common/stream.js';
10 > import { URI } from '../../../base/common/uri.js';
11 > import { localize } from '../../../nls.js';
12 > import { createFileSystemProviderError, ensureFileSystemProviderError, IFileReadStreamOptions, FileSystemProviderErrorCode, IFileSystemProviderWithOpenReadWriteCloseCapability } from './files.js';
13 >
14 > export interface ICreateReadStreamOptions extends IFileReadStreamOptions {
15 >
16 > /**
17 > * The size of the buffer to use before sending to the stream.
18 > */
19 > readonly bufferSize: number;
20 >
21 > /**
22 > * Allows to massage any possibly error that happens during reading.
23 > */
24 > readonly errorTransformer?: IErrorTransformer;
25 > }
26 >
27 > /**
28 > * A helper to read a file from a provider with open/read/close capability into a stream.
29 > */
30 export async function readFileIntoStream<T>(
31 provider: IFileSystemProviderWithOpenReadWriteCloseCapability,
54 }
55 }
56 > io.ts
57 async function doReadFileIntoStream<T>(provider: IFileSystemProviderWithOpenReadWriteCloseCapability, resource: URI, target: WriteableStream<T>, transformer: IDataTransformer<VSBuffer, T>, options: ICreateReadStreamOptions, token: CancellationToken): Promise<void> {
58
114 }
115 }
116 > io.ts
117 function throwIfCancelled(token: CancellationToken): boolean {
118 if (token.isCancellationRequested) {
122 return true;
123 }
124 > io.ts
125 function throwIfTooLarge(totalBytesRead: number, options: ICreateReadStreamOptions): boolean {
126
src/vs/platform/instantiation/common/serviceCollection.ts 30 covered LOC · 10 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- serviceCollection.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { ServiceIdentifier } from './instantiation.js';
7 > import { SyncDescriptor } from './descriptors.js';
8 >
9 > export class ServiceCollection {
10 >
11 > private _entries = new Map<ServiceIdentifier<any>, any>();
12 >
13 > constructor(...entries: [ServiceIdentifier<any>, any][]) {
14 > for (const [id, service] of entries) { serviceCollection.ts
15 > this.set(id, service); serviceCollection.ts
16 > }
19 > set<T>(id: ServiceIdentifier<T>, instanceOrDescriptor: T | SyncDescriptor<T>): T | SyncDescriptor<T> {
20 > const result = this._entries.get(id); serviceCollection.ts
21 > this._entries.set(id, instanceOrDescriptor);
22 > return result;
23 > }
25 > has(id: ServiceIdentifier<any>): boolean {
26 return this._entries.has(id);
27 }
29 > get<T>(id: ServiceIdentifier<T>): T | SyncDescriptor<T> {
30 > return this._entries.get(id); serviceCollection.ts
31 > }
src/vs/base/common/errorMessage.ts 29 covered LOC · 6 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- errorMessage.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as arrays from './arrays.js';
7 > import * as types from './types.js';
8 > import * as nls from '../../nls.js';
9 > import { IAction } from './actions.js';
10 >
11 function exceptionToErrorMessage(exception: any, verbose: boolean): string {
12 if (verbose && (exception.stack || exception.stacktrace)) {
16 return detectSystemErrorMessage(exception);
17 }
19 function stackToString(stack: string[] | string | undefined): string | undefined {
20 if (Array.isArray(stack)) {
24 return stack;
25 }
27 function detectSystemErrorMessage(exception: any): string {
28
39 return exception.message || nls.localize('error.defaultMessage', "An unknown error occurred. Please consult the log for more details.");
40 }
42 > /**
43 > * Tries to generate a human readable error message out of the error. If the verbose parameter
44 > * is set to true, the error message will include stacktrace details if provided.
45 > *
46 > * @returns A string containing the error message.
47 > */
48 > export function toErrorMessage(error: any = null, verbose: boolean = false): string {
49 if (!error) {
50 return nls.localize('error.defaultMessage', "An unknown error occurred. Please consult the log for more details.");
88 return nls.localize('error.defaultMessage', "An unknown error occurred. Please consult the log for more details.");
89 }
91 >
92 > export interface IErrorWithActions extends Error {
93 > actions: IAction[];
94 > }
95 >
96 > export function isErrorWithActions(obj: unknown): obj is IErrorWithActions {
97 const candidate = obj as IErrorWithActions | undefined;
98
99 return candidate instanceof Error && Array.isArray(candidate.actions);
100 }
102 > export function createErrorWithActions(messageOrError: string | Error, actions: IAction[]): IErrorWithActions {
103 let error: IErrorWithActions;
104 if (typeof messageOrError === 'string') {
src/vs/base/common/marshalling.ts 28 covered LOC · 4 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- marshalling.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { VSBuffer } from './buffer.js';
7 > import { URI, UriComponents } from './uri.js';
8 > import { MarshalledId } from './marshallingIds.js';
9 >
10 > export function stringify(obj: unknown): string {
11 return JSON.stringify(obj, replacer);
12 }
14 > export function parse(text: string): any {
15 let data = JSON.parse(text);
16 data = revive(data);
17 return data;
18 }
20 > export interface MarshalledObject {
21 > $mid: MarshalledId;
22 > }
23 >
24 function replacer(key: string, value: any): any {
25 // URI is done via toJSON-member
33 return value;
34 }
36 >
37 > type Deserialize<T> = T extends UriComponents ? URI
38 > : T extends VSBuffer ? VSBuffer
39 > : T extends object
40 > ? Revived<T>
41 > : T;
42 >
43 > export type Revived<T> = { [K in keyof T]: Deserialize<T[K]> };
44 >
45 > export function revive<T = any>(obj: any, depth = 0): Revived<T> {
46 if (!obj || depth > 200) {
47 return obj;
src/vs/base/common/stopwatch.ts 25 covered LOC · 6 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- stopwatch.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > declare const globalThis: { performance: { now(): number } };
7 > const performanceNow = globalThis.performance.now.bind(globalThis.performance);
8 >
9 > export class StopWatch {
10 >
11 > private _startTime: number;
12 > private _stopTime: number;
13 >
14 > private readonly _now: () => number;
15 >
16 > public static create(highResolution?: boolean): StopWatch {
17 return new StopWatch(highResolution);
18 }
20 > constructor(highResolution?: boolean) {
21 this._now = highResolution === false ? Date.now : performanceNow;
22 this._startTime = this._now();
23 this._stopTime = -1;
24 }
26 > public stop(): void {
27 this._stopTime = this._now();
28 }
30 > public reset(): void {
31 this._startTime = this._now();
32 this._stopTime = -1;
33 }
35 > public elapsed(): number {
36 if (this._stopTime !== -1) {
37 return this._stopTime - this._startTime;
39 return this._now() - this._startTime;
40 }
41 > } stopwatch.ts
src/vs/base/common/uuid.ts 25 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- uuid.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 >
7 > const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8 >
9 > export function isUUID(value: string): boolean {
10 return _UUIDPattern.test(value);
11 }
12 > uuid.ts
13 > export const generateUuid = (function (): () => string {
14 >
15 > // use `randomUUID` if possible
16 > if (typeof crypto.randomUUID === 'function') {
17 > // see https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto
18 > // > Although crypto is available on all windows, the returned Crypto object only has one
19 > // > usable feature in insecure contexts: the getRandomValues() method.
20 > // > In general, you should use this API only in secure contexts.
21 >
22 > return crypto.randomUUID.bind(crypto);
23 > }
24
25 // prep-work
63 return result;
64 };
65 > })(); uuid.ts
66 >
67 > /** Namespace should be 3 letters, e.g. `abc-<uuid>`. */
68 > export function prefixedUuid(namespace: string): string {
69 return `${namespace}-${generateUuid()}`;
70 }
src/vs/platform/instantiation/common/descriptors.ts 21 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- descriptors.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export class SyncDescriptor<T> {
7 >
8 > readonly ctor: any;
9 > readonly staticArguments: unknown[];
10 > readonly supportsDelayedInstantiation: boolean;
11 >
12 > constructor(ctor: new (...args: any[]) => T, staticArguments: unknown[] = [], supportsDelayedInstantiation: boolean = false) {
13 > this.ctor = ctor; descriptors.ts
14 > this.staticArguments = staticArguments;
15 > this.supportsDelayedInstantiation = supportsDelayedInstantiation;
16 > }
18 >
19 > export interface SyncDescriptor0<T> {
20 > readonly ctor: new () => T;
21 > }
src/vs/platform/userDataSync/common/content.ts 19 covered LOC · 5 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- content.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { JSONPath } from '../../../base/common/json.js';
7 > import { setProperty } from '../../../base/common/jsonEdit.js';
8 > import { FormattingOptions } from '../../../base/common/jsonFormatter.js';
9 >
10 >
11 > export function edit(content: string, originalPath: JSONPath, value: unknown, formattingOptions: FormattingOptions): string {
12 > const edit = setProperty(content, originalPath, value, formattingOptions)[0]; content.ts
13 > if (edit) {
14 content = content.substring(0, edit.offset) + edit.content + content.substring(edit.offset + edit.length);
15 }
16 > return content; content.ts
17 > }
18 > content.ts
19 > export function getLineStartOffset(content: string, eol: string, atOffset: number): number {
20 let lineStartingOffset = atOffset;
21 while (lineStartingOffset >= 0) {
34 return 0;
35 }
36 > content.ts
37 > export function getLineEndOffset(content: string, eol: string, atOffset: number): number {
38 let lineEndOffset = atOffset;
39 while (lineEndOffset >= 0) {
src/vs/platform/product/common/productService.ts 17 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- productService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { IProductConfiguration } from '../../../base/common/product.js';
7 > import { createDecorator } from '../../instantiation/common/instantiation.js';
8 >
9 > export const IProductService = createDecorator<IProductService>('productService');
10 >
11 > export interface IProductService extends Readonly<IProductConfiguration> {
12 >
13 > readonly _serviceBrand: undefined;
14 >
15 > }
16 >
17 > export const productSchemaId = 'vscode://schemas/vscode-product';
src/vs/base/test/common/virtualScheduling/loggingTimeApi.ts 15 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- loggingTimeApi.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { TimeApi } from './timeApi.js';
7 >
8 > /**
9 > * Wrap `underlying` so that every call to `setTimeout`, `setInterval`,
10 > * `setImmediate` or `requestAnimationFrame` invokes `onCall` first.
11 > *
12 > * Useful for diagnostics — e.g. logging timer registrations made outside of
13 > * virtual time, to find leaks of real-time scheduling into a fixture.
14 > */
15 > export function createLoggingTimeApi(
16 underlying: TimeApi,
17 onCall: (name: string, stack: string | undefined, handler?: () => void) => void,
src/vs/platform/telemetry/common/commonProperties.ts 14 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- commonProperties.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { isLinuxSnap, platform, Platform, PlatformToString } from '../../../base/common/platform.js';
7 > import { env, platform as nodePlatform } from '../../../base/common/process.js';
8 > import { generateUuid } from '../../../base/common/uuid.js';
9 > import { ICommonProperties } from './telemetry.js';
10 >
11 function getPlatformDetail(hostname: string): string | undefined {
12 if (platform === Platform.Linux && /^penguin(\.|$)/i.test(hostname)) {
16 return undefined;
17 }
19 > export function resolveCommonProperties(
20 release: string,
21 hostname: string,
97 return result;
98 }
100 > export function verifyMicrosoftInternalDomain(domainList: readonly string[]): boolean {
101 const userDnsDomain = env['USERDNSDOMAIN'];
102 if (!userDnsDomain) {
src/vs/base/common/functional.ts 9 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- functional.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > /**
7 > * Given a function, returns a function that is only calling that function once.
8 > */
9 > export function createSingleCallFunction<T extends Function>(this: unknown, fn: T, fnDidRunCallback?: () => void): T {
10 const _this = this;
11 let didCall = false;
src/vs/base/common/symbols.ts 9 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- symbols.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > /**
7 > * Can be passed into the Delayed to defer using a microtask
8 > * */
9 > export const MicrotaskDelay = Symbol('MicrotaskDelay');