mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Convert runMany and runManySync to use injectManyWithMeta + move to seperate package (#7244)
* Convert runMany and runManySync to use injectManyWithMeta Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fixup type errors due to new Runnable requirements Signed-off-by: Sebastian Malton <sebastian@malton.name> * Add documentation for verifyRunnablesAreDAG Signed-off-by: Sebastian Malton <sebastian@malton.name> * Simplify convertToWithIdWith Signed-off-by: Sebastian Malton <sebastian@malton.name> * Move all utility functions to separate package Signed-off-by: Sebastian Malton <sebastian@malton.name> * Move testing utilities to separate package Signed-off-by: Sebastian Malton <sebastian@malton.name> * Move run-many and run-many-sync to separate package Signed-off-by: Sebastian Malton <sebastian@malton.name> * Replace all internal uses of utilities with new packages Signed-off-by: Sebastian Malton <sebastian@malton.name> * Use new @k8slens/run-many package in core Signed-off-by: Sebastian Malton <sebastian@malton.name> * Add dep to open-lens Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fixup type errors Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fixup uses of @k8slens/test-utils Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fixup getGlobalOverride Signed-off-by: Sebastian Malton <sebastian@malton.name> * Move tests to new package too Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fix type errors Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fixup uses of AsyncResult and autoBind Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fixup remaining import issues Signed-off-by: Sebastian Malton <sebastian@malton.name> * Finial fixups to fix build Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fix lint Signed-off-by: Sebastian Malton <sebastian@malton.name> * Revert moving "testUsingFakeTime" to separate package - This fixes tests Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fix integration tests Signed-off-by: Sebastian Malton <sebastian@malton.name> * Fix unit test failing due to spelling fix Signed-off-by: Sebastian Malton <sebastian@malton.name> --------- Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
1 parent
ad9bafe2a5
commit
2789bcebcb
754 files changed
+2715
-2752
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# @k8slens/run-many
|
||||
|
||||
This package contains the functions `runMany` and `runManySync`
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./src/run-many-for";
|
||||
export * from "./src/run-many-sync-for";
|
||||
|
||||
export type { Runnable, RunnableSync, Run, RunSync } from "./src/types";
|
||||
@@ -0,0 +1,2 @@
|
||||
module.exports =
|
||||
require("@k8slens/jest").monorepoPackageConfig(__dirname).configForReact;
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "@k8slens/run-many",
|
||||
"version": "1.0.0",
|
||||
"type": "commonjs",
|
||||
"description": "A package containing runMany and runManySync",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org/"
|
||||
},
|
||||
"private": false,
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"author": {
|
||||
"name": "OpenLens Authors",
|
||||
"email": "info@k8slens.dev"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/lensapp/lens",
|
||||
"scripts": {
|
||||
"build": "webpack",
|
||||
"dev": "webpack --mode=development --watch",
|
||||
"test": "jest --coverage --runInBand"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@k8slens/test-utils": "^1.0.0",
|
||||
"@k8slens/utilities": "^1.0.0",
|
||||
"@ogre-tools/fp": "^15.1.1",
|
||||
"@ogre-tools/injectable": "^15.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { DiContainerForInjection, InjectionInstanceWithMeta } from "@ogre-tools/injectable";
|
||||
import { getOrInsertSetFor, isDefined } from "@k8slens/utilities";
|
||||
import * as uuid from "uuid";
|
||||
import assert from "assert";
|
||||
import type { Runnable, RunnableSync, RunnableSyncWithId, RunnableWithId } from "./types";
|
||||
|
||||
const computedNextEdge = (traversed: string[], graph: Map<string, Set<string>>, currentId: string, seenIds: Set<string>) => {
|
||||
seenIds.add(currentId);
|
||||
const currentNode = graph.get(currentId);
|
||||
|
||||
assert(currentNode, `Runnable graph does not contain node with id="${currentId}"`);
|
||||
|
||||
for (const nextId of currentNode.values()) {
|
||||
if (traversed.includes(nextId)) {
|
||||
throw new Error(`Cycle in runnable graph: "${traversed.join(`" -> "`)}" -> "${nextId}"`);
|
||||
}
|
||||
|
||||
computedNextEdge([...traversed, nextId], graph, nextId, seenIds);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Verifies that the graph produces by `runnables`'s `runAfter`'s is acyclic. Namely that it
|
||||
* produces a Directed Acyclic Graph.
|
||||
* @param tokenId The ID of the injectionToken that was `injectManyWithMeta()`-ed. Used for error messages
|
||||
* @param runnables The list of runnables to check.
|
||||
*/
|
||||
export function verifyRunnablesAreDAG<Param>(tokenId: string, runnables: RunnableWithId<Param>[]): void;
|
||||
export function verifyRunnablesAreDAG<Param>(tokenId: string, runnables: RunnableSyncWithId<Param>[]): void;
|
||||
|
||||
export function verifyRunnablesAreDAG<Param>(tokenId: string, runnables: (RunnableWithId<Param>[]) | (RunnableSyncWithId<Param>[])): void {
|
||||
const rootId = uuid.v4();
|
||||
const runnableGraph = new Map<string, Set<string>>();
|
||||
const seenIds = new Set<string>();
|
||||
const addRunnableId = getOrInsertSetFor(runnableGraph);
|
||||
|
||||
// Build the Directed graph
|
||||
for (const runnable of runnables) {
|
||||
addRunnableId(runnable.id);
|
||||
|
||||
if (runnable.runAfter.length === 0) {
|
||||
addRunnableId(rootId).add(runnable.id);
|
||||
} else {
|
||||
for (const parentRunnable of runnable.runAfter) {
|
||||
addRunnableId(parentRunnable.id).add(runnable.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addRunnableId(rootId);
|
||||
|
||||
// Do a DFS to find any cycles
|
||||
computedNextEdge([], runnableGraph, rootId, seenIds);
|
||||
|
||||
for (const id of runnableGraph.keys()) {
|
||||
if (!seenIds.has(id)) {
|
||||
const runnable = runnables.find(runnable => runnable.id === id);
|
||||
|
||||
if (!runnable) {
|
||||
throw new Error(`Runnable "${id}" is not part of the injection token "${tokenId}"`);
|
||||
}
|
||||
|
||||
const runAfters = [runnable.runAfter]
|
||||
.flat()
|
||||
.filter(isDefined)
|
||||
.map(runnable => runnable.id)
|
||||
.join('", "');
|
||||
|
||||
throw new Error(`Runnable "${id}" is unreachable for injection token "${tokenId}": run afters "${runAfters}" are a part of different injection tokens.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ConvertToWithId {
|
||||
<Param>(src: InjectionInstanceWithMeta<Runnable<Param>>): RunnableWithId<Param>;
|
||||
<Param>(src: InjectionInstanceWithMeta<RunnableSync<Param>>): RunnableSyncWithId<Param>;
|
||||
}
|
||||
|
||||
export const convertToWithIdWith = (di: DiContainerForInjection) => {
|
||||
const convert = <Param>(meta: { id: string }, instance: Runnable<Param>): RunnableWithId<Param> => ({
|
||||
id: meta.id,
|
||||
run: instance.run,
|
||||
runAfter: [instance.runAfter]
|
||||
.flat()
|
||||
.filter(isDefined)
|
||||
.map((injectable) => convert(injectable, di.inject(injectable))),
|
||||
});
|
||||
|
||||
return ((src) => convert(src.meta, src.instance)) as ConvertToWithId;
|
||||
};
|
||||
@@ -0,0 +1,622 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { AsyncFnMock } from "@async-fn/jest";
|
||||
import asyncFn from "@async-fn/jest";
|
||||
import { createContainer, getInjectable, getInjectionToken } from "@ogre-tools/injectable";
|
||||
import type { Runnable } from "./types";
|
||||
import { runManyFor } from "./run-many-for";
|
||||
import { getPromiseStatus, flushPromises } from "@k8slens/test-utils";
|
||||
import { runInAction } from "mobx";
|
||||
|
||||
describe("runManyFor", () => {
|
||||
describe("given no hierarchy, when running many", () => {
|
||||
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
|
||||
let actualPromise: Promise<void>;
|
||||
|
||||
beforeEach(() => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
runMock = asyncFn();
|
||||
|
||||
const someInjectionTokenForRunnables = getInjectionToken<Runnable>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable = getInjectable({
|
||||
id: "some-injectable",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-call"),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
const someOtherInjectable = getInjectable({
|
||||
id: "some-other-injectable",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-other-call"),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
rootDi.register(someInjectable, someOtherInjectable);
|
||||
|
||||
const runMany = runManyFor(rootDi)(someInjectionTokenForRunnables);
|
||||
|
||||
actualPromise = runMany() as Promise<void>;
|
||||
});
|
||||
|
||||
it("runs all runnables at the same time", () => {
|
||||
expect(runMock.mock.calls).toEqual([
|
||||
["some-call"],
|
||||
["some-other-call"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not resolve yet", async () => {
|
||||
const promiseStatus = await getPromiseStatus(actualPromise);
|
||||
|
||||
expect(promiseStatus.fulfilled).toBe(false);
|
||||
});
|
||||
|
||||
it("when all runnables resolve, resolves", async () => {
|
||||
await Promise.all([runMock.resolve(), runMock.resolve()]);
|
||||
|
||||
expect(await actualPromise).toBe(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("given hierarchy that is three levels deep, when running many", () => {
|
||||
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
|
||||
let actualPromise: Promise<void>;
|
||||
|
||||
beforeEach(() => {
|
||||
const di = createContainer("irrelevant");
|
||||
|
||||
runMock = asyncFn();
|
||||
|
||||
const someInjectionTokenForRunnables = getInjectionToken<Runnable>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable1 = getInjectable({
|
||||
id: "some-injectable-1",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("third-level-run"),
|
||||
runAfter: someInjectable2,
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
const someInjectable2 = getInjectable({
|
||||
id: "some-injectable-2",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("second-level-run"),
|
||||
runAfter: someInjectable3,
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
const someInjectable3 = getInjectable({
|
||||
id: "some-injectable-3",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("first-level-run"),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
di.register(someInjectable1, someInjectable2, someInjectable3);
|
||||
|
||||
const runMany = runManyFor(di)(someInjectionTokenForRunnables);
|
||||
|
||||
actualPromise = runMany() as Promise<void>;
|
||||
});
|
||||
|
||||
it("runs first level runnables", () => {
|
||||
expect(runMock.mock.calls).toEqual([["first-level-run"]]);
|
||||
});
|
||||
|
||||
it("does not resolve yet", async () => {
|
||||
const promiseStatus = await getPromiseStatus(actualPromise);
|
||||
|
||||
expect(promiseStatus.fulfilled).toBe(false);
|
||||
});
|
||||
|
||||
describe("when first level runnables resolve", () => {
|
||||
beforeEach(async () => {
|
||||
runMock.mockClear();
|
||||
|
||||
await runMock.resolveSpecific(["first-level-run"]);
|
||||
});
|
||||
|
||||
it("runs second level runnables", async () => {
|
||||
expect(runMock.mock.calls).toEqual([["second-level-run"]]);
|
||||
});
|
||||
|
||||
it("does not resolve yet", async () => {
|
||||
const promiseStatus = await getPromiseStatus(actualPromise);
|
||||
|
||||
expect(promiseStatus.fulfilled).toBe(false);
|
||||
});
|
||||
|
||||
describe("when second level runnables resolve", () => {
|
||||
beforeEach(async () => {
|
||||
runMock.mockClear();
|
||||
|
||||
await runMock.resolveSpecific(["second-level-run"]);
|
||||
});
|
||||
|
||||
it("runs final third level runnables", async () => {
|
||||
expect(runMock.mock.calls).toEqual([["third-level-run"]]);
|
||||
});
|
||||
|
||||
it("does not resolve yet", async () => {
|
||||
const promiseStatus = await getPromiseStatus(actualPromise);
|
||||
|
||||
expect(promiseStatus.fulfilled).toBe(false);
|
||||
});
|
||||
|
||||
describe("when final third level runnables resolve", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["third-level-run"]);
|
||||
});
|
||||
|
||||
it("resolves", async () => {
|
||||
const promiseStatus = await getPromiseStatus(actualPromise);
|
||||
|
||||
expect(promiseStatus.fulfilled).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("given invalid hierarchy, when running runnables, throws", () => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
const runMock = asyncFn<(...args: unknown[]) => void>();
|
||||
|
||||
const someInjectionToken = getInjectionToken<Runnable>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someOtherInjectionToken = getInjectionToken<Runnable>({
|
||||
id: "some-other-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable = getInjectable({
|
||||
id: "some-runnable-1",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-runnable-1"),
|
||||
runAfter: someOtherInjectable,
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const someOtherInjectable = getInjectable({
|
||||
id: "some-runnable-2",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-runnable-2"),
|
||||
}),
|
||||
injectionToken: someOtherInjectionToken,
|
||||
});
|
||||
|
||||
rootDi.register(someInjectable, someOtherInjectable);
|
||||
|
||||
const runMany = runManyFor(rootDi)(
|
||||
someInjectionToken,
|
||||
);
|
||||
|
||||
return expect(() => runMany()).rejects.toThrow(
|
||||
/Runnable "some-runnable-1" is unreachable for injection token "some-injection-token": run afters "some-runnable-2" are a part of different injection tokens./,
|
||||
);
|
||||
});
|
||||
|
||||
it("given partially incorrect hierarchy, when running runnables, throws", () => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
const runMock = asyncFn<(...args: unknown[]) => void>();
|
||||
|
||||
const someInjectionToken = getInjectionToken<Runnable>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someOtherInjectionToken = getInjectionToken<Runnable>({
|
||||
id: "some-other-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable = getInjectable({
|
||||
id: "some-runnable-1",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-runnable-1"),
|
||||
runAfter: [
|
||||
someOtherInjectable,
|
||||
someSecondInjectable,
|
||||
],
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const someSecondInjectable = getInjectable({
|
||||
id: "some-runnable-2",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-runnable-2"),
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const someOtherInjectable = getInjectable({
|
||||
id: "some-runnable-3",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-runnable-3"),
|
||||
}),
|
||||
injectionToken: someOtherInjectionToken,
|
||||
});
|
||||
|
||||
rootDi.register(someInjectable, someOtherInjectable, someSecondInjectable);
|
||||
|
||||
const runMany = runManyFor(rootDi)(
|
||||
someInjectionToken,
|
||||
);
|
||||
|
||||
return expect(() => runMany()).rejects.toThrow(
|
||||
/Runnable "some-runnable-3" is not part of the injection token "some-injection-token"/,
|
||||
);
|
||||
});
|
||||
|
||||
describe("when running many with parameter", () => {
|
||||
let runMock: AsyncFnMock<(...args: unknown[]) => Promise<void>>;
|
||||
|
||||
beforeEach(() => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
runMock = asyncFn();
|
||||
|
||||
const someInjectionTokenForRunnablesWithParameter = getInjectionToken<
|
||||
Runnable<string>
|
||||
>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable = getInjectable({
|
||||
id: "some-runnable-1",
|
||||
instantiate: () => ({
|
||||
run: (parameter) => runMock("run-of-some-runnable-1", parameter),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnablesWithParameter,
|
||||
});
|
||||
|
||||
const someOtherInjectable = getInjectable({
|
||||
id: "some-runnable-2",
|
||||
instantiate: () => ({
|
||||
run: (parameter) => runMock("run-of-some-runnable-2", parameter),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnablesWithParameter,
|
||||
});
|
||||
|
||||
rootDi.register(someInjectable, someOtherInjectable);
|
||||
|
||||
const runMany = runManyFor(rootDi)(
|
||||
someInjectionTokenForRunnablesWithParameter,
|
||||
);
|
||||
|
||||
runMany("some-parameter");
|
||||
});
|
||||
|
||||
it("runs all runnables using the parameter", () => {
|
||||
expect(runMock.mock.calls).toEqual([
|
||||
["run-of-some-runnable-1", "some-parameter"],
|
||||
["run-of-some-runnable-2", "some-parameter"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("given multiple runAfters", () => {
|
||||
let runMock: AsyncFnMock<(...args: unknown[]) => void>;
|
||||
let finishingPromise: Promise<void>;
|
||||
|
||||
beforeEach(async () => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
runMock = asyncFn<(...args: unknown[]) => void>();
|
||||
|
||||
const someInjectionToken = getInjectionToken<Runnable>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const runnableOneInjectable = getInjectable({
|
||||
id: "runnable-1",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("runnable-1"),
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const runnableTwoInjectable = getInjectable({
|
||||
id: "runnable-2",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("runnable-2"),
|
||||
runAfter: [], // shouldn't block being called
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const runnableThreeInjectable = getInjectable({
|
||||
id: "runnable-3",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("runnable-3"),
|
||||
runAfter: runnableOneInjectable,
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const runnableFourInjectable = getInjectable({
|
||||
id: "runnable-4",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("runnable-4"),
|
||||
runAfter: [runnableThreeInjectable], // should be the same as an single item
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const runnableFiveInjectable = getInjectable({
|
||||
id: "runnable-5",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("runnable-5"),
|
||||
runAfter: runnableThreeInjectable,
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const runnableSixInjectable = getInjectable({
|
||||
id: "runnable-6",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("runnable-6"),
|
||||
runAfter: [
|
||||
runnableFourInjectable,
|
||||
runnableFiveInjectable,
|
||||
],
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const runnableSevenInjectable = getInjectable({
|
||||
id: "runnable-7",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("runnable-7"),
|
||||
runAfter: [
|
||||
runnableFiveInjectable,
|
||||
runnableSixInjectable,
|
||||
],
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
runInAction(() => {
|
||||
rootDi.register(
|
||||
runnableOneInjectable,
|
||||
runnableTwoInjectable,
|
||||
runnableThreeInjectable,
|
||||
runnableFourInjectable,
|
||||
runnableFiveInjectable,
|
||||
runnableSixInjectable,
|
||||
runnableSevenInjectable,
|
||||
);
|
||||
});
|
||||
|
||||
const runMany = runManyFor(rootDi);
|
||||
const runSome = runMany(someInjectionToken);
|
||||
|
||||
finishingPromise = runSome();
|
||||
|
||||
await flushPromises();
|
||||
});
|
||||
|
||||
it("should run 'runnable-1'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-1");
|
||||
});
|
||||
|
||||
it("should run 'runnable-2'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-2");
|
||||
});
|
||||
|
||||
it("should not run 'runnable-3'", () => {
|
||||
expect(runMock).not.toBeCalledWith("runnable-3");
|
||||
});
|
||||
|
||||
describe("when 'runnable-1' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-1"]);
|
||||
});
|
||||
|
||||
it("should run 'runnable-3'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-3");
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-3' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-3"]);
|
||||
});
|
||||
|
||||
it("should run 'runnable-4'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-4");
|
||||
});
|
||||
|
||||
it("should run 'runnable-5'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-5");
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-4' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-4"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(5);
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-5' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-5"]);
|
||||
});
|
||||
|
||||
it("should run 'runnable-6'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-6");
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-6' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-6"]);
|
||||
});
|
||||
|
||||
it("should run 'runnable-7'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-7");
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(7);
|
||||
});
|
||||
|
||||
describe("when 'runnable-7' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-7"]);
|
||||
});
|
||||
|
||||
it("should resolve the runMany promise call", async () => {
|
||||
await finishingPromise;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-5' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-5"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(5);
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-4' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-4"]);
|
||||
});
|
||||
|
||||
it("should run 'runnable-6'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-6");
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-6' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-6"]);
|
||||
});
|
||||
|
||||
it("should run 'runnable-7'", () => {
|
||||
expect(runMock).toBeCalledWith("runnable-7");
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(7);
|
||||
});
|
||||
|
||||
describe("when 'runnable-7' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-7"]);
|
||||
});
|
||||
|
||||
it("should resolve the runMany promise call", async () => {
|
||||
await finishingPromise;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("when 'runnable-2' resolves", () => {
|
||||
beforeEach(async () => {
|
||||
await runMock.resolveSpecific(["runnable-2"]);
|
||||
});
|
||||
|
||||
it("shouldn't call any more runnables", () => {
|
||||
expect(runMock).toBeCalledTimes(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { DiContainerForInjection, InjectionToken } from "@ogre-tools/injectable";
|
||||
import { getOrInsert } from "@k8slens/utilities";
|
||||
import type TypedEventEmitter from "typed-emitter";
|
||||
import EventEmitter from "events";
|
||||
import { convertToWithIdWith, verifyRunnablesAreDAG } from "./helpers";
|
||||
import type { RunnableWithId, Runnable, Run } from "./types";
|
||||
import type { Asyncify } from "type-fest";
|
||||
|
||||
export type RunMany = <Param>(injectionToken: InjectionToken<Runnable<Param>, void>) => Asyncify<Run<Param>>;
|
||||
|
||||
interface BarrierEvent {
|
||||
finish: (id: string) => void;
|
||||
}
|
||||
|
||||
class DynamicBarrier {
|
||||
private readonly finishedIds = new Map<string, Promise<void>>();
|
||||
private readonly events: TypedEventEmitter<BarrierEvent> = new EventEmitter();
|
||||
|
||||
private initFinishingPromise(id: string): Promise<void> {
|
||||
return getOrInsert(this.finishedIds, id, new Promise<void>(resolve => {
|
||||
const handler = (finishedId: string) => {
|
||||
if (finishedId === id) {
|
||||
resolve();
|
||||
this.events.removeListener("finish", handler);
|
||||
}
|
||||
};
|
||||
|
||||
this.events.addListener("finish", handler);
|
||||
}));
|
||||
}
|
||||
|
||||
setFinished(id: string): void {
|
||||
void this.initFinishingPromise(id);
|
||||
|
||||
this.events.emit("finish", id);
|
||||
}
|
||||
|
||||
async blockOn(id: string): Promise<void> {
|
||||
await this.initFinishingPromise(id);
|
||||
}
|
||||
}
|
||||
|
||||
const executeRunnableWith = <Param>(param: Param) => {
|
||||
const barrier = new DynamicBarrier();
|
||||
|
||||
return async (runnable: RunnableWithId<Param>): Promise<void> => {
|
||||
for (const parentRunnable of runnable.runAfter) {
|
||||
await barrier.blockOn(parentRunnable.id);
|
||||
}
|
||||
|
||||
await runnable.run(param);
|
||||
barrier.setFinished(runnable.id);
|
||||
};
|
||||
};
|
||||
|
||||
export function runManyFor(di: DiContainerForInjection): RunMany {
|
||||
const convertToWithId = convertToWithIdWith(di);
|
||||
|
||||
return <Param>(injectionToken: InjectionToken<Runnable<Param>, void>) => async (param: Param) => {
|
||||
const executeRunnable = executeRunnableWith(param);
|
||||
const allRunnables = di.injectManyWithMeta(injectionToken).map(x => convertToWithId(x));
|
||||
|
||||
verifyRunnablesAreDAG(injectionToken.id, allRunnables);
|
||||
|
||||
await Promise.all(allRunnables.map(executeRunnable));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { createContainer, getInjectable, getInjectionToken } from "@ogre-tools/injectable";
|
||||
import { runManySyncFor } from "./run-many-sync-for";
|
||||
import type { RunnableSync } from "./types";
|
||||
|
||||
describe("runManySyncFor", () => {
|
||||
describe("given hierarchy, when running many", () => {
|
||||
let runMock: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
runMock = jest.fn();
|
||||
|
||||
const someInjectionTokenForRunnables = getInjectionToken<RunnableSync>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable = getInjectable({
|
||||
id: "some-injectable",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-call"),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
const someOtherInjectable = getInjectable({
|
||||
id: "some-other-injectable",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-other-call"),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
rootDi.register(someInjectable, someOtherInjectable);
|
||||
|
||||
const runMany = runManySyncFor(rootDi)(someInjectionTokenForRunnables);
|
||||
|
||||
runMany();
|
||||
});
|
||||
|
||||
it("runs all runnables at the same time", () => {
|
||||
expect(runMock.mock.calls).toEqual([
|
||||
["some-call"],
|
||||
["some-other-call"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("given hierarchy that is three levels deep, when running many", () => {
|
||||
let runMock: jest.Mock<(arg: string) => void>;
|
||||
|
||||
beforeEach(() => {
|
||||
const di = createContainer("irrelevant");
|
||||
|
||||
runMock = jest.fn();
|
||||
|
||||
const someInjectionTokenForRunnables = getInjectionToken<RunnableSync>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable1 = getInjectable({
|
||||
id: "some-injectable-1",
|
||||
instantiate: () => ({
|
||||
run: () => void runMock("third-level-run"),
|
||||
runAfter: someInjectable2,
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
const someInjectable2 = getInjectable({
|
||||
id: "some-injectable-2",
|
||||
instantiate: () => ({
|
||||
run: () => void runMock("second-level-run"),
|
||||
runAfter: someInjectable3,
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
const someInjectable3 = getInjectable({
|
||||
id: "some-injectable-3",
|
||||
instantiate: () => ({
|
||||
run: () => void runMock("first-level-run"),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnables,
|
||||
});
|
||||
|
||||
di.register(someInjectable1, someInjectable2, someInjectable3);
|
||||
|
||||
const runMany = runManySyncFor(di)(someInjectionTokenForRunnables);
|
||||
|
||||
runMany();
|
||||
});
|
||||
|
||||
it("runs runnables in order", () => {
|
||||
expect(runMock.mock.calls).toEqual([["first-level-run"], ["second-level-run"], ["third-level-run"]]);
|
||||
});
|
||||
});
|
||||
|
||||
it("given invalid hierarchy, when running runnables, throws", () => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
const runMock = jest.fn();
|
||||
|
||||
const someInjectionToken = getInjectionToken<RunnableSync>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someOtherInjectionToken = getInjectionToken<RunnableSync>({
|
||||
id: "some-other-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable = getInjectable({
|
||||
id: "some-runnable-1",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-runnable-1"),
|
||||
runAfter: someOtherInjectable,
|
||||
}),
|
||||
injectionToken: someInjectionToken,
|
||||
});
|
||||
|
||||
const someOtherInjectable = getInjectable({
|
||||
id: "some-runnable-2",
|
||||
instantiate: () => ({
|
||||
run: () => runMock("some-runnable-2"),
|
||||
}),
|
||||
injectionToken: someOtherInjectionToken,
|
||||
});
|
||||
|
||||
rootDi.register(someInjectable, someOtherInjectable);
|
||||
|
||||
const runMany = runManySyncFor(rootDi)(
|
||||
someInjectionToken,
|
||||
);
|
||||
|
||||
return expect(() => runMany()).toThrow(
|
||||
/Runnable "some-runnable-1" is unreachable for injection token "some-injection-token": run afters "some-runnable-2" are a part of different injection tokens./,
|
||||
);
|
||||
});
|
||||
|
||||
describe("when running many with parameter", () => {
|
||||
let runMock: jest.Mock<(arg: string, arg2: string) => undefined>;
|
||||
|
||||
beforeEach(() => {
|
||||
const rootDi = createContainer("irrelevant");
|
||||
|
||||
runMock = jest.fn();
|
||||
|
||||
const someInjectionTokenForRunnablesWithParameter = getInjectionToken<
|
||||
RunnableSync<string>
|
||||
>({
|
||||
id: "some-injection-token",
|
||||
});
|
||||
|
||||
const someInjectable = getInjectable({
|
||||
id: "some-runnable-1",
|
||||
instantiate: () => ({
|
||||
run: (parameter) => void runMock("run-of-some-runnable-1", parameter),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnablesWithParameter,
|
||||
});
|
||||
|
||||
const someOtherInjectable = getInjectable({
|
||||
id: "some-runnable-2",
|
||||
instantiate: () => ({
|
||||
run: (parameter) => void runMock("run-of-some-runnable-2", parameter),
|
||||
}),
|
||||
injectionToken: someInjectionTokenForRunnablesWithParameter,
|
||||
});
|
||||
|
||||
rootDi.register(someInjectable, someOtherInjectable);
|
||||
|
||||
const runMany = runManySyncFor(rootDi)(
|
||||
someInjectionTokenForRunnablesWithParameter,
|
||||
);
|
||||
|
||||
runMany("some-parameter");
|
||||
});
|
||||
|
||||
it("runs all runnables using the parameter", () => {
|
||||
expect(runMock.mock.calls).toEqual([
|
||||
["run-of-some-runnable-1", "some-parameter"],
|
||||
["run-of-some-runnable-2", "some-parameter"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { DiContainerForInjection, InjectionToken } from "@ogre-tools/injectable";
|
||||
import type { Disposer } from "@k8slens/utilities";
|
||||
import type { RunnableSync, RunSync, RunnableSyncWithId } from "./types";
|
||||
import { convertToWithIdWith, verifyRunnablesAreDAG } from "./helpers";
|
||||
import type TypedEventEmitter from "typed-emitter";
|
||||
import EventEmitter from "events";
|
||||
|
||||
export type RunManySync = <Param>(injectionToken: InjectionToken<RunnableSync<Param>, void>) => RunSync<Param>;
|
||||
|
||||
class SyncBarrier {
|
||||
private readonly finishedIds = new Set<string>();
|
||||
private readonly events: TypedEventEmitter<Record<string, () => void>> = new EventEmitter();
|
||||
|
||||
setFinished(id: string): void {
|
||||
this.finishedIds.add(id);
|
||||
this.events.emit(id);
|
||||
}
|
||||
|
||||
onceParentsAreFinished(id: string, parentIds: string[], action: () => void) {
|
||||
const finishers = new Map<string, Disposer>();
|
||||
|
||||
const checkAndRun = () => {
|
||||
if (finishers.size === 0) {
|
||||
action();
|
||||
this.setFinished(id);
|
||||
}
|
||||
};
|
||||
|
||||
for (const parentId of parentIds) {
|
||||
if (this.finishedIds.has(parentId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const onParentFinished = () => {
|
||||
this.events.removeListener(parentId, onParentFinished);
|
||||
finishers.delete(parentId);
|
||||
checkAndRun();
|
||||
};
|
||||
|
||||
finishers.set(parentId, onParentFinished);
|
||||
this.events.once(parentId, onParentFinished);
|
||||
}
|
||||
|
||||
checkAndRun();
|
||||
}
|
||||
}
|
||||
|
||||
const executeRunnableWith = <Param>(param: Param) => {
|
||||
const barrier = new SyncBarrier();
|
||||
|
||||
return (runnable: RunnableSyncWithId<Param>) => {
|
||||
barrier.onceParentsAreFinished(
|
||||
runnable.id,
|
||||
runnable.runAfter.map(r => r.id),
|
||||
() => runnable.run(param),
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
export function runManySyncFor(di: DiContainerForInjection): RunManySync {
|
||||
const convertToWithId = convertToWithIdWith(di);
|
||||
|
||||
return <Param>(injectionToken: InjectionToken<RunnableSync<Param>, void>) => (param: Param): undefined => {
|
||||
const executeRunnable = executeRunnableWith(param);
|
||||
const allRunnables = di.injectManyWithMeta(injectionToken).map(convertToWithId);
|
||||
|
||||
verifyRunnablesAreDAG(injectionToken.id, allRunnables);
|
||||
|
||||
allRunnables.forEach(executeRunnable);
|
||||
|
||||
return undefined;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { Injectable } from "@ogre-tools/injectable";
|
||||
import type { SingleOrMany } from "@k8slens/utilities";
|
||||
|
||||
export type Run<Param> = (parameter: Param) => Promise<void> | void;
|
||||
|
||||
export interface Runnable<T = void> {
|
||||
id?: never;
|
||||
run: Run<T>;
|
||||
readonly runAfter?: SingleOrMany<Injectable<Runnable<T>, Runnable<T>, void>>;
|
||||
}
|
||||
|
||||
export interface RunnableWithId<T> {
|
||||
run: Run<T>;
|
||||
readonly id: string;
|
||||
readonly runAfter: RunnableWithId<T>[];
|
||||
}
|
||||
|
||||
export interface RunnableSync<T = void> {
|
||||
id?: never;
|
||||
run: RunSync<T>;
|
||||
runAfter?: SingleOrMany<Injectable<RunnableSync<T>, RunnableSync<T>, void>>;
|
||||
}
|
||||
|
||||
export interface RunnableSyncWithId<T> {
|
||||
run: RunSync<T>;
|
||||
readonly id: string;
|
||||
readonly runAfter: RunnableSyncWithId<T>[];
|
||||
}
|
||||
|
||||
/**
|
||||
* NOTE: this is the worse of two evils. This makes sure that `RunnableSync` always is sync.
|
||||
* If the return type is `void` instead then async functions (those return `Promise<T>`) can
|
||||
* coerce to it.
|
||||
*/
|
||||
export type RunSync<Param> = (parameter: Param) => undefined;
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "@k8slens/typescript/config/base.json"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = require("@k8slens/webpack").configForNode;
|
||||
@@ -0,0 +1,3 @@
|
||||
# @k8slens/test-utils
|
||||
|
||||
This package contains many useful utilities for testing.
|
||||
@@ -0,0 +1,4 @@
|
||||
export * from "./src/flush-promises";
|
||||
export * from "./src/get-global-override-for-function";
|
||||
export * from "./src/get-global-override";
|
||||
export * from "./src/get-promise-status";
|
||||
@@ -0,0 +1,2 @@
|
||||
module.exports =
|
||||
require("@k8slens/jest").monorepoPackageConfig(__dirname).configForReact;
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@k8slens/test-utils",
|
||||
"version": "1.0.0",
|
||||
"description": "A collection of utilities for testing",
|
||||
"type": "commonjs",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org/"
|
||||
},
|
||||
"private": false,
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"author": {
|
||||
"name": "OpenLens Authors",
|
||||
"email": "info@k8slens.dev"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/lensapp/lens",
|
||||
"scripts": {
|
||||
"build": "webpack",
|
||||
"dev": "webpack --mode=development --watch",
|
||||
"test": "jest --coverage --runInBand"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { setImmediate } from "timers";
|
||||
|
||||
export const flushPromises = () => new Promise(setImmediate);
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { Injectable } from "@ogre-tools/injectable";
|
||||
import { getGlobalOverride } from "./get-global-override";
|
||||
import { camelCase } from "lodash/fp";
|
||||
|
||||
export const getGlobalOverrideForFunction = (injectable: Injectable<Function, any, any>) => (
|
||||
getGlobalOverride(injectable, () => (...args: any[]) => {
|
||||
console.warn(
|
||||
`Tried to invoke a function "${injectable.id}" without override. The args were:`,
|
||||
args,
|
||||
);
|
||||
|
||||
throw new Error(
|
||||
`Tried to invoke a function "${injectable.id}" without override. Add eg. "di.override(${camelCase(injectable.id)}Mock)" to the unit test interested in this.`,
|
||||
);
|
||||
})
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { Injectable, Instantiate } from "@ogre-tools/injectable";
|
||||
|
||||
export interface GlobalOverride<Instance, Param> {
|
||||
injectable: Injectable<Instance, unknown, Param>;
|
||||
overridingInstantiate: Instantiate<Instance, Param>;
|
||||
}
|
||||
|
||||
export const getGlobalOverride = <Instance, Param>(
|
||||
injectable: Injectable<Instance, unknown, Param>,
|
||||
overridingInstantiate: (typeof injectable)["instantiate"],
|
||||
) => ({
|
||||
injectable,
|
||||
overridingInstantiate,
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { flushPromises } from "./flush-promises";
|
||||
|
||||
export const getPromiseStatus = async (promise: Promise<unknown>) => {
|
||||
const status = { fulfilled: false };
|
||||
|
||||
promise.finally(() => {
|
||||
status.fulfilled = true;
|
||||
});
|
||||
|
||||
await flushPromises();
|
||||
|
||||
return status;
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "@k8slens/typescript/config/base.json"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = require("@k8slens/webpack").configForNode;
|
||||
@@ -0,0 +1,3 @@
|
||||
# @k8slens/utilities
|
||||
|
||||
This package contains many useful types.
|
||||
@@ -0,0 +1,45 @@
|
||||
export * from "./src/abort-controller";
|
||||
export * from "./src/array";
|
||||
export * from "./src/backoff-caller";
|
||||
export * from "./src/base64";
|
||||
export * from "./src/buildUrl";
|
||||
export * from "./src/camelCase";
|
||||
export * from "./src/collection-functions";
|
||||
export * from "./src/computed-or";
|
||||
export * from "./src/convertCpu";
|
||||
export * from "./src/convertMemory";
|
||||
export * from "./src/cssNames";
|
||||
export * from "./src/cssVar";
|
||||
export * from "./src/debouncePromise";
|
||||
export * from "./src/delay";
|
||||
export * from "./src/display-mode";
|
||||
export * from "./src/disposer";
|
||||
export * from "./src/formatDuration";
|
||||
export * from "./src/hash-set";
|
||||
export * from "./src/interval";
|
||||
export * from "./src/is-node-falsy";
|
||||
export * from "./src/isMiddleClick";
|
||||
export * from "./src/isReactNode";
|
||||
export * from "./src/iter";
|
||||
export * from "./src/json";
|
||||
export * from "./src/jsonPath";
|
||||
export * from "./src/metricUnitsToNumber";
|
||||
export * from "./src/name-parts";
|
||||
export * from "./src/noop";
|
||||
export * from "./src/object";
|
||||
export * from "./src/observable-crate";
|
||||
export * from "./src/on-keyboard-shortcut";
|
||||
export * from "./src/prevDefault";
|
||||
export * from "./src/readableStream";
|
||||
export * from "./src/readonly";
|
||||
export * from "./src/reject-promise";
|
||||
export * from "./src/result";
|
||||
export * from "./src/sort-compare";
|
||||
export * from "./src/sort-function";
|
||||
export * from "./src/tar";
|
||||
export * from "./src/tuple";
|
||||
export * from "./src/type-narrowing";
|
||||
export * from "./src/types";
|
||||
export * from "./src/union-env-path";
|
||||
export * from "./src/wait";
|
||||
export * from "./src/with-concurrency-limit";
|
||||
@@ -0,0 +1,2 @@
|
||||
module.exports =
|
||||
require("@k8slens/jest").monorepoPackageConfig(__dirname).configForReact;
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "@k8slens/utilities",
|
||||
"description": "A collection of useful types",
|
||||
"version": "1.0.0",
|
||||
"type": "commonjs",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org/"
|
||||
},
|
||||
"private": false,
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"author": {
|
||||
"name": "OpenLens Authors",
|
||||
"email": "info@k8slens.dev"
|
||||
},
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/lensapp/lens",
|
||||
"scripts": {
|
||||
"build": "webpack",
|
||||
"dev": "webpack --mode=development --watch",
|
||||
"test": "jest --coverage --runInBand"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mobx": "^6.8.0",
|
||||
"type-fest": "^2.19.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import AbortController from "abort-controller";
|
||||
|
||||
/**
|
||||
* This is like an `AbortController` but will also abort if the parent aborts,
|
||||
* but won't make the parent abort if this aborts (single direction)
|
||||
*/
|
||||
export class WrappedAbortController extends AbortController {
|
||||
constructor(parent?: AbortController | undefined) {
|
||||
super();
|
||||
|
||||
parent?.signal.addEventListener("abort", () => {
|
||||
this.abort();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function setTimeoutFor(controller: AbortController, timeout: number): void {
|
||||
const handle = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
controller.signal.addEventListener("abort", () => clearTimeout(handle));
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A inference typed version of `Array(length).fill(value)`
|
||||
* @param length The number of entries
|
||||
* @param value The value of each of the indices
|
||||
*/
|
||||
function filled<T>(length: number, value: T): T[] {
|
||||
return Array(length).fill(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* This function splits an array into two sub arrays on the first instance of
|
||||
* element (from the left). If the array does not contain the element. The
|
||||
* return value is defined to be `[array, [], false]`. If the element is in
|
||||
* the array then the return value is `[left, right, true]` where `left` is
|
||||
* the elements of `array` from `[0, index)` and `right` is `(index, length)`
|
||||
* @param array the full array to split into two sub-arrays
|
||||
* @param element the element in the middle of the array
|
||||
* @returns the left and right sub-arrays which when conjoined with `element`
|
||||
* is the same as `array`, and `true`
|
||||
*/
|
||||
function split<T>(src: T[], element: T): [T[], T[], boolean] {
|
||||
const index = src.indexOf(element);
|
||||
|
||||
if (index < 0) {
|
||||
return [src, [], false];
|
||||
}
|
||||
|
||||
return [src.slice(0, index), src.slice(index + 1, src.length), true];
|
||||
}
|
||||
|
||||
function bifurcate<T>(src: T[], condition: (item: T) => any): [falses: T[], trues: T[]] {
|
||||
const trues: T[] = [];
|
||||
const falses: T[] = [];
|
||||
|
||||
for (const item of src) {
|
||||
if (condition(item)) {
|
||||
trues.push(item);
|
||||
} else {
|
||||
falses.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
return [falses, trues];
|
||||
}
|
||||
|
||||
export const array = {
|
||||
bifurcate,
|
||||
filled,
|
||||
split,
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { AsyncResult, Result } from "./result";
|
||||
import { delay } from "./delay";
|
||||
import { noop } from "./noop";
|
||||
|
||||
/**
|
||||
* @param error The error that resulted in the failure
|
||||
* @param attempt The 1-index attempt count
|
||||
*/
|
||||
export type OnIntermediateError<E> = (error: E, attempt: number) => void;
|
||||
|
||||
export interface BackoffCallerOptions<E> {
|
||||
/**
|
||||
* Called when an attempt fails
|
||||
*/
|
||||
onIntermediateError?: OnIntermediateError<E>;
|
||||
|
||||
/**
|
||||
* @default 5
|
||||
*/
|
||||
maxAttempts?: number;
|
||||
|
||||
/**
|
||||
* In milliseconds
|
||||
* @default 1000
|
||||
*/
|
||||
initialTimeout?: number;
|
||||
|
||||
/**
|
||||
* @default 2
|
||||
*/
|
||||
scaleFactor?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls `fn` once and then again (with exponential delay between each attempt) up to `options.maxAttempts` times.
|
||||
* @param fn The function to repeatedly attempt
|
||||
* @returns The first success or the last failure
|
||||
*/
|
||||
export const backoffCaller = async <T, E>(fn: () => AsyncResult<T, E>, options?: BackoffCallerOptions<E>): AsyncResult<T, E> => {
|
||||
const {
|
||||
initialTimeout = 1000,
|
||||
maxAttempts = 5,
|
||||
onIntermediateError = noop as OnIntermediateError<E>,
|
||||
scaleFactor = 2,
|
||||
} = options ?? {};
|
||||
|
||||
let timeout = initialTimeout;
|
||||
let attempt = 0;
|
||||
let result: Result<T, E>;
|
||||
|
||||
do {
|
||||
result = await fn();
|
||||
|
||||
if (result.callWasSuccessful) {
|
||||
return result;
|
||||
}
|
||||
|
||||
onIntermediateError(result.error, attempt + 1);
|
||||
|
||||
await delay(timeout);
|
||||
timeout *= scaleFactor;
|
||||
} while (attempt += 1, attempt < maxAttempts);
|
||||
|
||||
return result;
|
||||
};
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Encode/decode utf-8 base64 string
|
||||
import * as Base64 from "crypto-js/enc-base64";
|
||||
import * as Utf8 from "crypto-js/enc-utf8";
|
||||
|
||||
/**
|
||||
* Computes utf-8 from base64
|
||||
* @param data A Base64 encoded string
|
||||
* @returns The original utf-8 string
|
||||
*/
|
||||
function decode(data: string): string {
|
||||
return Base64.parse(data).toString(Utf8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes base64 from utf-8
|
||||
* @param data A normal string
|
||||
* @returns A base64 encoded version
|
||||
*/
|
||||
function encode(data: string): string {
|
||||
return Utf8.parse(data).toString(Base64);
|
||||
}
|
||||
|
||||
export const base64 = {
|
||||
encode,
|
||||
decode,
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { compile } from "path-to-regexp";
|
||||
import type { RouteProps } from "react-router";
|
||||
import { isDefined } from "./type-narrowing";
|
||||
|
||||
export interface UrlRouteProps extends RouteProps {
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface URLParams<P extends object = {}, Q extends object = {}> {
|
||||
params?: P;
|
||||
query?: Q;
|
||||
fragment?: string;
|
||||
}
|
||||
|
||||
export function buildURL<P extends object = {}, Q extends object = {}>(path: string, { params, query, fragment }: URLParams<P, Q> = {}) {
|
||||
const pathBuilder = compile(String(path));
|
||||
|
||||
const queryParams = query ? new URLSearchParams(Object.entries(query)).toString() : "";
|
||||
const parts = [
|
||||
pathBuilder(params),
|
||||
queryParams && `?${queryParams}`,
|
||||
fragment && `#${fragment}`,
|
||||
];
|
||||
|
||||
return parts.filter(isDefined).join("");
|
||||
}
|
||||
|
||||
export function buildURLPositional<P extends object = {}, Q extends object = {}>(path: string) {
|
||||
return function (params?: P, query?: Q, fragment?: string): string {
|
||||
return buildURL(path, { params, query, fragment });
|
||||
};
|
||||
}
|
||||
|
||||
export type UrlParamsFor<Pathname extends string> =
|
||||
Pathname extends `${string}/:${infer A}?/${infer Tail}`
|
||||
? Partial<Record<A, string>> & UrlParamsFor<`/${Tail}`>
|
||||
: Pathname extends `${string}/:${infer A}/${infer Tail}`
|
||||
? Record<A, string> & UrlParamsFor<`/${Tail}`>
|
||||
: Pathname extends `${string}/:${infer A}?`
|
||||
? Partial<Record<A, string>>
|
||||
: Pathname extends `${string}/:${infer A}`
|
||||
? Record<A, string>
|
||||
: {};
|
||||
|
||||
export interface UrlBuilder<Pathname extends string> {
|
||||
compile(params: UrlParamsFor<Pathname>, query?: object, fragment?: string): string;
|
||||
}
|
||||
|
||||
export function urlBuilderFor<Pathname extends string>(pathname: Pathname): UrlBuilder<Pathname> {
|
||||
return {
|
||||
compile: buildURLPositional(pathname),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Convert object's keys to camelCase format
|
||||
import { camelCase } from "lodash";
|
||||
import type { SingleOrMany } from "./types";
|
||||
import { isObject, isString } from "./type-narrowing";
|
||||
import { object } from "./object";
|
||||
|
||||
export function toCamelCase<T extends Record<string, unknown>[]>(obj: T): T;
|
||||
export function toCamelCase<T extends Record<string, unknown>>(obj: T): T;
|
||||
|
||||
export function toCamelCase(obj: SingleOrMany<Record<string, unknown> | unknown>): SingleOrMany<Record<string, unknown> | unknown> {
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(toCamelCase);
|
||||
}
|
||||
|
||||
if (isObject(obj)) {
|
||||
return object.fromEntries(
|
||||
object.entries(obj)
|
||||
.filter((pair): pair is [string, unknown] => isString(pair[0]))
|
||||
.map(([key, value]) => [camelCase(key), isObject(value) ? toCamelCase(value) : value]),
|
||||
);
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { runInAction } from "mobx";
|
||||
import { inspect } from "util";
|
||||
import { isDefined } from "./type-narrowing";
|
||||
|
||||
/**
|
||||
* Get the value behind `key`. If it was not present, first insert `value`
|
||||
* @param map The map to interact with
|
||||
* @param key The key to insert into the map with
|
||||
* @param value The value to optional add to the map
|
||||
* @returns The value in the map
|
||||
*/
|
||||
export function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V {
|
||||
if (!map.has(key)) {
|
||||
map.set(key, value);
|
||||
}
|
||||
|
||||
return map.get(key)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates map and returns the value that was just inserted
|
||||
*/
|
||||
export function put<K, V>(map: Map<K, V>, key: K, value: V): V {
|
||||
map.set(key, value);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `getOrInsert` but specifically for when `V` is `Map<MK, MV>` so that
|
||||
* the typings are inferred correctly.
|
||||
*/
|
||||
export function getOrInsertMap<K, MK, MV>(map: Map<K, Map<MK, MV>>, key: K): Map<MK, MV> {
|
||||
return getOrInsert(map, key, new Map<MK, MV>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `getOrInsert` but specifically for when `V` is `Set<any>` so that
|
||||
* the typings are inferred.
|
||||
*/
|
||||
export function getOrInsertSet<K, SK>(map: Map<K, Set<SK>>, key: K): Set<SK> {
|
||||
return getOrInsert(map, key, new Set<SK>());
|
||||
}
|
||||
|
||||
/**
|
||||
* A currying version of {@link getOrInsertSet}
|
||||
*/
|
||||
export function getOrInsertSetFor<K, SK>(map: Map<K, Set<SK>>): (key: K) => Set<SK> {
|
||||
return (key) => getOrInsertSet(map, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `getOrInsert` but with delayed creation of the item. Which is useful
|
||||
* if it is very expensive to create the initial value.
|
||||
*/
|
||||
export function getOrInsertWith<K, V>(map: Map<K, V>, key: K, builder: () => V): V;
|
||||
export function getOrInsertWith<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, builder: () => V): V;
|
||||
|
||||
export function getOrInsertWith<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, builder: () => V): V {
|
||||
if (!map.has(key)) {
|
||||
map.set(key, builder());
|
||||
}
|
||||
|
||||
return map.get(key)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link getOrInsertWith} but the builder is async and will be awaited before inserting into the map
|
||||
*/
|
||||
export async function getOrInsertWithAsync<K, V>(map: Map<K, V>, key: K, asyncBuilder: () => Promise<V>): Promise<V> {
|
||||
if (!map.has(key)) {
|
||||
map.set(key, await asyncBuilder());
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return map.get(key)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value associated with `key` iff there was not a previous value
|
||||
* @param map The map to interact with
|
||||
* @throws if `key` already in map
|
||||
* @returns `this` so that `strictSet` can be chained
|
||||
*/
|
||||
export function strictSet<K, V>(map: Map<K, V>, key: K, val: V): typeof map {
|
||||
if (map.has(key)) {
|
||||
throw new TypeError(`Map already contains key: ${inspect(key)}`);
|
||||
}
|
||||
|
||||
return map.set(key, val);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value associated with `key`
|
||||
* @param map The map to interact with
|
||||
* @throws if `key` did not a value associated with it
|
||||
*/
|
||||
export function strictGet<K, V>(map: Map<K, V>, key: K): V {
|
||||
if (!map.has(key)) {
|
||||
throw new TypeError(`Map does not contains key: ${inspect(key)}`);
|
||||
}
|
||||
|
||||
return map.get(key)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* If `key` is in `set`, remove it otherwise add it.
|
||||
* @param set The set to manipulate
|
||||
* @param key The key to toggle the "is in"-ness of
|
||||
*/
|
||||
export function toggle<K>(set: Set<K>, key: K): void {
|
||||
runInAction(() => {
|
||||
// Returns true if value was already in Set; otherwise false.
|
||||
if (!set.delete(key)) {
|
||||
set.add(key);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function to also check for defined-ness
|
||||
*/
|
||||
export function includes<T>(src: T[], value: T | null | undefined): boolean {
|
||||
return isDefined(value) && src.includes(value);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { IComputedValue } from "mobx";
|
||||
import { computed } from "mobx";
|
||||
|
||||
export const computedOr = (...values: IComputedValue<boolean>[]) => computed((
|
||||
() => values.some(value => value.get())
|
||||
));
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { bytesToUnits, unitsToBytes } from "./convertMemory";
|
||||
|
||||
describe("unitsToBytes", () => {
|
||||
it("without any units, just parse as float", () => {
|
||||
expect(unitsToBytes("1234")).toBe(1234);
|
||||
});
|
||||
|
||||
it("should parse with B suffix", () => {
|
||||
expect(unitsToBytes("1234B")).toBe(1234);
|
||||
});
|
||||
|
||||
it("should parse with Ki suffix", () => {
|
||||
expect(unitsToBytes("1234Ki")).toBe(1234 * (1024));
|
||||
});
|
||||
|
||||
it("should parse with Ki suffix as the same as KiB", () => {
|
||||
expect(unitsToBytes("1234Ki")).toBe(unitsToBytes("1234KiB"));
|
||||
});
|
||||
|
||||
it("should parse with Mi suffix", () => {
|
||||
expect(unitsToBytes("1234Mi")).toBe(1234 * (1024 ** 2));
|
||||
});
|
||||
|
||||
it("should parse with Mi suffix as the same as MiB", () => {
|
||||
expect(unitsToBytes("1234Mi")).toBe(unitsToBytes("1234MiB"));
|
||||
});
|
||||
|
||||
it("should parse with Gi suffix", () => {
|
||||
expect(unitsToBytes("1234Gi")).toBe(1234 * (1024 ** 3));
|
||||
});
|
||||
|
||||
it("should parse with Gi suffix as the same as GiB", () => {
|
||||
expect(unitsToBytes("1234Gi")).toBe(unitsToBytes("1234GiB"));
|
||||
});
|
||||
|
||||
it("should parse with Ti suffix", () => {
|
||||
expect(unitsToBytes("1234Ti")).toBe(1234 * (1024 ** 4));
|
||||
});
|
||||
|
||||
it("should parse with Ti suffix as the same as TiB", () => {
|
||||
expect(unitsToBytes("1234Ti")).toBe(unitsToBytes("1234TiB"));
|
||||
});
|
||||
|
||||
it("should parse with Pi suffix", () => {
|
||||
expect(unitsToBytes("1234Pi")).toBe(1234 * (1024 ** 5));
|
||||
});
|
||||
|
||||
it("should parse with Pi suffix as the same as PiB", () => {
|
||||
expect(unitsToBytes("1234Pi")).toBe(unitsToBytes("1234PiB"));
|
||||
});
|
||||
|
||||
it("given unrelated data, return NaN", () => {
|
||||
expect(unitsToBytes("I am not a number")).toBeNaN();
|
||||
});
|
||||
|
||||
it("given unrelated data, but has number, return that", () => {
|
||||
expect(unitsToBytes("I am not a number, but this is 0.1")).toBe(0.1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bytesToUnits", () => {
|
||||
it("should return N/A for invalid bytes", () => {
|
||||
expect(bytesToUnits(-1)).toBe("N/A");
|
||||
expect(bytesToUnits(Infinity)).toBe("N/A");
|
||||
expect(bytesToUnits(NaN)).toBe("N/A");
|
||||
});
|
||||
|
||||
it("given a number within the magnitude of 0..124, format with B", () => {
|
||||
expect(bytesToUnits(100)).toBe("100.0B");
|
||||
});
|
||||
|
||||
it("given a number within the magnitude of 1024..1024^2, format with KiB", () => {
|
||||
expect(bytesToUnits(1024)).toBe("1.0KiB");
|
||||
expect(bytesToUnits(2048)).toBe("2.0KiB");
|
||||
expect(bytesToUnits(1900)).toBe("1.9KiB");
|
||||
expect(bytesToUnits(50*1024 + 1)).toBe("50.0KiB");
|
||||
});
|
||||
|
||||
it("given a number within the magnitude of 1024^2..1024^3, format with MiB", () => {
|
||||
expect(bytesToUnits(1024**2)).toBe("1.0MiB");
|
||||
expect(bytesToUnits(2048**2)).toBe("4.0MiB");
|
||||
expect(bytesToUnits(1900 * 1024)).toBe("1.9MiB");
|
||||
expect(bytesToUnits(50*(1024 ** 2) + 1)).toBe("50.0MiB");
|
||||
});
|
||||
|
||||
it("given a number within the magnitude of 1024^3..1024^4, format with GiB", () => {
|
||||
expect(bytesToUnits(1024**3)).toBe("1.0GiB");
|
||||
expect(bytesToUnits(2048**3)).toBe("8.0GiB");
|
||||
expect(bytesToUnits(1900 * 1024 ** 2)).toBe("1.9GiB");
|
||||
expect(bytesToUnits(50*(1024 ** 3) + 1)).toBe("50.0GiB");
|
||||
});
|
||||
|
||||
it("given a number within the magnitude of 1024^4..1024^5, format with TiB", () => {
|
||||
expect(bytesToUnits(1024**4)).toBe("1.0TiB");
|
||||
expect(bytesToUnits(2048**4)).toBe("16.0TiB");
|
||||
expect(bytesToUnits(1900 * 1024 ** 3)).toBe("1.9TiB");
|
||||
expect(bytesToUnits(50*(1024 ** 4) + 1)).toBe("50.0TiB");
|
||||
});
|
||||
|
||||
it("given a number within the magnitude of 1024^5..1024^6, format with PiB", () => {
|
||||
expect(bytesToUnits(1024**5)).toBe("1.0PiB");
|
||||
expect(bytesToUnits(2048**5)).toBe("32.0PiB");
|
||||
expect(bytesToUnits(1900 * 1024 ** 4)).toBe("1.9PiB");
|
||||
expect(bytesToUnits(50*(1024 ** 5) + 1)).toBe("50.0PiB");
|
||||
});
|
||||
});
|
||||
|
||||
describe("bytesToUnits -> unitsToBytes", () => {
|
||||
it("given an input, round trip to the same value, given enough precision", () => {
|
||||
expect(unitsToBytes(bytesToUnits(123))).toBe(123);
|
||||
expect(unitsToBytes(bytesToUnits(1024**0 + 1, { precision: 2 }))).toBe(1024**0 + 1);
|
||||
expect(unitsToBytes(bytesToUnits(1024**1 + 2, { precision: 3 }))).toBe(1024**1 + 2);
|
||||
expect(unitsToBytes(bytesToUnits(1024**2 + 3, { precision: 6 }))).toBe(1024**2 + 3);
|
||||
expect(unitsToBytes(bytesToUnits(1024**3 + 4, { precision: 9 }))).toBe(1024**3 + 4);
|
||||
expect(unitsToBytes(bytesToUnits(1024**4 + 5, { precision: 12 }))).toBe(1024**4 + 5);
|
||||
expect(unitsToBytes(bytesToUnits(1024**5 + 6, { precision: 16 }))).toBe(1024**5 + 6);
|
||||
expect(unitsToBytes(bytesToUnits(1024**6 + 7, { precision: 20 }))).toBe(1024**6 + 7);
|
||||
});
|
||||
|
||||
it("given an invalid input, round trips to NaN", () => {
|
||||
expect(unitsToBytes(bytesToUnits(-1))).toBeNaN();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { TypedRegEx } from "typed-regex";
|
||||
|
||||
// Helper to convert CPU K8S units to numbers
|
||||
|
||||
const unitConverters = new Map([
|
||||
["n", 1000 ** -3],
|
||||
["u", 1000 ** -2],
|
||||
["m", 1000 ** -1], // milli
|
||||
["", 1000 ** 0], // no units
|
||||
["k", 1000 ** 1],
|
||||
["M", 1000 ** 2],
|
||||
["G", 1000 ** 3],
|
||||
["P", 1000 ** 4],
|
||||
["T", 1000 ** 5],
|
||||
["E", 1000 ** 6],
|
||||
]);
|
||||
|
||||
const cpuUnitsRegex = TypedRegEx("^(?<digits>[+-]?[0-9.]+(e[-+]?[0-9]+)?)(?<unit>[EinumkKMGTP]*)$");
|
||||
|
||||
export function cpuUnitsToNumber(value: string) {
|
||||
const match = cpuUnitsRegex.captures(value);
|
||||
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { digits = "", unit } = match;
|
||||
const conversion = unitConverters.get(unit);
|
||||
|
||||
if (conversion === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return parseFloat(digits) * conversion;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import assert from "assert";
|
||||
import { iter } from "./iter";
|
||||
|
||||
// Helper to convert memory from units Ki, Mi, Gi, Ti, Pi to bytes and vise versa
|
||||
|
||||
const baseMagnitude = 1024;
|
||||
const maxMagnitude = ["PiB", baseMagnitude ** 5] as const;
|
||||
const magnitudes = new Map([
|
||||
["B", 1] as const,
|
||||
["KiB", baseMagnitude ** 1] as const,
|
||||
["MiB", baseMagnitude ** 2] as const,
|
||||
["GiB", baseMagnitude ** 3] as const,
|
||||
["TiB", baseMagnitude ** 4] as const,
|
||||
maxMagnitude,
|
||||
]);
|
||||
const unitRegex = /(?<value>[0-9]+(\.[0-9]*)?)(?<suffix>(B|[KMGTP]iB?))?/;
|
||||
|
||||
type BinaryUnit = typeof magnitudes extends Map<infer Key, any> ? Key : never;
|
||||
|
||||
export function unitsToBytes(value: string): number {
|
||||
const unitsMatch = value.match(unitRegex);
|
||||
|
||||
if (!unitsMatch?.groups) {
|
||||
return NaN;
|
||||
}
|
||||
|
||||
const parsedValue = parseFloat(unitsMatch.groups.value);
|
||||
|
||||
if (!unitsMatch.groups?.suffix) {
|
||||
return parsedValue;
|
||||
}
|
||||
|
||||
const magnitude = magnitudes.get(unitsMatch.groups.suffix as BinaryUnit)
|
||||
?? magnitudes.get(`${unitsMatch.groups.suffix}B` as BinaryUnit);
|
||||
|
||||
assert(magnitude, "UnitRegex is wrong some how");
|
||||
|
||||
return parseInt((parsedValue * magnitude).toFixed(1));
|
||||
}
|
||||
|
||||
export interface BytesToUnitesOptions {
|
||||
/**
|
||||
* The number of decimal places. MUST be an integer. MUST be in the range [0, 20].
|
||||
* @default 1
|
||||
*/
|
||||
precision?: number;
|
||||
}
|
||||
|
||||
export function bytesToUnits(bytes: number, { precision = 1 }: BytesToUnitesOptions = {}): string {
|
||||
if (bytes <= 0 || isNaN(bytes) || !isFinite(bytes)) {
|
||||
return "N/A";
|
||||
}
|
||||
|
||||
const index = Math.floor(Math.log(bytes) / Math.log(baseMagnitude));
|
||||
const [suffix, magnitude] = iter.nth(magnitudes.entries(), index) ?? maxMagnitude;
|
||||
|
||||
return `${(bytes / magnitude).toFixed(precision)}${suffix}`;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { getConvertedParts } from "./name-parts";
|
||||
|
||||
describe("getConvertedParts", () => {
|
||||
it.each([
|
||||
["hello", ["hello"]],
|
||||
["hello.goodbye", ["hello", "goodbye"]],
|
||||
["hello.1", ["hello", 1]],
|
||||
["3-hello.1", [3, "hello", 1]],
|
||||
["3_hello.1", [3, "hello", 1]],
|
||||
["3_hello.1/foobar", [3, "hello", 1, "foobar"]],
|
||||
["3_hello.1/foobar\\new", [3, "hello", 1, "foobar", "new"]],
|
||||
])("Splits '%s' as into %j", (input, output) => {
|
||||
expect(getConvertedParts(input)).toEqual(output);
|
||||
});
|
||||
});
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { iter } from "./iter";
|
||||
import { object } from "./object";
|
||||
import { isObject } from "./type-narrowing";
|
||||
|
||||
export type IgnoredClassNames = number | symbol | Function;
|
||||
export type IClassName = string | string[] | Record<string, any> | undefined | null | false | IgnoredClassNames;
|
||||
|
||||
export function cssNames(...classNames: IClassName[]): string {
|
||||
const classNamesEnabled = new Map<string, boolean>();
|
||||
|
||||
for (const className of classNames) {
|
||||
if (typeof className === "string") {
|
||||
classNamesEnabled.set(className, true);
|
||||
} else if (Array.isArray(className)) {
|
||||
for (const name of className) {
|
||||
classNamesEnabled.set(name, true);
|
||||
}
|
||||
} else if (isObject(className)) {
|
||||
for (const [name, value] of object.entries(className)) {
|
||||
classNamesEnabled.set(name, Boolean(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return iter.chain(classNamesEnabled.entries())
|
||||
.filter(([, isActive]) => isActive)
|
||||
.filterMap(([className]) => className.trim())
|
||||
.join(" ");
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Helper for getting/setting css-variables
|
||||
|
||||
export function cssVar(elem: HTMLElement) {
|
||||
return {
|
||||
get(name: string) {
|
||||
const value = window.getComputedStyle(elem).getPropertyValue(name).trim();
|
||||
|
||||
return {
|
||||
toString: () => value,
|
||||
valueOf: () => parseFloat(value),
|
||||
};
|
||||
},
|
||||
set(name: string, value: number | string) {
|
||||
if (typeof value === "number") value = `${value}px`;
|
||||
elem.style.setProperty(name, value);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Debouncing promise evaluation
|
||||
|
||||
export function debouncePromise<T, F extends any[]>(func: (...args: F) => T | Promise<T>, timeout = 0): (...args: F) => Promise<T> {
|
||||
let timer: NodeJS.Timeout;
|
||||
|
||||
return (...params: F) => new Promise(resolve => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => resolve(func(...params)), timeout);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type AbortController from "abort-controller";
|
||||
|
||||
/**
|
||||
* Return a promise that will be resolved after at least `timeout` ms have
|
||||
* passed. If `failFast` is provided then the promise is also resolved if it has
|
||||
* been aborted.
|
||||
* @param timeout The number of milliseconds before resolving
|
||||
* @param failFast An abort controller instance to cause the delay to short-circuit
|
||||
*/
|
||||
export function delay(timeout = 1000, failFast?: AbortController): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
const timeoutId = setTimeout(resolve, timeout);
|
||||
|
||||
failFast?.signal.addEventListener("abort", () => {
|
||||
clearTimeout(timeoutId);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Format `mode` in octal notation
|
||||
*/
|
||||
export function displayMode(mode: number): string {
|
||||
return `0o${mode.toString(8)}`;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { SingleOrMany } from "./types";
|
||||
|
||||
export interface Disposer {
|
||||
(): void;
|
||||
}
|
||||
|
||||
export interface Disposable {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface ExtendableDisposer extends Disposer {
|
||||
push(...values: (Disposer | ExtendableDisposer | Disposable)[]): void;
|
||||
}
|
||||
|
||||
export function disposer(...items: SingleOrMany<Disposer | Disposable | undefined | null>[]): ExtendableDisposer {
|
||||
return Object.assign(() => {
|
||||
for (const item of items.flat()) {
|
||||
if (!item) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof item === "function") {
|
||||
item();
|
||||
} else {
|
||||
item.dispose();
|
||||
}
|
||||
}
|
||||
items.length = 0;
|
||||
}, {
|
||||
push: (...newItems) => items.push(...newItems),
|
||||
} as Pick<ExtendableDisposer, "push">);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import moment from "moment";
|
||||
import { formatDuration } from "./formatDuration";
|
||||
|
||||
const second = 1000;
|
||||
const minute = 60 * second;
|
||||
const hour = 60 * minute;
|
||||
const day = 24 * hour;
|
||||
const year = 365 * day;
|
||||
|
||||
describe("human format durations", () => {
|
||||
test("small duration should output something", () => {
|
||||
expect(formatDuration(1)).toBe("0s");
|
||||
expect(formatDuration(3)).toBe("0s");
|
||||
});
|
||||
|
||||
test("returns seconds for duration under 1 min", () => {
|
||||
const res = formatDuration(8 * second);
|
||||
|
||||
expect(res).toBe("8s");
|
||||
});
|
||||
|
||||
test("zero duration should output something", () => {
|
||||
expect(formatDuration(0)).toBe("0s");
|
||||
});
|
||||
|
||||
describe("when compact is true", () => {
|
||||
|
||||
test("duration under 3 hours return minutes", () => {
|
||||
const res = formatDuration(1 * hour + 35 * minute);
|
||||
|
||||
expect(res).toBe("95m");
|
||||
});
|
||||
|
||||
test("duration under 8 hours return hours and minutes", () => {
|
||||
const res = formatDuration(6 * hour + 15 * minute + 20 * second);
|
||||
|
||||
expect(res).toBe("6h15m");
|
||||
});
|
||||
|
||||
test("duration under 48 hours return hours", () => {
|
||||
const res = formatDuration(1 * day + 4 * hour + 15 * minute);
|
||||
|
||||
expect(res).toBe("28h");
|
||||
});
|
||||
|
||||
test("duration under 2 years return days", () => {
|
||||
const res = formatDuration(400 * day + 4 * hour + 15 * minute);
|
||||
|
||||
expect(res).toBe("400d");
|
||||
});
|
||||
|
||||
test("durations less than 8 years returns years and days", () => {
|
||||
const timeValue = new Date(2020, 0, 10, 12, 0, 0, 0).getTime() - new Date(2018, 0, 4, 12, 0, 0, 0).getTime();
|
||||
|
||||
const res = formatDuration(timeValue);
|
||||
|
||||
expect(res).toBe("2y5d");
|
||||
});
|
||||
|
||||
test("durations more than 8 years returns years", () => {
|
||||
const timeValue = Date.now() - new Date(moment().subtract(9, "years").subtract(5, "days").toDate()).getTime();
|
||||
|
||||
const res = formatDuration(timeValue);
|
||||
|
||||
expect(res).toBe("9y");
|
||||
});
|
||||
|
||||
test("durations more than 8 years returns years", () => {
|
||||
const res = formatDuration(10 * year + 25 * day);
|
||||
|
||||
expect(res).toBe("10y");
|
||||
});
|
||||
test("durations shouldn't include zero magnitude parts", () => {
|
||||
const zeroSeconds = formatDuration(8 * minute);
|
||||
|
||||
expect(zeroSeconds).toBe("8m");
|
||||
|
||||
const zeroMinutes = formatDuration(8 * hour + 15 * minute);
|
||||
|
||||
expect(zeroMinutes).toBe("8h");
|
||||
|
||||
const zeroHours = formatDuration(6 * day + 2 * minute);
|
||||
|
||||
expect(zeroHours).toBe("6d");
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import moment from "moment";
|
||||
|
||||
/**
|
||||
* This function formats durations in a more human readable form.
|
||||
* @param timeValue the duration in milliseconds to format
|
||||
*/
|
||||
export function formatDuration(timeValue: number, compact = true) {
|
||||
const duration = moment.duration(timeValue, "milliseconds");
|
||||
const seconds = Math.floor(duration.asSeconds());
|
||||
const separator = compact ? "": " ";
|
||||
|
||||
if (seconds < 0) {
|
||||
return "0s";
|
||||
} else if (seconds < 60*2 ) {
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
const minutes = Math.floor(duration.asMinutes());
|
||||
|
||||
if (minutes < 10) {
|
||||
const seconds = duration.seconds();
|
||||
|
||||
return getMeaningfulValues([minutes, seconds], ["m", "s"], separator);
|
||||
} else if (minutes < 60 * 3) {
|
||||
if (!compact) {
|
||||
return getMeaningfulValues([minutes, duration.seconds()], ["m", "s"]);
|
||||
}
|
||||
|
||||
return `${minutes}m`;
|
||||
}
|
||||
|
||||
const hours = Math.floor(duration.asHours());
|
||||
|
||||
if(hours < 8) {
|
||||
const minutes = duration.minutes();
|
||||
|
||||
return getMeaningfulValues([hours, minutes], ["h", "m"], separator);
|
||||
} else if (hours < 48) {
|
||||
if (compact) {
|
||||
return `${hours}h`;
|
||||
} else {
|
||||
return getMeaningfulValues([hours, duration.minutes()], ["h", "m"]);
|
||||
}
|
||||
}
|
||||
|
||||
const days = Math.floor(duration.asDays());
|
||||
|
||||
if (days < 8) {
|
||||
const hours = duration.hours();
|
||||
|
||||
if (compact) {
|
||||
return getMeaningfulValues([days, hours], ["d", "h"], separator);
|
||||
} else {
|
||||
return getMeaningfulValues([days, hours, duration.minutes()], ["d", "h", "m"]);
|
||||
}
|
||||
}
|
||||
const years = Math.floor(duration.asYears());
|
||||
|
||||
if (years < 2) {
|
||||
if (compact) {
|
||||
return `${days}d`;
|
||||
} else {
|
||||
return getMeaningfulValues([days, duration.hours(), duration.minutes()], ["d", "h", "m"]);
|
||||
}
|
||||
} else if (years < 8) {
|
||||
const days = duration.days();
|
||||
|
||||
if (compact) {
|
||||
return getMeaningfulValues([years, days], ["y", "d"], separator);
|
||||
}
|
||||
}
|
||||
|
||||
if (compact) {
|
||||
return `${years}y`;
|
||||
}
|
||||
|
||||
return getMeaningfulValues([years, duration.days(), duration.hours(), duration.minutes()], ["y", "d", "h", "m"]);
|
||||
}
|
||||
|
||||
function getMeaningfulValues(values: number[], suffixes: string[], separator = " ") {
|
||||
return values
|
||||
.map((a, i): [number, string] => [a, suffixes[i]])
|
||||
.filter(([dur]) => dur > 0)
|
||||
.map(([dur, suf]) => dur + suf)
|
||||
.join(separator);
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { HashSet, ObservableHashSet } from "./hash-set";
|
||||
|
||||
describe("ObservableHashSet<T>", () => {
|
||||
it("should not throw on creation", () => {
|
||||
expect(() => new ObservableHashSet<{ a: number }>([], item => item.a.toString())).not.toThrowError();
|
||||
});
|
||||
|
||||
it("should be initialized", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.size).toBe(4);
|
||||
});
|
||||
|
||||
it("has should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
expect(res.has({ a: 5 })).toBe(false);
|
||||
});
|
||||
|
||||
it("forEach should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
let a = 1;
|
||||
|
||||
res.forEach((item) => {
|
||||
expect(item.a).toEqual(a++);
|
||||
});
|
||||
});
|
||||
|
||||
it("delete should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
expect(res.delete({ a: 1 })).toBe(true);
|
||||
expect(res.has({ a: 1 })).toBe(false);
|
||||
|
||||
expect(res.has({ a: 5 })).toBe(false);
|
||||
expect(res.delete({ a: 5 })).toBe(false);
|
||||
expect(res.has({ a: 5 })).toBe(false);
|
||||
});
|
||||
|
||||
it("toggle should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
res.toggle({ a: 1 });
|
||||
expect(res.has({ a: 1 })).toBe(false);
|
||||
|
||||
expect(res.has({ a: 6 })).toBe(false);
|
||||
res.toggle({ a: 6 });
|
||||
expect(res.has({ a: 6 })).toBe(true);
|
||||
});
|
||||
|
||||
it("add should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 6 })).toBe(false);
|
||||
res.add({ a: 6 });
|
||||
expect(res.has({ a: 6 })).toBe(true);
|
||||
});
|
||||
|
||||
it("add should treat the hash to be the same as equality", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1, foobar: "hello" },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
res.add({ a: 1, foobar: "goodbye" });
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
});
|
||||
|
||||
it("clear should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.size).toBe(4);
|
||||
res.clear();
|
||||
expect(res.size).toBe(0);
|
||||
});
|
||||
|
||||
it("replace should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.size).toBe(4);
|
||||
res.replace([{ a: 13 }]);
|
||||
expect(res.size).toBe(1);
|
||||
expect(res.has({ a: 1 })).toBe(false);
|
||||
expect(res.has({ a: 13 })).toBe(true);
|
||||
});
|
||||
|
||||
it("toJSON should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.toJSON()).toStrictEqual([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("values should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
const iter = res.values();
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 1 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 2 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 3 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 4 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: undefined,
|
||||
done: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keys should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
const iter = res.keys();
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 1 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 2 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 3 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 4 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: undefined,
|
||||
done: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("entries should work as expected", () => {
|
||||
const res = new ObservableHashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
const iter = res.entries();
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 1 }, { a: 1 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 2 }, { a: 2 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 3 }, { a: 3 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 4 }, { a: 4 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: undefined,
|
||||
done: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("HashSet<T>", () => {
|
||||
it("should not throw on creation", () => {
|
||||
expect(() => new HashSet<{ a: number }>([], item => item.a.toString())).not.toThrowError();
|
||||
});
|
||||
|
||||
it("should be initialized", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.size).toBe(4);
|
||||
});
|
||||
|
||||
it("has should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
expect(res.has({ a: 5 })).toBe(false);
|
||||
});
|
||||
|
||||
it("forEach should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
let a = 1;
|
||||
|
||||
res.forEach((item) => {
|
||||
expect(item.a).toEqual(a++);
|
||||
});
|
||||
});
|
||||
|
||||
it("delete should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
expect(res.delete({ a: 1 })).toBe(true);
|
||||
expect(res.has({ a: 1 })).toBe(false);
|
||||
|
||||
expect(res.has({ a: 5 })).toBe(false);
|
||||
expect(res.delete({ a: 5 })).toBe(false);
|
||||
expect(res.has({ a: 5 })).toBe(false);
|
||||
});
|
||||
|
||||
it("toggle should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
res.toggle({ a: 1 });
|
||||
expect(res.has({ a: 1 })).toBe(false);
|
||||
|
||||
expect(res.has({ a: 6 })).toBe(false);
|
||||
res.toggle({ a: 6 });
|
||||
expect(res.has({ a: 6 })).toBe(true);
|
||||
});
|
||||
|
||||
it("add should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 6 })).toBe(false);
|
||||
res.add({ a: 6 });
|
||||
expect(res.has({ a: 6 })).toBe(true);
|
||||
});
|
||||
|
||||
it("add should treat the hash to be the same as equality", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1, foobar: "hello" },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
res.add({ a: 1, foobar: "goodbye" });
|
||||
expect(res.has({ a: 1 })).toBe(true);
|
||||
});
|
||||
|
||||
it("clear should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.size).toBe(4);
|
||||
res.clear();
|
||||
expect(res.size).toBe(0);
|
||||
});
|
||||
|
||||
it("replace should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.size).toBe(4);
|
||||
res.replace([{ a: 13 }]);
|
||||
expect(res.size).toBe(1);
|
||||
expect(res.has({ a: 1 })).toBe(false);
|
||||
expect(res.has({ a: 13 })).toBe(true);
|
||||
});
|
||||
|
||||
it("toJSON should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
|
||||
expect(res.toJSON()).toStrictEqual([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("values should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
const iter = res.values();
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 1 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 2 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 3 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 4 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: undefined,
|
||||
done: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keys should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
const iter = res.keys();
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 1 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 2 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 3 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: { a: 4 },
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: undefined,
|
||||
done: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("entries should work as expected", () => {
|
||||
const res = new HashSet([
|
||||
{ a: 1 },
|
||||
{ a: 2 },
|
||||
{ a: 3 },
|
||||
{ a: 4 },
|
||||
], item => item.a.toString());
|
||||
const iter = res.entries();
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 1 }, { a: 1 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 2 }, { a: 2 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 3 }, { a: 3 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: [{ a: 4 }, { a: 4 }],
|
||||
done: false,
|
||||
});
|
||||
|
||||
expect(iter.next()).toStrictEqual({
|
||||
value: undefined,
|
||||
done: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { IInterceptable, IInterceptor, IListenable, ISetWillChange, ObservableMap } from "mobx";
|
||||
import { observable, ObservableSet, runInAction } from "mobx";
|
||||
|
||||
export function makeIterableIterator<T>(iterator: Iterator<T>): IterableIterator<T> {
|
||||
(iterator as IterableIterator<T>)[Symbol.iterator] = () => iterator as IterableIterator<T>;
|
||||
|
||||
return iterator as IterableIterator<T>;
|
||||
}
|
||||
|
||||
export class HashSet<T> implements Set<T> {
|
||||
#hashmap: Map<string, T>;
|
||||
|
||||
constructor(initialValues: Iterable<T>, protected hasher: (item: T) => string) {
|
||||
this.#hashmap = new Map<string, T>(Array.from(initialValues, value => [this.hasher(value), value]));
|
||||
}
|
||||
|
||||
replace(other: ObservableHashSet<T> | ObservableSet<T> | Set<T> | readonly T[]): this {
|
||||
if (other === null || other === undefined) {
|
||||
return this;
|
||||
}
|
||||
|
||||
if (!(Array.isArray(other) || other instanceof Set || other instanceof ObservableHashSet || other instanceof ObservableSet)) {
|
||||
throw new Error(`ObservableHashSet: Cannot initialize set from ${other}`);
|
||||
}
|
||||
|
||||
this.clear();
|
||||
|
||||
for (const value of other) {
|
||||
this.add(value);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.#hashmap.clear();
|
||||
}
|
||||
|
||||
add(value: T): this {
|
||||
this.#hashmap.set(this.hasher(value), value);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toggle(value: T): void {
|
||||
const hash = this.hasher(value);
|
||||
|
||||
if (this.#hashmap.has(hash)) {
|
||||
this.#hashmap.delete(hash);
|
||||
} else {
|
||||
this.#hashmap.set(hash, value);
|
||||
}
|
||||
}
|
||||
|
||||
delete(value: T): boolean {
|
||||
return this.#hashmap.delete(this.hasher(value));
|
||||
}
|
||||
|
||||
forEach(callbackfn: (value: T, key: T, set: Set<T>) => void, thisArg?: any): void {
|
||||
this.#hashmap.forEach(value => callbackfn(value, value, thisArg ?? this));
|
||||
}
|
||||
|
||||
has(value: T): boolean {
|
||||
return this.#hashmap.has(this.hasher(value));
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.#hashmap.size;
|
||||
}
|
||||
|
||||
entries(): IterableIterator<[T, T]> {
|
||||
let nextIndex = 0;
|
||||
const keys = Array.from(this.keys());
|
||||
const values = Array.from(this.values());
|
||||
|
||||
return makeIterableIterator<[T, T]>({
|
||||
next() {
|
||||
const index = nextIndex++;
|
||||
|
||||
return index < values.length
|
||||
? { value: [keys[index], values[index]], done: false }
|
||||
: { done: true, value: undefined };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
keys(): IterableIterator<T> {
|
||||
return this.values();
|
||||
}
|
||||
|
||||
values(): IterableIterator<T> {
|
||||
let nextIndex = 0;
|
||||
const observableValues = Array.from(this.#hashmap.values());
|
||||
|
||||
return makeIterableIterator<T>({
|
||||
next: () => {
|
||||
return nextIndex < observableValues.length
|
||||
? { value: observableValues[nextIndex++], done: false }
|
||||
: { done: true, value: undefined };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
[Symbol.iterator](): IterableIterator<T> {
|
||||
return this.#hashmap.values();
|
||||
}
|
||||
|
||||
get [Symbol.toStringTag](): string {
|
||||
return "Set";
|
||||
}
|
||||
|
||||
toJSON(): T[] {
|
||||
return Array.from(this);
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return "[object Set]";
|
||||
}
|
||||
}
|
||||
|
||||
export class ObservableHashSet<T> implements Set<T>, IInterceptable<ISetWillChange>, IListenable {
|
||||
#hashmap: ObservableMap<string, T>;
|
||||
|
||||
get interceptors_(): IInterceptor<ISetWillChange<T>>[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
get changeListeners_(): Function[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
constructor(initialValues: Iterable<T>, protected hasher: (item: T) => string) {
|
||||
this.#hashmap = observable.map<string, T>(Array.from(initialValues, value => [this.hasher(value), value]), undefined);
|
||||
}
|
||||
|
||||
replace(other: ObservableHashSet<T> | ObservableSet<T> | Set<T> | readonly T[]): this {
|
||||
return runInAction(() => {
|
||||
if (other === null || other === undefined) {
|
||||
return this;
|
||||
}
|
||||
|
||||
if (!(Array.isArray(other) || other instanceof Set || other instanceof ObservableHashSet || other instanceof ObservableSet)) {
|
||||
throw new Error(`ObservableHashSet: Cannot initialize set from ${other}`);
|
||||
}
|
||||
|
||||
this.clear();
|
||||
|
||||
for (const value of other) {
|
||||
this.add(value);
|
||||
}
|
||||
|
||||
return this;
|
||||
});
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.#hashmap.clear();
|
||||
}
|
||||
|
||||
add(value: T): this {
|
||||
this.#hashmap.set(this.hasher(value), value);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
toggle(value: T): void {
|
||||
runInAction(() => {
|
||||
const hash = this.hasher(value);
|
||||
|
||||
if (this.#hashmap.has(hash)) {
|
||||
this.#hashmap.delete(hash);
|
||||
} else {
|
||||
this.#hashmap.set(hash, value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
delete(value: T): boolean {
|
||||
return this.#hashmap.delete(this.hasher(value));
|
||||
}
|
||||
|
||||
forEach(callbackfn: (value: T, key: T, set: Set<T>) => void, thisArg?: any): void {
|
||||
this.#hashmap.forEach(value => callbackfn(value, value, thisArg ?? this));
|
||||
}
|
||||
|
||||
has(value: T): boolean {
|
||||
return this.#hashmap.has(this.hasher(value));
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.#hashmap.size;
|
||||
}
|
||||
|
||||
entries(): IterableIterator<[T, T]> {
|
||||
let nextIndex = 0;
|
||||
const keys = Array.from(this.keys());
|
||||
const values = Array.from(this.values());
|
||||
|
||||
return makeIterableIterator<[T, T]>({
|
||||
next() {
|
||||
const index = nextIndex++;
|
||||
|
||||
return index < values.length
|
||||
? { value: [keys[index], values[index]], done: false }
|
||||
: { done: true, value: undefined };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
keys(): IterableIterator<T> {
|
||||
return this.values();
|
||||
}
|
||||
|
||||
values(): IterableIterator<T> {
|
||||
let nextIndex = 0;
|
||||
const observableValues = Array.from(this.#hashmap.values());
|
||||
|
||||
return makeIterableIterator<T>({
|
||||
next: () => {
|
||||
return nextIndex < observableValues.length
|
||||
? { value: observableValues[nextIndex++], done: false }
|
||||
: { done: true, value: undefined };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
[Symbol.iterator](): IterableIterator<T> {
|
||||
return this.#hashmap.values();
|
||||
}
|
||||
|
||||
get [Symbol.toStringTag](): string {
|
||||
return "Set";
|
||||
}
|
||||
|
||||
toJSON(): T[] {
|
||||
return Array.from(this);
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return "[object ObservableSet]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Helper for working with time updates / data-polling callbacks
|
||||
|
||||
export interface IntervalFn {
|
||||
start(runImmediately?: boolean): void;
|
||||
stop(): void;
|
||||
restart(runImmediately?: boolean): void;
|
||||
readonly isRunning: boolean;
|
||||
}
|
||||
|
||||
export function interval(timeSec = 1, callback: (count: number) => void, autoRun = false): IntervalFn {
|
||||
let count = 0;
|
||||
let timer = -1;
|
||||
let isRunning = false;
|
||||
const intervalManager = {
|
||||
start(runImmediately = false) {
|
||||
if (isRunning) return;
|
||||
const tick = () => callback(++count);
|
||||
|
||||
isRunning = true;
|
||||
timer = window.setInterval(tick, 1000 * timeSec);
|
||||
if (runImmediately) tick();
|
||||
},
|
||||
stop() {
|
||||
count = 0;
|
||||
isRunning = false;
|
||||
clearInterval(timer);
|
||||
},
|
||||
restart(runImmediately = false) {
|
||||
this.stop();
|
||||
this.start(runImmediately);
|
||||
},
|
||||
get isRunning() {
|
||||
return isRunning;
|
||||
},
|
||||
};
|
||||
|
||||
if (autoRun) intervalManager.start();
|
||||
|
||||
return intervalManager;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type React from "react";
|
||||
|
||||
/**
|
||||
* Returns `true` if `node` is a falsy value
|
||||
*/
|
||||
export function isNodeFalsy(node: React.ReactNode): boolean {
|
||||
return !isNodeRenderable(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return `true` if React would render this
|
||||
*/
|
||||
export function isNodeRenderable(node: React.ReactNode): boolean {
|
||||
return Boolean(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first react node provided that is would be rendered by react
|
||||
*/
|
||||
export function foldNodes(...nodes: React.ReactNode[]): React.ReactNode {
|
||||
return nodes.find(isNodeRenderable);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type React from "react";
|
||||
|
||||
// Helper for inlining middleClick checks
|
||||
// <form onAuxClick={isMiddleClick(() => console.log('do some action'))}>
|
||||
// <input name="text"/>
|
||||
// <button type="submit">Action</button>
|
||||
// </form>
|
||||
|
||||
export function isMiddleClick<E extends React.MouseEvent>(callback: (evt: E) => any) {
|
||||
return function (evt: E) {
|
||||
if(evt.button === 1) {
|
||||
return callback(evt);
|
||||
}
|
||||
};
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Type guard for checking valid react node to use in render
|
||||
import type { ReactNode } from "react";
|
||||
import React from "react";
|
||||
import { isObject } from "./type-narrowing";
|
||||
|
||||
export function isReactNode(node: unknown): node is ReactNode {
|
||||
return (isObject(node) && React.isValidElement(node))
|
||||
|| Array.isArray(node) && node.every(isReactNode)
|
||||
|| node == null
|
||||
|| typeof node !== "object";
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { iter } from "./iter";
|
||||
|
||||
describe("iter", () => {
|
||||
describe("reduce", () => {
|
||||
it("can reduce a value", () => {
|
||||
expect(iter.reduce([1, 2, 3], (acc: number[], current: number) => [current, ...acc], [0])).toEqual([3, 2, 1, 0]);
|
||||
});
|
||||
|
||||
it("can reduce an empty iterable", () => {
|
||||
expect(iter.reduce([], (acc: number[], current: number) => [acc[0] + current], [])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("join", () => {
|
||||
it("should not prefix the output by the separator", () => {
|
||||
expect(iter.join(["a", "b", "c"].values(), " ")).toBe("a b c");
|
||||
});
|
||||
|
||||
it("should return empty string if iterator is empty", () => {
|
||||
expect(iter.join([].values(), " ")).toBe("");
|
||||
});
|
||||
|
||||
it("should return just first entry if iterator is of size 1", () => {
|
||||
expect(iter.join(["d"].values(), " ")).toBe("d");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nth", () => {
|
||||
it("should return undefined past the end of the iterator", () => {
|
||||
expect(iter.nth(["a"], 123)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should by 0-indexing the index", () => {
|
||||
expect(iter.nth(["a", "b"], 0)).toBe("a");
|
||||
});
|
||||
});
|
||||
|
||||
describe("concat", () => {
|
||||
it("should yield undefined for empty args", () => {
|
||||
const i = iter.concat();
|
||||
|
||||
expect(i.next()).toEqual({ done: true });
|
||||
});
|
||||
|
||||
it("should yield undefined for only empty args", () => {
|
||||
const i = iter.concat([].values(), [].values(), [].values(), [].values());
|
||||
|
||||
expect(i.next()).toEqual({ done: true });
|
||||
});
|
||||
|
||||
it("should yield all of the first and then all of the second", () => {
|
||||
const i = iter.concat([1, 2, 3].values(), [4, 5, 6].values());
|
||||
|
||||
expect(i.next()).toEqual({ done: false, value: 1 });
|
||||
expect(i.next()).toEqual({ done: false, value: 2 });
|
||||
expect(i.next()).toEqual({ done: false, value: 3 });
|
||||
expect(i.next()).toEqual({ done: false, value: 4 });
|
||||
expect(i.next()).toEqual({ done: false, value: 5 });
|
||||
expect(i.next()).toEqual({ done: false, value: 6 });
|
||||
expect(i.next()).toEqual({ done: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("nFircate", () => {
|
||||
it("should produce an empty array if no parts are provided", () => {
|
||||
expect(iter.nFircate([{ a: 1 }, { a: 2 }], "a", []).length).toBe(0);
|
||||
});
|
||||
|
||||
it("should ignore non-matching parts", () => {
|
||||
const res = iter.nFircate([{ a: 1 }, { a: 2 }], "a", [1]);
|
||||
|
||||
expect(res.length).toBe(1);
|
||||
expect(res[0].length).toBe(1);
|
||||
});
|
||||
|
||||
it("should include all matching parts in each type", () => {
|
||||
const res = iter.nFircate([{ a: 1, b: "a" }, { a: 2, b: "b" }, { a: 1, b: "c" }], "a", [1, 2]);
|
||||
|
||||
expect(res.length).toBe(2);
|
||||
expect(res[0].length).toBe(2);
|
||||
expect(res[0][0].b).toBe("a");
|
||||
expect(res[0][1].b).toBe("c");
|
||||
expect(res[1].length).toBe(1);
|
||||
expect(res[1][0].b).toBe("b");
|
||||
});
|
||||
|
||||
it("should throw a type error if the same part is provided more than once", () => {
|
||||
try {
|
||||
iter.nFircate([{ a: 1, b: "a" }, { a: 2, b: "b" }, { a: 1, b: "c" }], "a", [1, 2, 1]);
|
||||
fail("Expected error");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(TypeError);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
export type Falsy = false | 0 | "" | null | undefined;
|
||||
|
||||
interface Iterator<T> extends Iterable<T> {
|
||||
filter(fn: (val: T) => unknown): Iterator<T>;
|
||||
filterMap<U>(fn: (val: T) => Falsy | U): Iterator<U>;
|
||||
find(fn: (val: T) => unknown): T | undefined;
|
||||
collect<U>(fn: (values: Iterable<T>) => U): U;
|
||||
map<U>(fn: (val: T) => U): Iterator<U>;
|
||||
flatMap<U>(fn: (val: T) => U[]): Iterator<U>;
|
||||
concat(src2: IterableIterator<T>): Iterator<T>;
|
||||
join(sep?: string): string;
|
||||
}
|
||||
|
||||
function chain<T>(src: IterableIterator<T>): Iterator<T> {
|
||||
return {
|
||||
filter: (fn) => chain(filter(src, fn)),
|
||||
filterMap: (fn) => chain(filterMap(src, fn)),
|
||||
map: (fn) => chain(map(src, fn)),
|
||||
flatMap: (fn) => chain(flatMap(src, fn)),
|
||||
find: (fn) => find(src, fn),
|
||||
join: (sep) => join(src, sep),
|
||||
collect: (fn) => fn(src),
|
||||
concat: (src2) => chain(concat(src, src2)),
|
||||
[Symbol.iterator]: () => src,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new type safe empty Iterable
|
||||
* @returns An `Iterable` that yields 0 items
|
||||
*/
|
||||
function* newEmpty<T>(): IterableIterator<T> {}
|
||||
|
||||
/**
|
||||
* Creates a new `Iterable` that yields at most n items from src.
|
||||
* Does not modify `src` which can be used later.
|
||||
* @param src An initial iterator
|
||||
* @param n The maximum number of elements to take from src. Yields up to the floor of `n` and 0 items if n < 0
|
||||
*/
|
||||
function* take<T>(src: Iterable<T>, n: number): IterableIterator<T> {
|
||||
outer: for (let i = 0; i < n; i += 1) {
|
||||
for (const item of src) {
|
||||
yield item;
|
||||
continue outer;
|
||||
}
|
||||
|
||||
// if we are here that means that `src` has been exhausted. Don't bother trying again.
|
||||
break outer;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new iterator that iterates (lazily) over its input and yields the
|
||||
* result of `fn` for each item.
|
||||
* @param src A type that can be iterated over
|
||||
* @param fn The function that is called for each value
|
||||
*/
|
||||
function* map<T, U>(src: Iterable<T>, fn: (from: T) => U): IterableIterator<U> {
|
||||
for (const from of src) {
|
||||
yield fn(from);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The single layer flattening of an iterator, discarding `Falsy` values.
|
||||
* @param src A type that can be iterated over
|
||||
* @param fn The function that returns either an iterable over items that should be filtered out or a `Falsy` value indicating that it should be ignored
|
||||
*/
|
||||
function* filterFlatMap<T, U>(src: Iterable<T>, fn: (from: T) => Iterable<U | Falsy> | Falsy): IterableIterator<U> {
|
||||
for (const from of src) {
|
||||
if (!from) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const mapping = fn(from);
|
||||
|
||||
if (!mapping) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const mapped of mapping) {
|
||||
if (mapped) {
|
||||
yield mapped;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new iterator that yields the items that each call to `fn` would produce
|
||||
* @param src A type that can be iterated over
|
||||
* @param fn A function that returns an iterator
|
||||
*/
|
||||
function* flatMap<T, U>(src: Iterable<T>, fn: (from: T) => Iterable<U>): IterableIterator<U> {
|
||||
for (const from of src) {
|
||||
yield* fn(from);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new iterator that iterates (lazily) over its input and yields the
|
||||
* items that return a `truthy` value from `fn`.
|
||||
* @param src A type that can be iterated over
|
||||
* @param fn The function that is called for each value
|
||||
*/
|
||||
function* filter<T>(src: Iterable<T>, fn: (from: T) => any): IterableIterator<T> {
|
||||
for (const from of src) {
|
||||
if (fn(from)) {
|
||||
yield from;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new iterator that iterates (lazily) over its input and yields the
|
||||
* result of `fn` when it is `truthy`
|
||||
* @param src A type that can be iterated over
|
||||
* @param fn The function that is called for each value
|
||||
*/
|
||||
function* filterMap<T, U>(src: Iterable<T>, fn: (from: T) => U | Falsy): IterableIterator<U> {
|
||||
for (const from of src) {
|
||||
const res = fn(from);
|
||||
|
||||
if (res) {
|
||||
yield res;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new iterator that iterates (lazily) over its input and yields the
|
||||
* result of `fn` when it is not null or undefined
|
||||
* @param src A type that can be iterated over
|
||||
* @param fn The function that is called for each value
|
||||
*/
|
||||
function* filterMapStrict<T, U>(src: Iterable<T>, fn: (from: T) => U | null | undefined): IterableIterator<U> {
|
||||
for (const from of src) {
|
||||
const res = fn(from);
|
||||
|
||||
if (res != null) {
|
||||
yield res;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate through `src` until `match` returns a truthy value
|
||||
* @param src A type that can be iterated over
|
||||
* @param match A function that should return a truthy value for the item that you want to find
|
||||
* @returns The first entry that `match` returns a truthy value for, or `undefined`
|
||||
*/
|
||||
function find<T>(src: Iterable<T>, match: (i: T) => any): T | undefined {
|
||||
for (const from of src) {
|
||||
if (match(from)) {
|
||||
return from;
|
||||
}
|
||||
}
|
||||
|
||||
return void 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over `src` calling `reducer` with the previous produced value and the current
|
||||
* yielded value until `src` is exhausted. Then return the final value.
|
||||
* @param src The value to iterate over
|
||||
* @param reducer A function for producing the next item from an accumulation and the current item
|
||||
* @param initial The initial value for the iteration
|
||||
*/
|
||||
function reduce<T, R extends Iterable<any>>(src: Iterable<T>, reducer: (acc: R, cur: T) => R, initial: R): R;
|
||||
|
||||
function reduce<T, R = T>(src: Iterable<T>, reducer: (acc: R, cur: T) => R, initial: R): R {
|
||||
let acc = initial;
|
||||
|
||||
for (const item of src) {
|
||||
acc = reducer(acc, item);
|
||||
}
|
||||
|
||||
return acc;
|
||||
}
|
||||
|
||||
/**
|
||||
* A convenience function for reducing over an iterator of strings and concatenating them together
|
||||
* @param src The value to iterate over
|
||||
* @param connector The string value to intersperse between the yielded values
|
||||
* @returns The concatenated entries of `src` interspersed with copies of `connector`
|
||||
*/
|
||||
function join(src: IterableIterator<unknown>, connector = ","): string {
|
||||
const iterSrc = src[Symbol.iterator]();
|
||||
const first = iterSrc.next();
|
||||
|
||||
if (first.done === true) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return reduce(iterSrc, (acc, cur) => `${acc}${connector}${cur}`, `${first.value}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate `n` times and then return the next value.
|
||||
* @param src The value to iterate over
|
||||
* @param n The zero-index value for the item to return to.
|
||||
*/
|
||||
function nth<T>(src: Iterable<T>, n: number): T | undefined {
|
||||
const iterator = src[Symbol.iterator]();
|
||||
|
||||
while (n --> 0) {
|
||||
iterator.next();
|
||||
}
|
||||
|
||||
return iterator.next().value;
|
||||
}
|
||||
|
||||
/**
|
||||
* A convenience function to get the first item of an iterator
|
||||
* @param src The value to iterate over
|
||||
*/
|
||||
function first<T>(src: Iterable<T>): T | undefined {
|
||||
return nth(src, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate through `src` and return `true` if `fn` returns a truthy value for every yielded value.
|
||||
* Otherwise, return `false`. This function short circuits.
|
||||
* @param src The type to be iterated over
|
||||
* @param fn A function to check each iteration
|
||||
*/
|
||||
function every<T>(src: Iterable<T>, fn: (val: T) => any): boolean {
|
||||
for (const val of src) {
|
||||
if (!fn(val)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function* concat<T>(...sources: IterableIterator<T>[]): IterableIterator<T> {
|
||||
for (const source of sources) {
|
||||
for (const val of source) {
|
||||
yield val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Split an iterable into several arrays with matching fields
|
||||
* @param from The iterable of items to split up
|
||||
* @param field The field of each item to split over
|
||||
* @param parts What each array will be filtered to
|
||||
* @returns A `parts.length` tuple of `T[]` where each array has matching `field` values
|
||||
*/
|
||||
function nFircate<T>(from: Iterable<T>, field: keyof T, parts: []): [];
|
||||
function nFircate<T>(from: Iterable<T>, field: keyof T, parts: [T[typeof field]]): [T[]];
|
||||
function nFircate<T>(from: Iterable<T>, field: keyof T, parts: [T[typeof field], T[typeof field]]): [T[], T[]];
|
||||
function nFircate<T>(from: Iterable<T>, field: keyof T, parts: [T[typeof field], T[typeof field], T[typeof field]]): [T[], T[], T[]];
|
||||
function nFircate<T>(from: Iterable<T>, field: keyof T, parts: T[typeof field][]): T[][] {
|
||||
if (new Set(parts).size !== parts.length) {
|
||||
throw new TypeError("Duplicate parts entries");
|
||||
}
|
||||
|
||||
const res = Array.from(parts, () => [] as T[]);
|
||||
|
||||
for (const item of from) {
|
||||
const index = parts.indexOf(item[field]);
|
||||
|
||||
if (index < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
res[index].push(item);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
export const iter = {
|
||||
chain,
|
||||
concat,
|
||||
every,
|
||||
filter,
|
||||
filterFlatMap,
|
||||
filterMap,
|
||||
filterMapStrict,
|
||||
find,
|
||||
first,
|
||||
flatMap,
|
||||
join,
|
||||
map,
|
||||
nFircate,
|
||||
newEmpty,
|
||||
nth,
|
||||
reduce,
|
||||
take,
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { Result } from "./result";
|
||||
|
||||
export const json = {
|
||||
parse: (input: string): Result<unknown, Error> => {
|
||||
try {
|
||||
return {
|
||||
callWasSuccessful: true,
|
||||
response: JSON.parse(input) as unknown,
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
callWasSuccessful: false,
|
||||
error: error as Error,
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { convertKubectlJsonPathToNodeJsonPath, safeJSONPathValue } from "./jsonPath";
|
||||
|
||||
describe("convertKubectlJsonPathToNodeJsonPath", () => {
|
||||
it("should convert \\. to use indexed notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels.kubesphere\\.io/alias-name");
|
||||
|
||||
expect(res).toBe("$.metadata.labels['kubesphere.io/alias-name']");
|
||||
});
|
||||
|
||||
it("should convert keys with escaped characters to use indexed notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels.kubesphere\\\"io/alias-name");
|
||||
|
||||
expect(res).toBe("$.metadata.labels['kubesphere\"io/alias-name']");
|
||||
});
|
||||
|
||||
it("should convert '-' to use indexed notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels.alias-name");
|
||||
|
||||
expect(res).toBe("$.metadata.labels['alias-name']");
|
||||
});
|
||||
|
||||
it("should drop leading dot if first group is converted to index notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata\\.labels.alias-name");
|
||||
|
||||
expect(res).toBe("$['metadata.labels']['alias-name']");
|
||||
});
|
||||
|
||||
it("should handle scenario when both \\. and indexed notation are present", () => {
|
||||
const rest = convertKubectlJsonPathToNodeJsonPath(".metadata.labels\\.serving['some.other.item']");
|
||||
|
||||
expect(rest).toBe("$.metadata['labels.serving']['some.other.item']");
|
||||
});
|
||||
|
||||
it("should not touch given jsonPath if no invalid characters present", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".status.conditions[?(@.type=='Ready')].status");
|
||||
|
||||
expect(res).toBe("$.status.conditions[?(@.type=='Ready')].status");
|
||||
});
|
||||
|
||||
it("strips '\\' away from the result", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels['serving\\.knative\\.dev/configuration']");
|
||||
|
||||
expect(res).toBe("$.metadata.labels['serving.knative.dev/configuration']");
|
||||
});
|
||||
|
||||
it("converts all [] to [0]", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels[].foo[]");
|
||||
|
||||
expect(res).toBe("$.metadata.labels[0].foo[0]");
|
||||
});
|
||||
|
||||
it("removes trailing ..", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels[]..");
|
||||
|
||||
expect(res).toBe("$.metadata.labels[0]");
|
||||
});
|
||||
|
||||
it("converts ending ...name to ..name", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels[]...name");
|
||||
|
||||
expect(res).toBe("$.metadata.labels[0]..name");
|
||||
});
|
||||
});
|
||||
|
||||
describe("safeJSONPathValue", () => {
|
||||
let oldWarn: typeof console["warn"];
|
||||
|
||||
beforeEach(() => {
|
||||
oldWarn = console.warn;
|
||||
console.warn = jest.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.warn = oldWarn;
|
||||
});
|
||||
|
||||
it("should convert boolean values to strings", () => {
|
||||
const res = safeJSONPathValue({ bar: false }, ".bar");
|
||||
|
||||
expect(res).toBe(false);
|
||||
});
|
||||
|
||||
it("should convert number values to strings", () => {
|
||||
const res = safeJSONPathValue({ bar: 0 }, ".bar");
|
||||
|
||||
expect(res).toBe(0);
|
||||
});
|
||||
|
||||
it("should join sliced entries with commas only", () => {
|
||||
const res = safeJSONPathValue({
|
||||
bar: [
|
||||
{
|
||||
foo: 1,
|
||||
},
|
||||
{
|
||||
foo: "hello",
|
||||
},
|
||||
],
|
||||
}, ".bar[].foo");
|
||||
|
||||
expect(res).toBe(1);
|
||||
});
|
||||
|
||||
it("should join an array of values using JSON.stringify", () => {
|
||||
const res = safeJSONPathValue({
|
||||
bar: [
|
||||
"world",
|
||||
"hello",
|
||||
],
|
||||
}, ".bar");
|
||||
|
||||
expect(res).toEqual(["world", "hello"]);
|
||||
});
|
||||
|
||||
it("should stringify an object value", () => {
|
||||
const res = safeJSONPathValue({
|
||||
foo: { bar: "bat" },
|
||||
}, ".foo");
|
||||
|
||||
expect(res).toEqual({ "bar":"bat" });
|
||||
});
|
||||
|
||||
it("should use convertKubectlJsonPathToNodeJsonPath", () => {
|
||||
const res = safeJSONPathValue({
|
||||
foo: { "hello.world": "bat" },
|
||||
}, ".foo.hello\\.world");
|
||||
|
||||
expect(res).toBe("bat");
|
||||
});
|
||||
|
||||
it("should not throw when given '.spec.metrics[*].external.highWatermark..'", () => {
|
||||
const obj = {
|
||||
spec: {
|
||||
metrics: [
|
||||
{
|
||||
external: {
|
||||
metricName: "cpu",
|
||||
highWatermark: "100",
|
||||
},
|
||||
},
|
||||
{
|
||||
external: {
|
||||
metricName: "memory",
|
||||
highWatermark: "100",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const res = safeJSONPathValue(obj, ".spec.metrics[*].external.highWatermark..");
|
||||
|
||||
expect(res).toEqual(["100", "100"]);
|
||||
});
|
||||
|
||||
it("should not throw if path is invalid jsonpath", () => {
|
||||
const res = safeJSONPathValue({
|
||||
foo: { "hello.world": "bat" },
|
||||
}, "asd[");
|
||||
|
||||
expect(res).toBe(undefined);
|
||||
});
|
||||
|
||||
it("should retrive value with '/' in jsonpath", () => {
|
||||
const res = safeJSONPathValue({
|
||||
foo: {
|
||||
"hello/world": "bat",
|
||||
},
|
||||
}, ".foo.hello/world");
|
||||
|
||||
expect(res).toBe("bat");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { JSONPath } from "@astronautlabs/jsonpath";
|
||||
import { TypedRegEx } from "typed-regex";
|
||||
|
||||
const slashDashSearch = /[/\\-]/g;
|
||||
const pathByBareDots = /(?<=\w)\./;
|
||||
const textBeforeFirstSquare = /^.*(?=\[)/g;
|
||||
const backSlash = /\\/g;
|
||||
const kubectlOptionPrefix = TypedRegEx("^\\$?\\.?(?<pathExpression>.*)");
|
||||
const sliceVersion = /\[]/g;
|
||||
const tripleDotName = /\.\.\.(?<trailing>.)/g;
|
||||
const trailingDotDot = /\.\.$/;
|
||||
|
||||
/**
|
||||
* The GO package that kubectl and kubernetes uses for its JSONpath implementation has some
|
||||
* shorthand conveniences that are not part of the official spec. This function tries to convert
|
||||
* those shorthands to the official spec.
|
||||
*
|
||||
* Known shorthands:
|
||||
* - Leading `$` is optional (but implied)
|
||||
* - The string `/` can be used without a leading `\` escapement
|
||||
* - The string `\.` is used to denote the "value of '.'" and not "next key"
|
||||
* - The string `-` can be used while not in quotes
|
||||
* - `[]` as shorthand for `[0]`
|
||||
* - Remove `..` at the end of a path, we will just format it slightly differently
|
||||
* - Allow `...foo` as well as `..foo`
|
||||
*/
|
||||
export function convertKubectlJsonPathToNodeJsonPath(jsonPath: string) {
|
||||
const captures = kubectlOptionPrefix.captures(jsonPath);
|
||||
let start = "$";
|
||||
|
||||
if (!captures) {
|
||||
return start;
|
||||
}
|
||||
|
||||
let { pathExpression } = captures;
|
||||
|
||||
if (pathExpression.match(slashDashSearch)) {
|
||||
const [first, ...rest] = pathExpression.split(pathByBareDots);
|
||||
|
||||
pathExpression = `${convertToIndexNotation(first, true)}${rest.map(value => convertToIndexNotation(value)).join("")}`;
|
||||
}
|
||||
|
||||
pathExpression = pathExpression.replace(trailingDotDot, "");
|
||||
pathExpression = pathExpression.replace(tripleDotName, "..$<trailing>");
|
||||
|
||||
if (!pathExpression.startsWith("[")) {
|
||||
start += ".";
|
||||
}
|
||||
|
||||
// strip '\' characters from the result
|
||||
return `${start}${pathExpression.replace(backSlash, "").replace(sliceVersion, "[0]")}`;
|
||||
}
|
||||
|
||||
function convertToIndexNotation(key: string, firstItem = false) {
|
||||
if (key.match(slashDashSearch)) {
|
||||
if (key.includes("[")) { // handle cases where key contains [...]
|
||||
const keyToConvert = key.match(textBeforeFirstSquare); // get the text from the key before '['
|
||||
|
||||
if (keyToConvert && keyToConvert[0].match(slashDashSearch)) { // check if that part contains illegal characters
|
||||
return key.replace(keyToConvert[0], `['${keyToConvert[0]}']`); // surround key with '[' and ']'
|
||||
} else {
|
||||
return `.${key}`; // otherwise return as is with leading '.'
|
||||
}
|
||||
}
|
||||
|
||||
return `['${key}']`;
|
||||
} else { // no illegal characters found, do not touch
|
||||
const prefix = firstItem ? "" : ".";
|
||||
|
||||
return `${prefix}${key}`;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatJSONValue(value: unknown): string {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(formatJSONValue).join(", ");
|
||||
}
|
||||
|
||||
if (typeof value === "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* This function is a safer version of `JSONPath.value(obj, path)` with untrusted jsonpath strings
|
||||
*
|
||||
* This function will also stringify the value retreived from the object
|
||||
*/
|
||||
export function safeJSONPathValue(obj: object, path: string): unknown {
|
||||
try {
|
||||
const parsedPath = JSONPath.parse(convertKubectlJsonPathToNodeJsonPath(path));
|
||||
const isSlice = parsedPath.some((exp: any) => exp.expression.type === "slice" || exp.expression.type === "wildcard");
|
||||
const value = JSONPath.query(obj, JSONPath.stringify(parsedPath), isSlice ? Infinity : 1);
|
||||
|
||||
if (isSlice) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return value[0];
|
||||
} catch (error) {
|
||||
// something failed
|
||||
console.warn("[JSON-PATH]: failed to parse jsonpath", error);
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { metricUnitsToNumber } from "./metricUnitsToNumber";
|
||||
|
||||
describe("metricUnitsToNumber tests", () => {
|
||||
test("plain number", () => {
|
||||
expect(metricUnitsToNumber("124")).toStrictEqual(124);
|
||||
});
|
||||
|
||||
test("with k suffix", () => {
|
||||
expect(metricUnitsToNumber("124k")).toStrictEqual(124000);
|
||||
});
|
||||
|
||||
test("with m suffix", () => {
|
||||
expect(metricUnitsToNumber("124m")).toStrictEqual(124000000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
const base = 1000;
|
||||
const suffixes = ["k", "m", "g", "t", "q"];
|
||||
|
||||
export function metricUnitsToNumber(value: string): number {
|
||||
const suffix = value.toLowerCase().slice(-1);
|
||||
const index = suffixes.indexOf(suffix);
|
||||
|
||||
return parseInt(
|
||||
(parseFloat(value) * Math.pow(base, index + 1)).toFixed(1),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Split `name` into the parts seperated by one or more of (-, _, or .) and
|
||||
* the sections can be converted to numbers will be converted
|
||||
* @param name A kube object name
|
||||
* @returns The converted parts of the name
|
||||
*/
|
||||
export function getConvertedParts(name: string): (string | number)[] {
|
||||
return name
|
||||
.split(/[-_./\\]+/)
|
||||
.map(part => {
|
||||
const converted = +part;
|
||||
|
||||
return isNaN(converted) ? part : converted;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A function that does nothing
|
||||
*/
|
||||
export function noop<T extends any[]>(...args: T): void {
|
||||
return void args;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A better typed version of `Object.fromEntries` where the keys are known to
|
||||
* be a specific subset
|
||||
*/
|
||||
function fromEntries<T, Key extends string>(entries: Iterable<readonly [Key, T]>): Record<Key, T> {
|
||||
return Object.fromEntries(entries) as Record<Key, T>;
|
||||
}
|
||||
|
||||
function keys<K extends keyof any>(obj: Partial<Record<K, any>>): K[];
|
||||
function keys<K extends keyof any>(obj: Record<K, any>): K[] {
|
||||
return Object.keys(obj) as K[];
|
||||
}
|
||||
|
||||
function entries<K extends string, V>(obj: Partial<Record<K, V>> | null | undefined): [K, V][];
|
||||
function entries<K extends string | number | symbol, V>(obj: Partial<Record<K, V>> | null | undefined): [K, V][];
|
||||
function entries<K extends string | number | symbol, V>(obj: Record<K, V> | null | undefined): [K, V][];
|
||||
function entries<K extends string | number | symbol, V>(obj: Record<K, V> | null | undefined): [K, V][] {
|
||||
if (obj && typeof obj == "object") {
|
||||
return Object.entries(obj) as never;
|
||||
}
|
||||
|
||||
return [] as never;
|
||||
}
|
||||
|
||||
export const object = {
|
||||
entries,
|
||||
fromEntries,
|
||||
keys,
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { ObservableCrate } from "./observable-crate";
|
||||
import { observableCrate } from "./observable-crate";
|
||||
|
||||
describe("observable-crate", () => {
|
||||
it("can be constructed with initial value", () => {
|
||||
expect(() => observableCrate(0)).not.toThrow();
|
||||
});
|
||||
|
||||
it("has a definite type if the initial value is provided", () => {
|
||||
expect (() => {
|
||||
const res: ObservableCrate<number> = observableCrate(0);
|
||||
|
||||
void res;
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it("accepts an array of transitionHandlers", () => {
|
||||
expect(() => observableCrate(0, [])).not.toThrow();
|
||||
});
|
||||
|
||||
describe("with a crate over an enum, and some transition handlers", () => {
|
||||
enum Test {
|
||||
Start,
|
||||
T1,
|
||||
End,
|
||||
}
|
||||
|
||||
let crate: ObservableCrate<Test>;
|
||||
let correctHandler: jest.MockedFunction<() => void>;
|
||||
let incorrectHandler: jest.MockedFunction<() => void>;
|
||||
|
||||
beforeEach(() => {
|
||||
correctHandler = jest.fn();
|
||||
incorrectHandler = jest.fn();
|
||||
crate = observableCrate(Test.Start, [
|
||||
{
|
||||
from: Test.Start,
|
||||
to: Test.Start,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
{
|
||||
from: Test.Start,
|
||||
to: Test.T1,
|
||||
onTransition: correctHandler,
|
||||
},
|
||||
{
|
||||
from: Test.Start,
|
||||
to: Test.End,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
{
|
||||
from: Test.T1,
|
||||
to: Test.Start,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
{
|
||||
from: Test.T1,
|
||||
to: Test.T1,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
{
|
||||
from: Test.T1,
|
||||
to: Test.End,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
{
|
||||
from: Test.End,
|
||||
to: Test.Start,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
{
|
||||
from: Test.End,
|
||||
to: Test.T1,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
{
|
||||
from: Test.End,
|
||||
to: Test.End,
|
||||
onTransition: incorrectHandler,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("initial value is available", () => {
|
||||
expect(crate.get()).toBe(Test.Start);
|
||||
});
|
||||
|
||||
it("does not call any transition handler", () => {
|
||||
expect(correctHandler).not.toBeCalled();
|
||||
expect(incorrectHandler).not.toBeCalled();
|
||||
});
|
||||
|
||||
describe("when setting a new value", () => {
|
||||
beforeEach(() => {
|
||||
crate.set(Test.T1);
|
||||
});
|
||||
|
||||
it("calls the associated transition handler", () => {
|
||||
expect(correctHandler).toBeCalled();
|
||||
});
|
||||
|
||||
it("does not call any other transition handler", () => {
|
||||
expect(incorrectHandler).not.toBeCalled();
|
||||
});
|
||||
|
||||
it("new value is available", () => {
|
||||
expect(crate.get()).toBe(Test.T1);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { observable, runInAction } from "mobx";
|
||||
import { getOrInsertMap } from "./collection-functions";
|
||||
import { noop } from "./noop";
|
||||
|
||||
export interface ObservableCrate<T> {
|
||||
get(): T;
|
||||
set(value: T): void;
|
||||
}
|
||||
|
||||
export interface ObservableCrateFactory {
|
||||
<T>(initialValue: T, transitionHandlers?: ObservableCrateTransitionHandlers<T>): ObservableCrate<T>;
|
||||
}
|
||||
|
||||
export interface ObservableCrateTransitionHandler<T> {
|
||||
from: T;
|
||||
to: T;
|
||||
onTransition: () => void;
|
||||
}
|
||||
export type ObservableCrateTransitionHandlers<T> = ObservableCrateTransitionHandler<T>[];
|
||||
|
||||
function convertToHandlersMap<T>(handlers: ObservableCrateTransitionHandlers<T>): Map<T, Map<T, () => void>> {
|
||||
const res: ReturnType<typeof convertToHandlersMap<T>> = new Map();
|
||||
|
||||
for (const { from, to, onTransition } of handlers) {
|
||||
getOrInsertMap(res, from).set(to, onTransition);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
export const observableCrate = ((initialValue, transitionHandlers = []) => {
|
||||
const crate = observable.box(initialValue);
|
||||
const handlers = convertToHandlersMap(transitionHandlers);
|
||||
|
||||
return {
|
||||
get() {
|
||||
return crate.get();
|
||||
},
|
||||
set(value) {
|
||||
const onTransition = handlers.get(crate.get())?.get(value) ?? noop;
|
||||
|
||||
runInAction(() => {
|
||||
crate.set(value);
|
||||
onTransition();
|
||||
});
|
||||
},
|
||||
};
|
||||
}) as ObservableCrateFactory;
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
function parseKeyDownDescriptor(descriptor: string): (event: KeyboardEvent) => boolean {
|
||||
const parts = new Set((
|
||||
descriptor
|
||||
.split("+")
|
||||
.filter(Boolean)
|
||||
.map(part => part.toLowerCase())
|
||||
));
|
||||
|
||||
if (parts.size === 0) {
|
||||
return () => true;
|
||||
}
|
||||
|
||||
const hasShift = parts.delete("shift");
|
||||
const hasAlt = parts.delete("alt");
|
||||
|
||||
const rawHasCtrl = parts.delete("ctrl");
|
||||
const rawHasControl = parts.delete("control");
|
||||
const hasCtrl = rawHasCtrl || rawHasControl;
|
||||
|
||||
const rawHasMeta = parts.delete("meta");
|
||||
const rawHasCmd = parts.delete("cmd");
|
||||
const hasMeta = rawHasCmd || rawHasMeta; // This means either matches
|
||||
|
||||
const [key, ...rest] = [...parts];
|
||||
|
||||
if (rest.length !== 0) {
|
||||
throw new Error("only single key combinations are currently supported");
|
||||
}
|
||||
|
||||
return (event) => {
|
||||
return event.altKey === hasAlt
|
||||
&& event.shiftKey === hasShift
|
||||
&& event.ctrlKey === hasCtrl
|
||||
&& event.metaKey === hasMeta
|
||||
&& event.key.toLowerCase() === key.toLowerCase();
|
||||
};
|
||||
}
|
||||
|
||||
export function onKeyboardShortcut(descriptor: string, action: () => void): (this: Window, ev: WindowEventMap["keydown"]) => any {
|
||||
const isMatchingEvent = parseKeyDownDescriptor(descriptor);
|
||||
|
||||
return (event) => {
|
||||
if (isMatchingEvent(event)) {
|
||||
action();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type React from "react";
|
||||
|
||||
// Helper for preventing default event action and performing custom callback
|
||||
// 1)
|
||||
// <form onSubmit={prevDefault(() => console.log('do some action'))}>
|
||||
// <input name="text"/>
|
||||
// <button type="submit">Action</button>
|
||||
// </form>
|
||||
// 2)
|
||||
// <a href="/some-page-url">
|
||||
// <span>Link text</span>
|
||||
// <Icon onClick={prevDefault(() => console.log('stay on the page and open dialog'))}/>
|
||||
// </a>
|
||||
|
||||
export function prevDefault<E extends React.SyntheticEvent | Event, R>(callback: (evt: E) => R): (event: E) => R {
|
||||
return function (evt: E) {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
|
||||
return callback(evt);
|
||||
};
|
||||
}
|
||||
|
||||
export function stopPropagation(evt: Event | React.SyntheticEvent) {
|
||||
evt.stopPropagation();
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { Readable } from "readable-stream";
|
||||
import type { TypedArray } from "type-fest";
|
||||
|
||||
/**
|
||||
* ReadableWebToNodeStream
|
||||
*
|
||||
* Copied from https://github.com/Borewit/readable-web-to-node-stream
|
||||
*
|
||||
* Adds read error handler
|
||||
*
|
||||
* */
|
||||
export class ReadableWebToNodeStream<T extends TypedArray> extends Readable {
|
||||
|
||||
public bytesRead = 0;
|
||||
public released = false;
|
||||
|
||||
/**
|
||||
* Default web API stream reader
|
||||
* https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader
|
||||
*/
|
||||
private reader: ReadableStreamDefaultReader<T>;
|
||||
private pendingRead?: Promise<ReadableStreamReadResult<T>>;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param stream ReadableStream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
|
||||
*/
|
||||
constructor(stream: ReadableStream<T>) {
|
||||
super();
|
||||
this.reader = stream.getReader();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implementation of readable._read(size).
|
||||
* When readable._read() is called, if data is available from the resource,
|
||||
* the implementation should begin pushing that data into the read queue
|
||||
* https://nodejs.org/api/stream.html#stream_readable_read_size_1
|
||||
*/
|
||||
public async _read() {
|
||||
// Should start pushing data into the queue
|
||||
// Read data from the underlying Web-API-readable-stream
|
||||
if (this.released) {
|
||||
this.push(null); // Signal EOF
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.pendingRead = this.reader.read();
|
||||
const data = await this.pendingRead;
|
||||
|
||||
// clear the promise before pushing pushing new data to the queue and allow sequential calls to _read()
|
||||
delete this.pendingRead;
|
||||
|
||||
if (data.done || this.released) {
|
||||
this.push(null); // Signal EOF
|
||||
} else {
|
||||
this.bytesRead += data.value.length;
|
||||
this.push(data.value); // Push new data to the queue
|
||||
}
|
||||
} catch (error) {
|
||||
this.push(null); // Signal EOF
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If there is no unresolved read call to Web-API ReadableStream immediately returns;
|
||||
* otherwise will wait until the read is resolved.
|
||||
*/
|
||||
public async waitForReadToComplete() {
|
||||
if (this.pendingRead) {
|
||||
await this.pendingRead;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close wrapper
|
||||
*/
|
||||
public async close(): Promise<void> {
|
||||
await this.syncAndRelease();
|
||||
}
|
||||
|
||||
private async syncAndRelease() {
|
||||
this.released = true;
|
||||
await this.waitForReadToComplete();
|
||||
await this.reader.releaseLock();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { ReadonlyDeep } from "type-fest";
|
||||
|
||||
export function readonly<T>(src: T): ReadonlyDeep<T> {
|
||||
return src as ReadonlyDeep<T>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { AbortSignal } from "abort-controller";
|
||||
|
||||
/**
|
||||
* Creates a new promise that will be rejected when the signal rejects.
|
||||
*
|
||||
* Useful for `Promise.race()` applications.
|
||||
* @param signal The AbortController's signal to reject with
|
||||
*/
|
||||
export function rejectPromiseBy(signal: AbortSignal): Promise<never> {
|
||||
return new Promise((_, reject) => {
|
||||
signal.addEventListener("abort", reject);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A helper type for async functions that return a `Result`
|
||||
*/
|
||||
export type AsyncResult<Response, Error = string> = Promise<Result<Response, Error>>;
|
||||
|
||||
/**
|
||||
* Result describes the "error is just more data" pattern instead of using exceptions for
|
||||
* normal execution
|
||||
*/
|
||||
export type Result<Response, Error = string> =
|
||||
| (
|
||||
Response extends void
|
||||
? { callWasSuccessful: true; response?: undefined }
|
||||
: { callWasSuccessful: true; response: Response }
|
||||
)
|
||||
| { callWasSuccessful: false; error: Error };
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import semver, { coerce } from "semver";
|
||||
|
||||
export enum Ordering {
|
||||
LESS = -1,
|
||||
EQUAL = 0,
|
||||
GREATER = 1,
|
||||
}
|
||||
|
||||
/**
|
||||
* This function switches the direction of `ordering` if `direction` is `"desc"`
|
||||
* @param ordering The original ordering (assumed to be an "asc" ordering)
|
||||
* @param direction The new desired direction
|
||||
*/
|
||||
export function rectifyOrdering(ordering: Ordering, direction: "asc" | "desc"): Ordering {
|
||||
if (direction === "desc") {
|
||||
return -ordering;
|
||||
}
|
||||
|
||||
return ordering;
|
||||
}
|
||||
|
||||
/**
|
||||
* An ascending sorting function
|
||||
* @param left An item from an array
|
||||
* @param right An item from an array
|
||||
* @returns The relative ordering in an ascending manner.
|
||||
* - Less if left < right
|
||||
* - Equal if left == right
|
||||
* - Greater if left > right
|
||||
*/
|
||||
export function sortCompare<T>(left: T, right: T): Ordering {
|
||||
if (left < right) {
|
||||
return Ordering.LESS;
|
||||
}
|
||||
|
||||
if (left === right) {
|
||||
return Ordering.EQUAL;
|
||||
}
|
||||
|
||||
return Ordering.GREATER;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function sorts of list of items that have what should be a semver version formatted string
|
||||
* as the field `version` but if it is not loosely coercible to semver falls back to sorting them
|
||||
* alphanumerically
|
||||
*/
|
||||
export function sortBySemverVersion<T extends { version: string }>(versioned: T[]): T[] {
|
||||
return versioned
|
||||
.map(versioned => ({
|
||||
__version: coerce(versioned.version, { loose: true }),
|
||||
raw: versioned,
|
||||
}))
|
||||
.sort((left, right) => {
|
||||
if (left.__version && right.__version) {
|
||||
return semver.compare(right.__version, left.__version);
|
||||
}
|
||||
|
||||
if (!left.__version && right.__version) {
|
||||
return Ordering.GREATER;
|
||||
}
|
||||
|
||||
if (left.__version && !right.__version) {
|
||||
return Ordering.LESS;
|
||||
}
|
||||
|
||||
return sortCompare(left.raw.version, right.raw.version);
|
||||
})
|
||||
.map(({ raw }) => raw);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get an ordering function based on the function getter
|
||||
*/
|
||||
export function byValue<T>(getOrderValue: (src: T) => number): (left: T, right: T) => number {
|
||||
return (left, right) => {
|
||||
const leftValue = getOrderValue(left);
|
||||
const rightValue = getOrderValue(right);
|
||||
|
||||
return leftValue - rightValue;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { bifurcateArray, splitArray } from "../splitArray";
|
||||
|
||||
describe("split array on element tests", () => {
|
||||
it("empty array", () => {
|
||||
expect(splitArray([], 10)).toStrictEqual([[], [], false]);
|
||||
});
|
||||
|
||||
it("one element, not in array", () => {
|
||||
expect(splitArray([1], 10)).toStrictEqual([[1], [], false]);
|
||||
});
|
||||
|
||||
it("ten elements, not in array", () => {
|
||||
expect(splitArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 10)).toStrictEqual([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [], false]);
|
||||
});
|
||||
|
||||
it("one elements, in array", () => {
|
||||
expect(splitArray([1], 1)).toStrictEqual([[], [], true]);
|
||||
});
|
||||
|
||||
it("ten elements, in front array", () => {
|
||||
expect(splitArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 0)).toStrictEqual([[], [1, 2, 3, 4, 5, 6, 7, 8, 9], true]);
|
||||
});
|
||||
|
||||
it("ten elements, in middle array", () => {
|
||||
expect(splitArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 4)).toStrictEqual([[0, 1, 2, 3], [5, 6, 7, 8, 9], true]);
|
||||
});
|
||||
|
||||
it("ten elements, in end array", () => {
|
||||
expect(splitArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)).toStrictEqual([[0, 1, 2, 3, 4, 5, 6, 7, 8], [], true]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bifurcateArray", () => {
|
||||
it("should return tuple of empty arrays from empty array", () => {
|
||||
const [left, right] = bifurcateArray([], () => true);
|
||||
|
||||
expect(left).toStrictEqual([]);
|
||||
expect(right).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it("should return all true condition returning items in the right array", () => {
|
||||
const [left, right] = bifurcateArray([1, 2, 3], () => true);
|
||||
|
||||
expect(left).toStrictEqual([]);
|
||||
expect(right).toStrictEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("should return all false condition returning items in the right array", () => {
|
||||
const [left, right] = bifurcateArray([1, 2, 3], () => false);
|
||||
|
||||
expect(left).toStrictEqual([1, 2, 3]);
|
||||
expect(right).toStrictEqual([]);
|
||||
});
|
||||
|
||||
it("should split array as specified", () => {
|
||||
const [left, right] = bifurcateArray([1, 2, 3], (i) => Boolean(i % 2));
|
||||
|
||||
expect(left).toStrictEqual([2]);
|
||||
expect(right).toStrictEqual([1, 3]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Helper for working with tarball files (.tar, .tgz)
|
||||
// Docs: https://github.com/npm/node-tar
|
||||
import tar from "tar";
|
||||
import path from "path";
|
||||
import type { JsonValue } from "type-fest";
|
||||
|
||||
export type ReadFileFromTarOpts<ParseJson extends boolean> = {
|
||||
tarPath: string;
|
||||
filePath: string;
|
||||
} & (
|
||||
ParseJson extends true
|
||||
? {
|
||||
parseJson: true;
|
||||
}
|
||||
: {
|
||||
parseJson?: false;
|
||||
}
|
||||
);
|
||||
|
||||
export function readFileFromTar(opts: ReadFileFromTarOpts<false>): Promise<Buffer>;
|
||||
export function readFileFromTar(opts: ReadFileFromTarOpts<true>): Promise<JsonValue>;
|
||||
|
||||
export function readFileFromTar<ParseJson extends boolean>({ tarPath, filePath, parseJson = false }: ReadFileFromTarOpts<ParseJson>): Promise<JsonValue | Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fileChunks: Buffer[] = [];
|
||||
|
||||
tar.list({
|
||||
file: tarPath,
|
||||
filter: entryPath => path.normalize(entryPath) === filePath,
|
||||
sync: true,
|
||||
onentry(entry) {
|
||||
entry.on("data", chunk => {
|
||||
fileChunks.push(chunk);
|
||||
});
|
||||
entry.once("error", err => {
|
||||
reject(new Error(`reading file has failed ${entry.path}: ${err}`));
|
||||
});
|
||||
entry.once("end", () => {
|
||||
const data = Buffer.concat(fileChunks);
|
||||
const result = parseJson ? JSON.parse(data.toString("utf8")) : data;
|
||||
|
||||
resolve(result);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
if (!fileChunks.length) {
|
||||
reject(new Error("Not found"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function listTarEntries(filePath: string): Promise<string[]> {
|
||||
const entries: string[] = [];
|
||||
|
||||
await tar.list({
|
||||
file: filePath,
|
||||
onentry: (entry) => {
|
||||
entries.push(path.normalize(entry.path));
|
||||
},
|
||||
});
|
||||
|
||||
return entries;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { tuple } from "./tuple";
|
||||
|
||||
describe("tuple tests", () => {
|
||||
describe("zip()", () => {
|
||||
it("should yield 0 times and return 1 tuple of empty arrays when given empty array", () => {
|
||||
expect(tuple.zip([]).next()).toEqual({
|
||||
done: true,
|
||||
value: [[]],
|
||||
});
|
||||
});
|
||||
|
||||
it("should yield 1 times and return 2 tuple of empty arrays when given one element array tuples", () => {
|
||||
const i = tuple.zip([1], [2]);
|
||||
|
||||
expect(i.next()).toEqual({
|
||||
done: false,
|
||||
value: [1, 2],
|
||||
});
|
||||
expect(i.next()).toEqual({
|
||||
done: true,
|
||||
value: [[], []],
|
||||
});
|
||||
});
|
||||
|
||||
it("should yield 1 times and return 2 tuple of partial arrays when given one element array tuples", () => {
|
||||
const i = tuple.zip([1], [2, 3]);
|
||||
|
||||
expect(i.next()).toEqual({
|
||||
done: false,
|
||||
value: [1, 2],
|
||||
});
|
||||
expect(i.next()).toEqual({
|
||||
done: true,
|
||||
value: [[], [3]],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { array } from "./array";
|
||||
|
||||
/**
|
||||
* A strict N-tuple of type T
|
||||
*/
|
||||
export type Tuple<T, N extends number> = N extends N
|
||||
? number extends N
|
||||
? T[]
|
||||
: TupleOfImpl<T, N, []>
|
||||
: never;
|
||||
type TupleOfImpl<T, N extends number, R extends unknown[]> = R["length"] extends N
|
||||
? R
|
||||
: TupleOfImpl<T, N, [T, ...R]>;
|
||||
|
||||
/**
|
||||
* Iterates over `sources` yielding full tuples until one of the tuple arrays
|
||||
* is empty. Then it returns a tuple with the rest of each of tuples
|
||||
* @param sources The source arrays
|
||||
* @yields A tuple of the next element from each of the sources
|
||||
* @returns The tuple of all the sources as soon as at least one of the sources is exausted
|
||||
*/
|
||||
function zip<T>(...sources: Tuple<T[], 0>): Iterator<Tuple<T, 0>, Tuple<T[], 0>>;
|
||||
function zip<T>(...sources: Tuple<T[], 1>): Iterator<Tuple<T, 1>, Tuple<T[], 1>>;
|
||||
function zip<T>(...sources: Tuple<T[], 2>): Iterator<Tuple<T, 2>, Tuple<T[], 2>>;
|
||||
function* zip<T, N extends number>(...sources: Tuple<T[], N>): Iterator<Tuple<T, N>, Tuple<T[], N>> {
|
||||
const maxSafeLength = Math.min(...sources.map(source => source.length));
|
||||
|
||||
for (let i = 0; i < maxSafeLength; i += 1) {
|
||||
yield sources.map(source => source[i]) as Tuple<T, N>;
|
||||
}
|
||||
|
||||
return sources.map(source => source.slice(maxSafeLength)) as Tuple<T[], N>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a `length` tuple filled with copies of `value`
|
||||
* @param length The size of the tuple
|
||||
* @param value The value for each of the tuple entries
|
||||
*/
|
||||
function filled<T, L extends number>(length: L, value: T): Tuple<T, L> {
|
||||
return array.filled(length, value) as Tuple<T, L>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A function for converting an explicit array to a tuple but without the `readonly` typing
|
||||
*/
|
||||
function from<T extends any[]>(...args: T): [...T] {
|
||||
return args;
|
||||
}
|
||||
|
||||
export const tuple = {
|
||||
zip,
|
||||
filled,
|
||||
from,
|
||||
};
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { ExecException, ExecFileException } from "child_process";
|
||||
import type { IncomingMessage } from "http";
|
||||
|
||||
/**
|
||||
* Narrows `val` to include the property `key` (if true is returned)
|
||||
* @param val The object to be tested
|
||||
* @param key The key to test if it is present on the object (must be a literal for tsc to do any meaningful typing)
|
||||
*/
|
||||
export function hasOwnProperty<S extends object, K extends PropertyKey>(val: S, key: K): val is (S & { [key in K]: unknown }) {
|
||||
// this call syntax is for when `val` was created by `Object.create(null)`
|
||||
return Object.prototype.hasOwnProperty.call(val, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows `val` to a static type that includes fields of names in `keys`
|
||||
* @param val the value that we are trying to type narrow
|
||||
* @param keys the key names (must be literals for tsc to do any meaningful typing)
|
||||
*/
|
||||
export function hasOwnProperties<S extends object, K extends PropertyKey>(val: S, ...keys: K[]): val is (S & { [key in K]: unknown }) {
|
||||
return keys.every(key => hasOwnProperty(val, key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows `val` to include the property `key` with type `V`
|
||||
* @param val the value that we are trying to type narrow
|
||||
* @param key The key to test if it is present on the object (must be a literal for tsc to do any meaningful typing)
|
||||
* @param isValid a function to check if the field is valid
|
||||
*/
|
||||
export function hasTypedProperty<S extends object, K extends PropertyKey, V>(val: S, key: K, isValid: (value: unknown) => value is V): val is (S & { [key in K]: V }) {
|
||||
return hasOwnProperty(val, key) && isValid(val[key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows `val` to include the property `key` with type string
|
||||
* @param val the value that we are trying to type narrow
|
||||
* @param key The key to test if it is present on the object (must be a literal for tsc to do any meaningful typing)
|
||||
*/
|
||||
export function hasStringProperty<S extends object, K extends PropertyKey>(val: S, key: K): val is (S & { [key in K]: string }) {
|
||||
return hasOwnProperty(val, key) && isString(val[key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrows `val` to include the property `key` with type `V | undefined` or doesn't contain it
|
||||
* @param val the value that we are trying to type narrow
|
||||
* @param key The key to test if it is present on the object (must be a literal for tsc to do any meaningful typing)
|
||||
* @param isValid a function to check if the field (when present) is valid
|
||||
*/
|
||||
export function hasOptionalTypedProperty<S extends object, K extends PropertyKey, V>(val: S, key: K, isValid: (value: unknown) => value is V): val is (S & { [key in K]?: V }) {
|
||||
if (hasOwnProperty(val, key)) {
|
||||
return typeof val[key] === "undefined" || isValid(val[key]);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* isRecord checks if `val` matches the signature `Record<T, V>` or `{ [label in T]: V }`
|
||||
* @param val The value to be checked
|
||||
* @param isKey a function for checking if the key is of the correct type
|
||||
* @param isValue a function for checking if a value is of the correct type
|
||||
*/
|
||||
export function isRecord<T extends PropertyKey, V>(val: unknown, isKey: (key: unknown) => key is T, isValue: (value: unknown) => value is V): val is Record<T, V> {
|
||||
return isObject(val) && Object.entries(val).every(([key, value]) => isKey(key) && isValue(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* isTypedArray checks if `val` is an array and all of its entries are of type `T`
|
||||
* @param val The value to be checked
|
||||
* @param isEntry a function for checking if an entry is the correct type
|
||||
*/
|
||||
export function isTypedArray<T>(val: unknown, isEntry: (entry: unknown) => entry is T): val is T[] {
|
||||
return Array.isArray(val) && val.every(isEntry);
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if val is of type string
|
||||
* @param val the value to be checked
|
||||
*/
|
||||
export function isString(val: unknown): val is string {
|
||||
return typeof val === "string";
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if val is of type Buffer
|
||||
* @param val the value to be checked
|
||||
*/export function isBuffer(val: unknown): val is Buffer {
|
||||
return val instanceof Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if val is of type number
|
||||
* @param val the value to be checked
|
||||
*/
|
||||
export function isNumber(val: unknown): val is number {
|
||||
return typeof val === "number";
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if val is of type boolean
|
||||
* @param val the value to be checked
|
||||
*/
|
||||
export function isBoolean(val: unknown): val is boolean {
|
||||
return typeof val === "boolean";
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if val is of type object and isn't null
|
||||
* @param val the value to be checked
|
||||
*/
|
||||
export function isObject(val: unknown): val is Record<string | symbol | number, unknown> {
|
||||
return typeof val === "object" && val !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if `val` is defined, useful for filtering out undefined values in a strict manner
|
||||
*/
|
||||
export function isDefined<T>(val: T | undefined | null): val is T {
|
||||
return val != null;
|
||||
}
|
||||
|
||||
export function isFunction(val: unknown): val is (...args: unknown[]) => unknown {
|
||||
return typeof val === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the value in the second position is non-nullable
|
||||
*/
|
||||
export function hasDefinedTupleValue<K, V>(pair: readonly [K, V | undefined | null]): pair is [K, V] {
|
||||
return pair[1] != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new predicate function (with the same predicate) from `fn`. Such
|
||||
* that it can be called with just the value to be tested.
|
||||
*
|
||||
* This is useful for when using `hasOptionalProperty` and `hasTypedProperty`
|
||||
* @param fn A typescript user predicate function to be bound
|
||||
* @param boundArgs the set of arguments to be passed to `fn` in the new function
|
||||
*/
|
||||
export function bindPredicate<FnArgs extends any[], T>(fn: (arg1: unknown, ...args: FnArgs) => arg1 is T, ...boundArgs: FnArgs): (arg1: unknown) => arg1 is T {
|
||||
return (arg1: unknown): arg1 is T => fn(arg1, ...boundArgs);
|
||||
}
|
||||
|
||||
export function hasDefiniteField<Field extends keyof T, T>(field: Field): (val: T) => val is T & { [f in Field]-?: NonNullable<T[Field]> } {
|
||||
return (val): val is T & { [f in Field]-?: NonNullable<T[Field]> } => val[field] != null;
|
||||
}
|
||||
|
||||
export function isPromiseLike(res: unknown): res is (Promise<unknown> | { then: (fn: (val: unknown) => any) => Promise<unknown> }) {
|
||||
if (res instanceof Promise) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return isObject(res)
|
||||
&& hasTypedProperty(res, "then", isFunction);
|
||||
}
|
||||
|
||||
export function isPromiseSettledRejected<T>(result: PromiseSettledResult<T>): result is PromiseRejectedResult {
|
||||
return result.status === "rejected";
|
||||
}
|
||||
|
||||
export function isPromiseSettledFulfilled<T>(result: PromiseSettledResult<T>): result is PromiseFulfilledResult<T> {
|
||||
return result.status === "fulfilled";
|
||||
}
|
||||
|
||||
export function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
|
||||
return isObject(error)
|
||||
&& hasOptionalTypedProperty(error, "code", isString)
|
||||
&& hasOptionalTypedProperty(error, "path", isString)
|
||||
&& hasOptionalTypedProperty(error, "syscall", isString)
|
||||
&& hasOptionalTypedProperty(error, "errno", isNumber)
|
||||
&& error instanceof Error;
|
||||
}
|
||||
|
||||
export function isExecException(error: unknown): error is ExecException {
|
||||
return isObject(error)
|
||||
&& hasOptionalTypedProperty(error, "cmd", isString)
|
||||
&& hasOptionalTypedProperty(error, "killed", isBoolean)
|
||||
&& hasOptionalTypedProperty(error, "signal", isString)
|
||||
&& hasOptionalTypedProperty(error, "code", isNumber)
|
||||
&& error instanceof Error;
|
||||
}
|
||||
|
||||
export function isExecFileException(error: unknown): error is ExecFileException {
|
||||
return isExecException(error) && isErrnoException(error);
|
||||
}
|
||||
|
||||
export type OutputFormat = "string" | "buffer";
|
||||
export type ComputeOutputFormat<Format> = Format extends "string"
|
||||
? string
|
||||
: Format extends "buffer"
|
||||
? Buffer
|
||||
: string | Buffer;
|
||||
|
||||
export interface ChildProcessExecpetion<Format> extends ExecFileException {
|
||||
stderr: ComputeOutputFormat<Format>;
|
||||
stdout: ComputeOutputFormat<Format>;
|
||||
}
|
||||
|
||||
const isStringOrBuffer = (val: unknown): val is string | Buffer => isString(val) || isBuffer(val);
|
||||
|
||||
export function isChildProcessError(error: unknown, format?: OutputFormat): error is ChildProcessExecpetion<typeof format> {
|
||||
if (!isExecFileException(error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (format === "string") {
|
||||
return hasTypedProperty(error, "stderr", isString)
|
||||
&& hasTypedProperty(error, "stdout", isString);
|
||||
} else if (format === "buffer") {
|
||||
return hasTypedProperty(error, "stderr", isBuffer)
|
||||
&& hasTypedProperty(error, "stdout", isBuffer);
|
||||
} else {
|
||||
return hasTypedProperty(error, "stderr", isStringOrBuffer)
|
||||
&& hasTypedProperty(error, "stdout", isStringOrBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
export interface RequestLikeError extends Error {
|
||||
statusCode?: number;
|
||||
failed?: boolean;
|
||||
timedOut?: boolean;
|
||||
error?: string;
|
||||
response?: IncomingMessage & { body?: any };
|
||||
}
|
||||
|
||||
/**
|
||||
* A type guard for checking if the error is similar in shape to a request package error
|
||||
*/
|
||||
export function isRequestError(error: unknown): error is RequestLikeError {
|
||||
return isObject(error)
|
||||
&& hasOptionalTypedProperty(error, "statusCode", isNumber)
|
||||
&& hasOptionalTypedProperty(error, "failed", isBoolean)
|
||||
&& hasOptionalTypedProperty(error, "timedOut", isBoolean)
|
||||
&& hasOptionalTypedProperty(error, "error", isString)
|
||||
&& hasOptionalTypedProperty(error, "response", isObject)
|
||||
&& error instanceof Error;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { SetRequired } from "type-fest";
|
||||
|
||||
export type RemoveUndefinedFromValues<K> = {
|
||||
[P in keyof K]: NonNullable<K[P]>;
|
||||
};
|
||||
|
||||
/**
|
||||
* This type helps define which fields of some type will always be defined
|
||||
*/
|
||||
export type Defaulted<Params, DefaultParams extends keyof Params> = RemoveUndefinedFromValues<Required<Pick<Params, DefaultParams>>> & Omit<Params, DefaultParams>;
|
||||
|
||||
export type OptionVariant<Key, Base, RequiredKey extends keyof Base> = {
|
||||
type: Key;
|
||||
} & Pick<Base, RequiredKey> & {
|
||||
[OtherKey in Exclude<keyof Base, RequiredKey>]?: undefined;
|
||||
};
|
||||
|
||||
export type SingleOrMany<T> = T | T[];
|
||||
|
||||
export type IfEquals<T, U, Y=unknown, N=never> =
|
||||
(<G>() => G extends T ? 1 : 2) extends
|
||||
(<G>() => G extends U ? 1 : 2) ? Y : N;
|
||||
|
||||
export type MaybeSetRequired<BaseType, Keys extends keyof BaseType, Query> = Query extends true
|
||||
? SetRequired<BaseType, Keys>
|
||||
: BaseType;
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import path from "path";
|
||||
import { unionPATHs } from "../union-env-path";
|
||||
|
||||
describe("unionPATHs", () => {
|
||||
it("return the same path if given only one with no double delimiters", () => {
|
||||
expect(unionPATHs(`/bin/bar${path.delimiter}/usr/bin`)).toBe(`/bin/bar${path.delimiter}/usr/bin`);
|
||||
});
|
||||
|
||||
it("return equivalent path if given only one with no double delimiters", () => {
|
||||
expect(unionPATHs(`/bin/bar${path.delimiter}${path.delimiter}/usr/bin`)).toBe(`/bin/bar${path.delimiter}/usr/bin`);
|
||||
});
|
||||
|
||||
it("should remove duplicate entries, appending non duplicates in order received", () => {
|
||||
expect(unionPATHs(
|
||||
`/bin/bar${path.delimiter}/usr/bin`,
|
||||
`/bin/bar${path.delimiter}/usr/lens/bat`,
|
||||
)).toBe(`/bin/bar${path.delimiter}/usr/bin${path.delimiter}/usr/lens/bat`);
|
||||
});
|
||||
|
||||
it("should remove duplicate entries, appending non duplicates in order received, 3", () => {
|
||||
expect(unionPATHs(
|
||||
`/bin/bar${path.delimiter}/usr/bin`,
|
||||
`/bin/bar${path.delimiter}/usr/lens/bat`,
|
||||
`/usr/local/lens${path.delimiter}/usr/bin`,
|
||||
)).toBe(`/bin/bar${path.delimiter}/usr/bin${path.delimiter}/usr/lens/bat${path.delimiter}/usr/local/lens`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import path from "path";
|
||||
import { iter } from "./iter";
|
||||
|
||||
/**
|
||||
* Join all entires with a PATH env var delimited string together
|
||||
* @param PATHs Any number of PATH env variables
|
||||
*
|
||||
* NOTE: This function does not attempt to handle any sort of escape sequences since after testing
|
||||
* it was found that `zsh` (at least on `macOS`) does not when trying to find programs
|
||||
*/
|
||||
export function unionPATHs(...PATHs: string[]): string {
|
||||
const entries = new Set(iter.filterFlatMap(PATHs, PATH => PATH.split(path.delimiter)));
|
||||
|
||||
return iter.join(entries.values(), path.delimiter);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { IComputedValue } from "mobx";
|
||||
import { runInAction, when } from "mobx";
|
||||
import type { Disposer } from "./disposer";
|
||||
|
||||
export async function waitUntilDefined<T>(getter: (() => T | null | undefined) | IComputedValue<T | null | undefined>, opts?: { timeout?: number }): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
when(
|
||||
() => {
|
||||
const res = typeof getter === "function"
|
||||
? getter()
|
||||
: getter.get();
|
||||
const isDefined = res != null;
|
||||
|
||||
if (isDefined) {
|
||||
resolve(res);
|
||||
}
|
||||
|
||||
return isDefined;
|
||||
},
|
||||
() => {},
|
||||
{
|
||||
onError: reject,
|
||||
...(opts ?? {}),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function onceDefined<T>(getter: () => T | null | undefined, action: (val: T) => void): Disposer {
|
||||
let res: T | null | undefined;
|
||||
|
||||
return when(
|
||||
() => {
|
||||
res = getter();
|
||||
|
||||
if (res != null) {
|
||||
const r = res;
|
||||
|
||||
runInAction(() => {
|
||||
action(r);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
() => {},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import pLimit from "p-limit";
|
||||
|
||||
export type ConcurrencyLimiter = <Args extends any[], Res>(fn: (...args: Args) => Res) => (...args: Args) => Promise<Res>;
|
||||
|
||||
export function withConcurrencyLimit(limit: number): ConcurrencyLimiter {
|
||||
const limiter = pLimit(limit);
|
||||
|
||||
return fn => (...args) => limiter(() => fn(...args));
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "@k8slens/typescript/config/base.json"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = require("@k8slens/webpack").configForNode;
|
||||
Reference in new issue
Block a user