-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutils.ts
More file actions
626 lines (582 loc) · 15.8 KB
/
utils.ts
File metadata and controls
626 lines (582 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
import type {
POJO,
FileSystem,
Timer,
PromiseDeconstructed,
Callback,
} from '../types.js';
import type { ContextTimed, ContextTimedInput } from '@matrixai/contexts';
import os from 'node:os';
import process from 'process';
import path from 'node:path';
import nodesEvents from 'node:events';
import lexi from 'lexicographic-integer';
import { PromiseCancellable } from '@matrixai/async-cancellable';
import { functions } from '@matrixai/contexts';
import * as utilsErrors from './errors.js';
const AsyncFunction = (async () => {}).constructor;
const GeneratorFunction = function* () {}.constructor;
const AsyncGeneratorFunction = async function* () {}.constructor;
function getDefaultNodePath(): string | undefined {
const prefix = 'polykey';
const platform = os.platform();
let p: string;
if (platform === 'linux') {
const homeDir = os.homedir();
const dataDir = process.env.XDG_DATA_HOME;
if (dataDir != null) {
p = path.join(dataDir, prefix);
} else {
p = path.join(homeDir, '.local', 'share', prefix);
}
} else if (platform === 'darwin') {
const homeDir = os.homedir();
p = path.join(homeDir, 'Library', 'Application Support', prefix);
} else if (platform === 'win32') {
const homeDir = os.homedir();
const appDataDir = process.env.LOCALAPPDATA;
if (appDataDir != null) {
p = path.join(appDataDir, prefix);
} else {
p = path.join(homeDir, 'AppData', 'Local', prefix);
}
} else {
return;
}
return p;
}
function never(message: string): never {
throw new utilsErrors.ErrorUtilsUndefinedBehaviour(message);
}
async function mkdirExists(fs: FileSystem, path, ...args) {
try {
return await fs.promises.mkdir(path, ...args);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
}
/**
* Checks if a directory is empty
* If the path does not exist, also returns true
*/
async function dirEmpty(fs: FileSystem, path): Promise<boolean> {
try {
const entries = await fs.promises.readdir(path);
return entries.length === 0;
} catch (e) {
if (e.code === 'ENOENT') {
return true;
}
throw e;
}
}
/**
* Test whether a path includes another path
* This will return true when path 1 is the same as path 2
*/
function pathIncludes(p1: string, p2: string): boolean {
const relative = path.relative(p2, p1);
// Absolute directory check is needed for Windows
return (
(relative === '' || !relative.startsWith('..')) &&
!path.isAbsolute(relative)
);
}
async function sleep(ms: number): Promise<void> {
return await new Promise<void>((r) => setTimeout(r, ms));
}
function sleepCancellable(ms: number): PromiseCancellable<void> {
return new PromiseCancellable<void>((resolve, reject, signal) => {
if (signal.aborted) return reject(signal.reason);
const handleTimeout = () => {
signal.removeEventListener('abort', handleAbort);
resolve();
};
const handleAbort = () => {
clearTimeout(timer);
reject(signal.reason);
};
signal.addEventListener('abort', handleAbort, { once: true });
const timer = setTimeout(handleTimeout, ms);
});
}
/**
* Checks if value is an object.
* Arrays are also considered objects.
* At that point `'x' in o` checks become type guards that
* can assert the property's existence.
*/
function isObject(o: unknown): o is object {
return o !== null && typeof o === 'object';
}
function isEmptyObject(o) {
for (const k in o) return false;
return true;
}
/**
* Filters out all undefined properties recursively
*/
function filterEmptyObject(o) {
return filterObject(o, ([_, v]) => v !== undefined).map(([k, v]) => [
k,
v === Object(v) ? filterEmptyObject(v) : v,
]);
}
function filterObject<T extends Record<K, V>, K extends string, V>(
obj: T,
f: (element: [K, V], index: number, arr: Array<[K, V]>) => boolean,
): Partial<T> {
return Object.fromEntries(Object.entries(obj).filter(f)) as Partial<T>;
}
/**
* Merges an input object to a default object.
*/
function mergeObjects(object1: POJO, object2: POJO): POJO {
const keys = new Set([...Object.keys(object2), ...Object.keys(object1)]);
const mergedObject = {};
for (const key of keys) {
if (isObject(object1[key]) && isObject(object2[key])) {
mergedObject[key] = mergeObjects(object1[key], object2[key]);
} else if (object1[key] !== undefined) {
mergedObject[key] = object1[key];
} else {
mergedObject[key] = object2[key];
}
}
return mergedObject;
}
function getUnixtime(date: Date = new Date()) {
return Math.round(date.getTime() / 1000);
}
const sleepCancelReasonSymbol = Symbol('sleepCancelReasonSymbol');
/**
* Poll execution and use condition to accept or reject the results
*/
async function poll_<T, E = any>(
ctx: ContextTimed,
f: () => T | PromiseLike<T>,
condition: {
(e: E, result?: undefined): boolean;
(e: null, result: T): boolean;
},
interval: number,
): Promise<T> {
let result: T;
const { p: abortP, resolveP: resolveAbortP } = promise();
const handleAbortP = () => resolveAbortP();
if (ctx.signal.aborted) {
resolveAbortP();
} else {
ctx.signal.addEventListener('abort', handleAbortP, { once: true });
}
try {
while (true) {
if (ctx.signal.aborted) {
throw new utilsErrors.ErrorUtilsPollTimeout();
}
try {
result = await f();
if (condition(null, result)) {
return result;
}
} catch (e) {
if (condition(e)) {
throw e;
}
}
const sleepP = sleepCancellable(interval);
await Promise.race([sleepP, abortP])
.finally(async () => {
// Clean up
sleepP.cancel(sleepCancelReasonSymbol);
await sleepP;
})
.catch((e) => {
if (e !== sleepCancelReasonSymbol) throw e;
});
}
} finally {
resolveAbortP();
await abortP;
ctx.signal.removeEventListener('abort', handleAbortP);
}
}
const pollCancellable = functions.timedCancellable(
poll_,
true,
undefined,
utilsErrors.ErrorUtilsPollTimeout,
);
/**
* Poll execution and use condition to accept or reject the results
*/
function poll<T, E = any>(
f: () => T | PromiseLike<T>,
condition: {
(e: E, result?: undefined): boolean;
(e: null, result: T): boolean;
},
interval = 1000,
ctx?: Partial<ContextTimedInput>,
): PromiseCancellable<T> {
return pollCancellable(ctx, f, condition, interval);
}
/**
* Convert callback-style to promise-style
* If this is applied to overloaded function
* it will only choose one of the function signatures to use
*/
function promisify<
T extends Array<unknown>,
P extends Array<unknown>,
R extends T extends [] ? void : T extends [unknown] ? T[0] : T,
>(
f: (...args: [...params: P, callback: Callback<T>]) => unknown,
): (...params: P) => Promise<R> {
// Uses a regular function so that `this` can be bound
return function (...params: P): Promise<R> {
return new Promise((resolve, reject) => {
const callback = (error, ...values) => {
if (error != null) {
return reject(error);
}
if (values.length === 0) {
(resolve as () => void)();
} else if (values.length === 1) {
resolve(values[0] as R);
} else {
resolve(values as R);
}
return;
};
params.push(callback);
f.apply(this, params);
});
};
}
/**
* Deconstructed promise
*/
function promise<T = void>(): PromiseDeconstructed<T> {
let resolveP, rejectP;
const p = new Promise<T>((resolve, reject) => {
resolveP = resolve;
rejectP = reject;
});
return {
p,
resolveP,
rejectP,
};
}
/**
* Promise constructed from signal
* This rejects when the signal is aborted
*/
function signalPromise(signal: AbortSignal): PromiseCancellable<void> {
setMaxListeners(signal);
return new PromiseCancellable((resolve, _, signalCancel) => {
// Short circuit if signal already aborted
if (signal.aborted) return resolve();
// Short circuit if promise is already cancelled
if (signalCancel.aborted) return resolve();
const handler = () => {
signalCancel.removeEventListener('abort', handler);
signal.removeEventListener('abort', handler);
resolve();
};
signal.addEventListener('abort', handler, { once: true });
signalCancel.addEventListener('abort', handler, { once: true });
});
}
function timerStart(timeout: number): Timer {
const timer = {} as Timer;
timer.timedOut = false;
timer.timerP = new Promise<void>((resolve) => {
timer.timer = setTimeout(() => {
timer.timedOut = true;
resolve();
}, timeout);
});
return timer;
}
function timerStop(timer: Timer): void {
clearTimeout(timer.timer);
}
function arraySet<T>(items: Array<T>, item: T) {
if (items.indexOf(item) === -1) {
items.push(item);
}
}
function arrayUnset<T>(items: Array<T>, item: T) {
const itemIndex = items.indexOf(item);
if (itemIndex !== -1) {
items.splice(itemIndex, 1);
}
}
function arrayZip<T1, T2>(a: Array<T1>, b: Array<T2>): Array<[T1, T2]> {
return Array.from(Array(Math.min(b.length, a.length)), (_, i) => [
a[i],
b[i],
]);
}
function arrayZipWithPadding<T1, T2>(
a: Array<T1>,
b: Array<T2>,
): Array<[T1 | undefined, T2 | undefined]> {
return Array.from(Array(Math.max(b.length, a.length)), (_, i) => [
a[i],
b[i],
]);
}
async function asyncIterableArray<T>(
iterable: AsyncIterable<T>,
): Promise<Array<T>> {
const arr: Array<T> = [];
for await (const item of iterable) {
arr.push(item);
}
return arr;
}
function bufferSplit(
input: Buffer,
delimiter?: Buffer,
limit?: number,
remaining: boolean = false,
): Array<Buffer> {
const output: Array<Buffer> = [];
let delimiterOffset = 0;
let delimiterIndex = 0;
let i = 0;
if (delimiter != null) {
while (true) {
if (i === limit) break;
delimiterIndex = input.indexOf(delimiter, delimiterOffset);
if (delimiterIndex > -1) {
output.push(input.subarray(delimiterOffset, delimiterIndex));
delimiterOffset = delimiterIndex + delimiter.byteLength;
} else {
const chunk = input.subarray(delimiterOffset);
output.push(chunk);
delimiterOffset += chunk.byteLength;
break;
}
i++;
}
} else {
for (; delimiterIndex < input.byteLength; ) {
if (i === limit) break;
delimiterIndex++;
const chunk = input.subarray(delimiterOffset, delimiterIndex);
output.push(chunk);
delimiterOffset += chunk.byteLength;
i++;
}
}
// If remaining, then the rest of the input including delimiters is extracted
if (
remaining &&
limit != null &&
output.length > 0 &&
delimiterIndex > -1 &&
delimiterIndex <= input.byteLength
) {
const inputRemaining = input.subarray(
delimiterIndex - output[output.length - 1].byteLength,
);
output[output.length - 1] = inputRemaining;
}
return output;
}
/**
* Zero-copy wraps ArrayBuffer-like objects into Buffer
* This supports ArrayBuffer, TypedArrays and the NodeJS Buffer
*/
function bufferWrap(
array: BufferSource,
offset?: number,
length?: number,
): Buffer {
if (Buffer.isBuffer(array)) {
return array;
} else if (ArrayBuffer.isView(array)) {
return Buffer.from(
array.buffer,
offset ?? array.byteOffset,
length ?? array.byteLength,
);
} else {
return Buffer.from(array, offset, length);
}
}
/**
* Checks if data is an ArrayBuffer-like object
* This includes ArrayBuffer, TypedArrays and the NodeJS Buffer
*/
function isBufferSource(data: unknown): data is BufferSource {
return ArrayBuffer.isView(data) || data instanceof ArrayBuffer;
}
function debounce<P extends any[]>(
f: (...params: P) => any,
timeout: number = 0,
): (...param: P) => void {
let timer: ReturnType<typeof setTimeout>;
return function (this: any, ...args: any[]) {
clearTimeout(timer);
timer = setTimeout(() => f.apply(this, args), timeout);
};
}
function isPromise(v: any): v is Promise<unknown> {
return (
v instanceof Promise ||
(v != null &&
typeof v.then === 'function' &&
typeof v.catch === 'function' &&
typeof v.finally === 'function')
);
}
function isPromiseLike(v: any): v is PromiseLike<unknown> {
return v != null && typeof v.then === 'function';
}
/**
* Is generator object
* Use this to check for generators
*/
function isGenerator(v: any): v is Generator<unknown> {
return (
v != null &&
typeof v[Symbol.iterator] === 'function' &&
typeof v.next === 'function' &&
typeof v.return === 'function' &&
typeof v.throw === 'function'
);
}
/**
* Is async generator object
* Use this to check for async generators
*/
function isAsyncGenerator(v: any): v is AsyncGenerator<unknown> {
return (
v != null &&
typeof v === 'object' &&
typeof v[Symbol.asyncIterator] === 'function' &&
typeof v.next === 'function' &&
typeof v.return === 'function' &&
typeof v.throw === 'function'
);
}
/**
* Encodes whole numbers (inc of 0) to lexicographic buffers
*/
function lexiPackBuffer(n: number): Buffer {
return Buffer.from(lexi.pack(n));
}
/**
* Decodes lexicographic buffers to whole numbers (inc of 0)
*/
function lexiUnpackBuffer(b: Buffer): number {
return lexi.unpack([...b]);
}
/**
* Used to yield to the event loop to allow other micro tasks to process
*/
async function yieldMicro() {
return await new Promise<void>((r) => queueMicrotask(r));
}
/**
* Increases the total number of registered event handlers before a node warning is emitted.
* In most cases this is not needed but in the case where you have one event emitter for multiple handlers you'll need
* to increase the limit.
* @param target - The specific `EventTarget` or `EventEmitter` to increase the warning for.
* @param limit - The limit before the warning is emitted, defaults to 100000.
*/
function setMaxListeners(
target: EventTarget | NodeJS.EventEmitter,
limit: number = 100000,
) {
nodesEvents.setMaxListeners(limit, target);
}
async function importFS(fs?: FileSystem): Promise<FileSystem> {
if (fs != null) return fs;
const { default: fsImported } = await import('node:fs');
return fsImported;
}
/**
* Races a promise against a context. If the context is aborted, then the promise
* rejects with the reason. Otherwise, the original value is returned upon
* resolving.
* @param prom The promise to resolve
* @param ctx The ctx with which to race the promise against
* @returns A promise which resolves to the prom value or errors if ctx aborts
*/
async function raceSignal<T>(
prom: Promise<T>,
abortSignal: AbortSignal,
): Promise<T> {
// Create an abort promise which rejects when ctx is aborted
const { p: abortP, rejectP: rejectAbortP } = promise<never>();
const abortHandler = () => {
rejectAbortP(abortSignal.reason);
};
if (abortSignal.aborted) {
abortHandler();
} else {
abortSignal.addEventListener('abort', abortHandler, { once: true });
}
// Race the original promise and abortP. If the original promise resolves
// first, then it is returned. If the context aborts first, then the
// promise is rejected.
try {
return await Promise.race([prom, abortP]);
} catch (e) {
Error.captureStackTrace(e);
throw e;
} finally {
abortSignal.removeEventListener('abort', abortHandler);
}
}
export {
AsyncFunction,
GeneratorFunction,
AsyncGeneratorFunction,
getDefaultNodePath,
never,
mkdirExists,
dirEmpty,
pathIncludes,
sleep,
sleepCancellable,
isObject,
isEmptyObject,
filterEmptyObject,
filterObject,
mergeObjects,
getUnixtime,
poll,
promisify,
promise,
signalPromise,
timerStart,
timerStop,
arraySet,
arrayUnset,
arrayZip,
arrayZipWithPadding,
asyncIterableArray,
bufferSplit,
debounce,
isPromise,
isPromiseLike,
isGenerator,
isAsyncGenerator,
lexiPackBuffer,
lexiUnpackBuffer,
bufferWrap,
isBufferSource,
yieldMicro,
setMaxListeners,
importFS,
raceSignal,
};