Replace all internal uses of utilities with new packages

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton committed 2023-03-02 13:30:57 -05:00
1 parent 3a2e436933
commit ef32f2b72b
410 files changed
+1222 -825

No files matched your search

+2
View File
@@ -330,6 +330,8 @@
},
"peerDependencies": {
"@k8slens/application": "^6.5.0-alpha.0",
"@k8slens/test-utils": "^1.0.0",
"@k8slens/utilities": "^1.0.0",
"@types/byline": "^4.2.33",
"@types/chart.js": "^2.9.36",
"@types/color": "^3.0.3",
@@ -7,7 +7,7 @@ import type Config from "conf";
import type { Migrations, Options as ConfOptions } from "conf/dist/source/types";
import type { IEqualsComparer } from "mobx";
import { makeObservable, reaction } from "mobx";
import { disposer, isPromiseLike, toJS } from "../utils";
import { disposer, isPromiseLike } from "@k8slens/utilities";
import { broadcastMessage } from "../ipc";
import isEqual from "lodash/isEqual";
import { kebabCase } from "lodash";
@@ -16,6 +16,7 @@ import type { Logger } from "../logger";
import type { PersistStateToConfig } from "./save-to-file";
import type { GetBasenameOfPath } from "../path/get-basename.injectable";
import type { EnlistMessageChannelListener } from "../utils/channel/enlist-message-channel-listener-injection-token";
import { toJS } from "../utils";
export interface BaseStoreParams<T> extends Omit<ConfOptions<T>, "migrations"> {
syncOptions?: {
@@ -7,7 +7,7 @@ import { lifecycleEnum, getInjectable } from "@ogre-tools/injectable";
import type Conf from "conf/dist/source";
import type { Migrations } from "conf/dist/source/types";
import loggerInjectable from "../logger.injectable";
import { getOrInsert, iter } from "../utils";
import { getOrInsert, iter } from "@k8slens/utilities";
export interface MigrationDeclaration {
version: string;
@@ -5,7 +5,7 @@
import { getInjectable } from "@ogre-tools/injectable";
import { generalCatalogEntityInjectionToken } from "../general-catalog-entity-injection-token";
import { GeneralEntity } from "../../index";
import { buildURL } from "../../../utils/buildUrl";
import { buildURL } from "@k8slens/utilities";
import catalogRouteInjectable from "../../../front-end-routing/routes/catalog/catalog-route.injectable";
const catalogCatalogEntityInjectable = getInjectable({
@@ -5,7 +5,7 @@
import { getInjectable } from "@ogre-tools/injectable";
import { generalCatalogEntityInjectionToken } from "../general-catalog-entity-injection-token";
import { GeneralEntity } from "../../index";
import { buildURL } from "../../../utils/buildUrl";
import { buildURL } from "@k8slens/utilities/src/buildUrl";
import welcomeRouteInjectable from "../../../front-end-routing/routes/welcome/welcome-route.injectable";
const welcomeCatalogEntityInjectable = getInjectable({
@@ -7,8 +7,8 @@ import EventEmitter from "events";
import type TypedEmitter from "typed-emitter";
import { observable, makeObservable } from "mobx";
import { once } from "lodash";
import type { Disposer } from "../utils";
import { iter } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { iter } from "@k8slens/utilities";
import type { CategoryColumnRegistration, TitleCellProps } from "../../renderer/components/+catalog/custom-category-columns";
export type { CategoryColumnRegistration, TitleCellProps };
@@ -5,8 +5,8 @@
import { action, computed, observable, makeObservable } from "mobx";
import { once } from "lodash";
import { iter, getOrInsertMap, strictSet } from "../utils";
import type { Disposer } from "../utils";
import { iter, getOrInsertMap, strictSet } from "@k8slens/utilities";
import type { Disposer } from "@k8slens/utilities";
import type { CatalogCategory, CatalogEntityData, CatalogEntityKindData } from "./catalog-entity";
export type CategoryFilter = (category: CatalogCategory) => any;
+5 -4
View File
@@ -11,10 +11,10 @@ import type { Kubectl } from "../../main/kubectl/kubectl";
import type { KubeconfigManager } from "../../main/kubeconfig-manager/kubeconfig-manager";
import type { KubeApiResource, KubeApiResourceDescriptor } from "../rbac";
import { formatKubeApiResource } from "../rbac";
import plimit from "p-limit";
import type { ClusterState, ClusterMetricsResourceType, ClusterId, ClusterMetadata, ClusterModel, ClusterPreferences, ClusterPrometheusPreferences, UpdateClusterModel, KubeAuthUpdate, ClusterConfigData } from "../cluster-types";
import { ClusterMetadataKey, initialNodeShellImage, ClusterStatus, clusterModelIdChecker, updateClusterModelChecker } from "../cluster-types";
import { disposer, isDefined, isRequestError, toJS } from "../utils";
import { disposer, isDefined, isRequestError, withConcurrencyLimit } from "@k8slens/utilities";
import { toJS } from "../utils";
import { clusterListNamespaceForbiddenChannel } from "../ipc/cluster";
import type { CanI } from "./authorization-review.injectable";
import type { ListNamespaces } from "./list-namespaces.injectable";
@@ -683,10 +683,11 @@ export class Cluster implements ClusterModel {
return [];
}
const apiLimit = withConcurrencyLimit(5);
try {
const apiLimit = plimit(5); // 5 concurrent api requests
const canListResourceCheckers = await Promise.all((
this.allowedNamespaces.map(namespace => apiLimit(() => requestNamespaceListPermissions(namespace)))
this.allowedNamespaces.map(namespace => apiLimit(() => requestNamespaceListPermissions(namespace))())
));
const canListNamespacedResource: CanListResource = (resource) => canListResourceCheckers.some(fn => fn(resource));
@@ -5,7 +5,7 @@
import type { KubeConfig } from "@kubernetes/client-node";
import { CoreV1Api } from "@kubernetes/client-node";
import { getInjectable } from "@ogre-tools/injectable";
import { isDefined } from "../utils";
import { isDefined } from "@k8slens/utilities";
export type ListNamespaces = () => Promise<string[]>;
@@ -4,14 +4,14 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { RequestInit, Response } from "@k8slens/node-fetch";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import fetchInjectable from "./fetch.injectable";
export interface DownloadBinaryOptions {
signal?: AbortSignal | null | undefined;
}
export type DownloadBinary = (url: string, opts?: DownloadBinaryOptions) => Promise<AsyncResult<Buffer, string>>;
export type DownloadBinary = (url: string, opts?: DownloadBinaryOptions) => AsyncResult<Buffer, string>;
const downloadBinaryInjectable = getInjectable({
id: "download-binary",
@@ -2,7 +2,7 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { AsyncResult } from "../../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { Fetch } from "../fetch.injectable";
import type { RequestInit, Response } from "@k8slens/node-fetch";
@@ -10,7 +10,7 @@ export interface DownloadJsonOptions {
signal?: AbortSignal | null | undefined;
}
export type DownloadJson = (url: string, opts?: DownloadJsonOptions) => Promise<AsyncResult<unknown, string>>;
export type DownloadJson = (url: string, opts?: DownloadJsonOptions) => AsyncResult<unknown, string>;
export const downloadJsonWith = (fetch: Fetch): DownloadJson => async (url, opts) => {
let result: Response;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "../../../../utility-features/test-utils/src/get-global-override-for-function";
import fetchInjectable from "./fetch.injectable";
export default getGlobalOverrideForFunction(fetchInjectable);
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "../../../../utility-features/test-utils/src/get-global-override-for-function";
import lensFetchInjectable from "./lens-fetch.injectable";
export default getGlobalOverrideForFunction(lensFetchInjectable);
@@ -4,7 +4,7 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import { shouldShowResourceInjectionToken } from "../../../../../cluster-store/allowed-resources-injection-token";
import { computedOr } from "../../../../../utils/computed-or";
import { computedOr } from "@k8slens/utilities";
import { frontEndRouteInjectionToken } from "../../../../front-end-route-injection-token";
const ingressesRouteInjectable = getInjectable({
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "../../../../utility-features/test-utils/src/get-global-override-for-function";
import execFileInjectable from "./exec-file.injectable";
export default getGlobalOverrideForFunction(execFileInjectable);
@@ -5,14 +5,14 @@
import { getInjectable } from "@ogre-tools/injectable";
import type { ExecFileException, ExecFileOptions } from "child_process";
import { execFile } from "child_process";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
export type ExecFileError = ExecFileException & { stderr: string };
export interface ExecFile {
(filePath: string): Promise<AsyncResult<string, ExecFileError>>;
(filePath: string, argsOrOptions: string[] | ExecFileOptions): Promise<AsyncResult<string, ExecFileError>>;
(filePath: string, args: string[], options: ExecFileOptions): Promise<AsyncResult<string, ExecFileError>>;
(filePath: string): AsyncResult<string, ExecFileError>;
(filePath: string, argsOrOptions: string[] | ExecFileOptions): AsyncResult<string, ExecFileError>;
(filePath: string, args: string[], options: ExecFileOptions): AsyncResult<string, ExecFileError>;
}
const execFileInjectable = getInjectable({
@@ -21,6 +21,7 @@ const fsInjectable = getInjectable({
rm,
access,
stat,
unlink,
},
ensureDir,
ensureDirSync,
@@ -56,6 +57,7 @@ const fsInjectable = getInjectable({
ensureDirSync,
createReadStream,
stat,
unlink,
};
},
causesSideEffects: true,
@@ -0,0 +1,15 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import fsInjectable from "./fs.injectable";
export type Unlink = (path: string) => Promise<void>;
const unlinkInjectable = getInjectable({
id: "unlink",
instantiate: (di): Unlink => di.inject(fsInjectable).unlink,
});
export default unlinkInjectable;
@@ -3,13 +3,13 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { AsyncResult } from "../utils/async-result";
import { isErrnoException } from "../utils";
import type { AsyncResult } from "@k8slens/utilities";
import { isErrnoException } from "@k8slens/utilities";
import type { Stats } from "fs-extra";
import { lowerFirst } from "lodash/fp";
import statInjectable from "./stat.injectable";
export type ValidateDirectory = (path: string) => Promise<AsyncResult<undefined>>;
export type ValidateDirectory = (path: string) => AsyncResult<undefined>;
function getUserReadableFileType(stats: Stats): string {
if (stats.isFile()) {
@@ -6,7 +6,7 @@ import { getInjectable } from "@ogre-tools/injectable";
import { watch } from "chokidar";
import type { Stats } from "fs";
import type TypedEventEmitter from "typed-emitter";
import type { SingleOrMany } from "../../utils";
import type { SingleOrMany } from "@k8slens/utilities";
export interface AlwaysStatWatcherEvents {
add: (path: string, stats: Stats) => void;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { HelmRepo } from "./helm-repo";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
export type AddHelmRepositoryChannel = RequestChannel<HelmRepo, AsyncResult<void, string>>;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { HelmRepo } from "./helm-repo";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
export type GetActiveHelmRepositoriesChannel = RequestChannel<void, AsyncResult<HelmRepo[]>>;
@@ -2,7 +2,7 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
import type { HelmRepo } from "./helm-repo";
+2 -2
View File
@@ -4,8 +4,8 @@
*/
import * as uuid from "uuid";
import type { Tuple } from "../utils";
import { tuple } from "../utils";
import type { Tuple } from "@k8slens/utilities";
import { tuple } from "@k8slens/utilities";
export interface HotbarItem {
entity: {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "../test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "../../../../utility-features/test-utils/src/get-global-override-for-function";
import broadcastMessageInjectable from "./broadcast-message.injectable";
export default getGlobalOverrideForFunction(broadcastMessageInjectable);
+1 -1
View File
@@ -11,7 +11,7 @@ import { ipcMain, ipcRenderer, webContents } from "electron";
import { toJS } from "../utils/toJS";
import type { ClusterFrameInfo } from "../cluster-frames";
import { clusterFrameMap } from "../cluster-frames";
import type { Disposer } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { getLegacyGlobalDiForExtensionApi } from "../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import ipcRendererInjectable from "../../renderer/utils/channel/ipc-renderer.injectable";
import loggerInjectable from "../logger.injectable";
+1 -1
View File
@@ -3,8 +3,8 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import autoBind from "auto-bind";
import orderBy from "lodash/orderBy";
import { autoBind } from "./utils";
import { action, computed, observable, when, makeObservable } from "mobx";
export interface ItemObject {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { noop } from "../../utils";
import { noop } from "@k8slens/utilities";
import type { KubeApi } from "../kube-api";
import { KubeObject } from "../kube-object";
import type { KubeObjectStoreLoadingParams } from "../kube-object.store";
@@ -10,7 +10,7 @@ import { autorun, action, observable } from "mobx";
import type { KubeApi } from "../kube-api";
import type { KubeObject, ObjectReference } from "../kube-object";
import { parseKubeApi, createKubeApiURL } from "../kube-api-parse";
import { chain, find } from "../../utils/iter";
import { chain, find } from "@k8slens/utilities/src/iter";
export type RegisterableStore<Store> = Store extends KubeObjectStore<any, any, any>
? Store
@@ -8,7 +8,7 @@ import { KubeObject } from "../kube-object";
import type { KubeJsonApiData } from "../kube-json-api";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import { autoBind } from "../../utils";
import autoBind from "auto-bind";
export interface ConfigMapData extends KubeJsonApiData<KubeObjectMetadata<KubeObjectScope.Namespace>, void, void> {
data?: Partial<Record<string, string>>;
@@ -6,7 +6,7 @@
import moment from "moment";
import type { NamespaceScopedMetadata, ObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { formatDuration } from "../../utils/formatDuration";
import { formatDuration } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { JobTemplateSpec } from "./types/job-template-spec";
@@ -5,7 +5,7 @@
import { getLegacyGlobalDiForExtensionApi } from "../../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import customResourcesRouteInjectable from "../../front-end-routing/routes/cluster/custom-resources/custom-resources/custom-resources-route.injectable";
import { buildURL } from "../../utils/buildUrl";
import { buildURL } from "@k8slens/utilities/src/buildUrl";
import type { BaseKubeObjectCondition, ClusterScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
@@ -10,7 +10,7 @@ import { KubeApi } from "../kube-api";
import type { PodSpec } from "./pod.api";
import type { KubeObjectStatus, LabelSelector, NamespaceScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import { hasTypedProperty, isNumber, isObject } from "../../utils";
import { hasTypedProperty, isNumber, isObject } from "@k8slens/utilities";
export class DeploymentApi extends KubeApi<Deployment> {
constructor(deps: KubeApiDependencies, opts?: DerivedKubeApiOptions) {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { autoBind } from "../../utils";
import autoBind from "auto-bind";
import type { KubeObjectMetadata, KubeObjectScope, NamespaceScopedMetadata, ObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
@@ -6,7 +6,7 @@
import moment from "moment";
import type { KubeObjectMetadata, KubeObjectScope, ObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { formatDuration } from "../../utils/formatDuration";
import { formatDuration } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { KubeJsonApiData } from "../kube-json-api";
@@ -3,7 +3,8 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { autoBind, bifurcateArray } from "../../utils";
import { array } from "@k8slens/utilities";
import autoBind from "auto-bind";
import Joi from "joi";
export interface RawHelmChart {
@@ -263,7 +264,7 @@ export class HelmChart implements HelmChartData {
return new HelmChart(result.value);
}
const [actualErrors, unknownDetails] = bifurcateArray(result.error.details, ({ type }) => type === "object.unknown");
const [actualErrors, unknownDetails] = array.bifurcate(result.error.details, ({ type }) => type === "object.unknown");
if (unknownDetails.length > 0) {
console.warn("HelmChart data has unexpected fields", { original: data, unknownFields: unknownDetails.flatMap(d => d.path) });
@@ -5,7 +5,7 @@
import { getInjectable } from "@ogre-tools/injectable";
import type { RawHelmChart } from "../helm-charts.api";
import { HelmChart } from "../helm-charts.api";
import { isDefined } from "../../../utils";
import { isDefined } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmCharts = () => Promise<HelmChart[]>;
@@ -3,13 +3,13 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { AsyncResult } from "../../../utils/async-result";
import { urlBuilderFor } from "../../../utils/buildUrl";
import type { AsyncResult } from "@k8slens/utilities";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
const requestReadmeEndpoint = urlBuilderFor("/v2/charts/:repo/:name/readme");
export type RequestHelmChartReadme = (repo: string, name: string, version?: string) => Promise<AsyncResult<string>>;
export type RequestHelmChartReadme = (repo: string, name: string, version?: string) => AsyncResult<string>;
const requestHelmChartReadmeInjectable = getInjectable({
id: "request-helm-chart-readme",
@@ -3,13 +3,13 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { AsyncResult } from "../../../utils/async-result";
import { urlBuilderFor } from "../../../utils/buildUrl";
import type { AsyncResult } from "@k8slens/utilities";
import { urlBuilderFor } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
const requestValuesEndpoint = urlBuilderFor("/v2/charts/:repo/:name/values");
export type RequestHelmChartValues = (repo: string, name: string, version: string) => Promise<AsyncResult<string>>;
export type RequestHelmChartValues = (repo: string, name: string, version: string) => AsyncResult<string>;
const requestHelmChartValuesInjectable = getInjectable({
id: "request-helm-chart-values",
@@ -3,10 +3,10 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import { HelmChart } from "../helm-charts.api";
import type { RawHelmChart } from "../helm-charts.api";
import { isDefined } from "../../../utils";
import { isDefined } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
const requestVersionsEndpoint = urlBuilderFor("/v2/charts/:repo/:name/versions");
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmReleaseConfiguration = (
@@ -5,7 +5,7 @@
import yaml from "js-yaml";
import { getInjectable } from "@ogre-tools/injectable";
import type { HelmReleaseUpdateDetails } from "../helm-releases.api";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
interface HelmReleaseCreatePayload {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestDeleteHelmRelease = (name: string, namespace: string) => Promise<void>;
@@ -4,7 +4,7 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import type { KubeJsonApiData } from "../../kube-json-api";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
export interface HelmReleaseDetails {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
export interface HelmReleaseRevision {
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
import type { HelmReleaseDto } from "../helm-releases.api";
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmReleaseRollback = (name: string, namespace: string, revision: number) => Promise<void>;
@@ -3,8 +3,8 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import type { AsyncResult } from "../../../utils/async-result";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import type { AsyncResult } from "@k8slens/utilities";
import apiBaseInjectable from "../../api-base.injectable";
interface HelmReleaseUpdatePayload {
@@ -18,7 +18,7 @@ export type RequestHelmReleaseUpdate = (
name: string,
namespace: string,
payload: HelmReleaseUpdatePayload
) => Promise<AsyncResult<void, unknown>>;
) => AsyncResult<void, unknown>;
const requestUpdateEndpoint = urlBuilderFor("/v2/releases/:namespace/:name");
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { urlBuilderFor } from "../../../utils/buildUrl";
import { urlBuilderFor } from "@k8slens/utilities/src/buildUrl";
import apiBaseInjectable from "../../api-base.injectable";
export type RequestHelmReleaseValues = (name: string, namespace: string, all?: boolean) => Promise<string>;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { OptionVarient } from "../../utils";
import type { OptionVariant } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { BaseKubeObjectCondition, LabelSelector, NamespaceScopedMetadata } from "../kube-object";
@@ -46,7 +46,7 @@ export interface V2Beta1ContainerResourceMetricSource {
targetAverageValue?: string;
}
export type ContainerResourceMetricSource =
export type ContainerResourceMetricSource =
| V2ContainerResourceMetricSource
| V2Beta1ContainerResourceMetricSource;
@@ -74,7 +74,7 @@ export interface V2Beta1ExternalMetricSource {
};
}
export type ExternalMetricSource =
export type ExternalMetricSource =
| V2Beta1ExternalMetricSource
| V2ExternalMetricSource;
@@ -152,11 +152,11 @@ export interface BaseHorizontalPodAutoscalerMetricSpec {
}
export type HorizontalPodAutoscalerMetricSpec =
| OptionVarient<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricSpec, "resource">
| OptionVarient<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricSpec, "external">
| OptionVarient<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricSpec, "object">
| OptionVarient<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricSpec, "pods">
| OptionVarient<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricSpec, "containerResource">;
| OptionVariant<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricSpec, "resource">
| OptionVariant<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricSpec, "external">
| OptionVariant<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricSpec, "object">
| OptionVariant<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricSpec, "pods">
| OptionVariant<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricSpec, "containerResource">;
interface HorizontalPodAutoscalerBehavior {
scaleUp?: HPAScalingRules;
@@ -294,11 +294,11 @@ export interface BaseHorizontalPodAutoscalerMetricStatus {
}
export type HorizontalPodAutoscalerMetricStatus =
| OptionVarient<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricStatus, "resource">
| OptionVarient<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricStatus, "external">
| OptionVarient<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricStatus, "object">
| OptionVarient<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricStatus, "pods">
| OptionVarient<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricStatus, "containerResource">;
| OptionVariant<HpaMetricType.Resource, BaseHorizontalPodAutoscalerMetricStatus, "resource">
| OptionVariant<HpaMetricType.External, BaseHorizontalPodAutoscalerMetricStatus, "external">
| OptionVariant<HpaMetricType.Object, BaseHorizontalPodAutoscalerMetricStatus, "object">
| OptionVariant<HpaMetricType.Pods, BaseHorizontalPodAutoscalerMetricStatus, "pods">
| OptionVariant<HpaMetricType.ContainerResource, BaseHorizontalPodAutoscalerMetricStatus, "containerResource">;
export interface HorizontalPodAutoscalerSpec {
scaleTargetRef: CrossVersionObjectReference;
@@ -5,7 +5,7 @@
import type { NamespaceScopedMetadata, TypedLocalObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { hasTypedProperty, isString, iter } from "../../utils";
import { hasTypedProperty, isString, iter } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { RequireExactlyOne } from "type-fest";
@@ -6,7 +6,7 @@
// Metrics api
import moment from "moment";
import { isDefined, object } from "../../utils";
import { isDefined, object } from "@k8slens/utilities";
export interface MetricData {
status: string;
@@ -5,7 +5,7 @@
import type { BaseKubeObjectCondition, ClusterScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import { cpuUnitsToNumber, unitsToBytes, isObject } from "../../../renderer/utils";
import { cpuUnitsToNumber, unitsToBytes, isObject } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import { TypedRegEx } from "typed-regex";
@@ -8,7 +8,7 @@ import { KubeObject } from "../kube-object";
import type { Pod } from "./pod.api";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import { object } from "../../utils";
import { object } from "@k8slens/utilities";
import type { ResourceRequirements } from "./types/resource-requirements";
export class PersistentVolumeClaimApi extends KubeApi<PersistentVolumeClaim> {
@@ -5,7 +5,7 @@
import type { ClusterScopedMetadata, LabelSelector, ObjectReference, TypedLocalObjectReference } from "../kube-object";
import { KubeObject } from "../kube-object";
import { unitsToBytes } from "../../utils";
import { unitsToBytes } from "@k8slens/utilities";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { ResourceRequirements } from "./types/resource-requirements";
@@ -10,7 +10,7 @@ import type { KubeObjectMetadata, LocalObjectReference, Affinity, Toleration, Na
import type { SecretReference } from "./secret.api";
import type { PersistentVolumeClaimSpec } from "./persistent-volume-claim.api";
import { KubeObject } from "../kube-object";
import { isDefined } from "../../utils";
import { isDefined } from "@k8slens/utilities";
import type { PodSecurityContext } from "./types/pod-security-context";
import type { Probe } from "./types/probe";
import type { Container } from "./types/container";
@@ -5,10 +5,10 @@
import { getInjectable } from "@ogre-tools/injectable";
import type { Patch } from "rfc6902";
import apiBaseInjectable from "../../api-base.injectable";
import type { AsyncResult } from "../../../utils/async-result";
import type { AsyncResult, Result } from "@k8slens/utilities";
import type { KubeJsonApiData } from "../../kube-json-api";
export type RequestKubeObjectPatch = (name: string, kind: string, ns: string | undefined, patch: Patch) => Promise<AsyncResult<KubeJsonApiData, string>>;
export type RequestKubeObjectPatch = (name: string, kind: string, ns: string | undefined, patch: Patch) => AsyncResult<KubeJsonApiData, string>;
const requestKubeObjectPatchInjectable = getInjectable({
id: "request-kube-object-patch",
@@ -23,7 +23,7 @@ const requestKubeObjectPatchInjectable = getInjectable({
ns,
patch,
},
}) as AsyncResult<string, string>;
}) as Result<string, string>;
if (!result.callWasSuccessful) {
return result;
@@ -4,10 +4,10 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import apiBaseInjectable from "../../api-base.injectable";
import type { AsyncResult } from "../../../utils/async-result";
import type { AsyncResult, Result } from "@k8slens/utilities";
import type { KubeJsonApiData } from "../../kube-json-api";
export type RequestKubeObjectCreation = (resourceDescriptor: string) => Promise<AsyncResult<KubeJsonApiData, string>>;
export type RequestKubeObjectCreation = (resourceDescriptor: string) => AsyncResult<KubeJsonApiData, string>;
const requestKubeObjectCreationInjectable = getInjectable({
id: "request-kube-object-creation",
@@ -15,7 +15,7 @@ const requestKubeObjectCreationInjectable = getInjectable({
const apiBase = di.inject(apiBaseInjectable);
return async (data) => {
const result = await apiBase.post("/stack", { data }) as AsyncResult<string, string>;
const result = await apiBase.post("/stack", { data }) as Result<string, string>;
if (!result.callWasSuccessful) {
return result;
@@ -6,9 +6,9 @@
import type { KubeObjectMetadata, KubeObjectScope, NamespaceScopedMetadata } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { KubeJsonApiData } from "../kube-json-api";
import { autoBind } from "../../utils";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import autoBind from "auto-bind";
export enum SecretType {
Opaque = "Opaque",
@@ -3,12 +3,12 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { autoBind } from "../../utils";
import type { ClusterScopedMetadata, KubeObjectMetadata, KubeObjectScope } from "../kube-object";
import { KubeObject } from "../kube-object";
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
import { KubeApi } from "../kube-api";
import type { KubeJsonApiData } from "../kube-json-api";
import autoBind from "auto-bind";
export interface TopologySelectorLabelRequirement {
key: string;
+16 -15
View File
@@ -15,8 +15,8 @@ import type { PartialDeep, ValueOf } from "type-fest";
import { EventEmitter } from "../../common/event-emitter";
import type { Logger } from "../../common/logger";
import type { Fetch } from "../fetch/fetch.injectable";
import type { Defaulted } from "../utils";
import { json } from "../utils";
import type { Defaulted } from "@k8slens/utilities";
import { isObject, isString, json } from "@k8slens/utilities";
export interface JsonApiData {}
@@ -184,20 +184,17 @@ export class JsonApi<Data = JsonApiData, Params extends JsonApiParams<Data> = Js
const res = await this.dependencies.fetch(reqUrl, reqInit);
return this.parseResponse<OutData>(res, infoLog);
return await this.parseResponse(res, infoLog) as OutData;
}
protected async parseResponse<OutData>(res: Response, log: JsonApiLog): Promise<OutData> {
protected async parseResponse(res: Response, log: JsonApiLog): Promise<Data> {
const { status } = res;
const text = await res.text();
let data: any;
try {
data = text ? json.parse(text) : ""; // DELETE-requests might not have response-body
} catch (e) {
data = text;
}
const parseResponse = json.parse(text || "{}");
const data = parseResponse.callWasSuccessful
? parseResponse.response as Data
: text as Data;
if (status >= 200 && status < 300) {
this.onData.emit(data, res);
@@ -211,7 +208,7 @@ export class JsonApi<Data = JsonApiData, Params extends JsonApiParams<Data> = Js
throw data;
}
const error = new JsonApiErrorParsed(data, this.parseError(data, res));
const error = new JsonApiErrorParsed(data as JsonApiError, this.parseError(data, res));
this.onError.emit(error, res);
this.writeLog({ ...log, error });
@@ -219,16 +216,20 @@ export class JsonApi<Data = JsonApiData, Params extends JsonApiParams<Data> = Js
throw error;
}
protected parseError(error: JsonApiError | string, res: Response): string[] {
if (typeof error === "string") {
protected parseError(error: unknown, res: Response): string[] {
if (isString(error)) {
return [error];
}
if (!isObject(error)) {
return [];
}
if (Array.isArray(error.errors)) {
return error.errors.map(error => error.title);
}
if (error.message) {
if (isString(error.message)) {
return [error.message];
}
@@ -5,7 +5,7 @@
// Parse kube-api path and get api-version, group, etc.
import { splitArray } from "../utils";
import { array } from "@k8slens/utilities";
export interface IKubeApiLinkRef {
apiPrefix?: string;
@@ -26,7 +26,7 @@ export function parseKubeApi(path: string): IKubeApiParsed {
const apiPath = new URL(path, "https://localhost").pathname;
const [, prefix, ...parts] = apiPath.split("/");
const apiPrefix = `/${prefix}`;
const [left, right, namespaced] = splitArray(parts, "namespaces");
const [left, right, namespaced] = array.split(parts, "namespaces");
let apiGroup!: string;
let apiVersion!: string;
let namespace!: string;
+2 -2
View File
@@ -13,8 +13,8 @@ import { KubeObject, KubeStatus, isKubeStatusData } from "./kube-object";
import byline from "byline";
import type { IKubeWatchEvent } from "./kube-watch-event";
import type { KubeJsonApiData, KubeJsonApi } from "./kube-json-api";
import type { Disposer } from "../utils";
import { isDefined, noop, WrappedAbortController } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { isDefined, noop, WrappedAbortController } from "@k8slens/utilities";
import type { RequestInit, Response } from "@k8slens/node-fetch";
import type { Patch } from "rfc6902";
import assert from "assert";
@@ -4,8 +4,8 @@
*/
import { action, computed, makeObservable, observable, reaction } from "mobx";
import type { Disposer } from "../utils";
import { waitUntilDefined, autoBind, includes, rejectPromiseBy } from "../utils";
import type { Disposer } from "@k8slens/utilities";
import { waitUntilDefined, includes, rejectPromiseBy, object } from "@k8slens/utilities";
import type { KubeJsonApiDataFor, KubeObject } from "./kube-object";
import { KubeStatus } from "./kube-object";
import type { IKubeWatchEvent } from "./kube-watch-event";
@@ -17,9 +17,9 @@ import type { Patch } from "rfc6902";
import type { Logger } from "../logger";
import assert from "assert";
import type { PartialDeep } from "type-fest";
import { entries } from "../utils/objects";
import AbortController from "abort-controller";
import type { ClusterContext } from "../../renderer/cluster-frame-context/cluster-frame-context";
import autoBind from "auto-bind";
export type OnLoadFailure = (error: unknown) => void;
@@ -179,7 +179,7 @@ export abstract class KubeObjectStore<
return this.items.filter((item: K) => {
const itemLabels = item.metadata.labels || {};
return entries(labels)
return object.entries(labels)
.every(([key, value]) => itemLabels[key] === value);
});
}
@@ -7,7 +7,7 @@
import moment from "moment";
import type { KubeJsonApiData, KubeJsonApiDataList, KubeJsonApiListMetadata } from "./kube-json-api";
import { autoBind, formatDuration, hasOptionalTypedProperty, hasTypedProperty, isObject, isString, isNumber, bindPredicate, isTypedArray, isRecord, json } from "../utils";
import { formatDuration, hasOptionalTypedProperty, hasTypedProperty, isObject, isString, isNumber, bindPredicate, isTypedArray, isRecord } from "@k8slens/utilities";
import type { ItemObject } from "../item.store";
import type { Patch } from "rfc6902";
import assert from "assert";
@@ -17,6 +17,7 @@ import { apiKubeInjectionToken } from "./api-kube";
import requestKubeObjectCreationInjectable from "./endpoints/resource-applier.api/request-update.injectable";
import { dump } from "js-yaml";
import { getLegacyGlobalDiForExtensionApi } from "../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import autoBind from "auto-bind";
export type KubeJsonApiDataFor<K> = K extends KubeObject<infer Metadata, infer Status, infer Spec>
? KubeJsonApiData<Metadata, Status, Spec>
@@ -624,7 +625,7 @@ export class KubeObject<
}
toPlainObject() {
return json.parse(JSON.stringify(this)) as JsonObject;
return JSON.parse(JSON.stringify(this)) as JsonObject;
}
/**
@@ -7,13 +7,13 @@ import type { KubernetesCluster } from "../catalog-entities";
import yaml from "js-yaml";
import { getLegacyGlobalDiForExtensionApi } from "../../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import productNameInjectable from "../vars/product-name.injectable";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { Logger } from "../logger";
import type { KubectlApplyAll, KubectlDeleteAll } from "../kube-helpers/channels";
import type { ReadDirectory } from "../fs/read-directory.injectable";
import type { JoinPaths } from "../path/join-paths.injectable";
import type { ReadFile } from "../fs/read-file.injectable";
import { hasTypedProperty, isObject } from "../utils";
import { hasTypedProperty, isObject } from "@k8slens/utilities";
export interface ResourceApplyingStack {
kubectlApplyFolder(folderPath: string, templateContext?: any, extraArgs?: string[]): Promise<string>;
+1 -1
View File
@@ -7,7 +7,7 @@ import { KubeConfig } from "@kubernetes/client-node";
import yaml from "js-yaml";
import type { Cluster, Context, User } from "@kubernetes/client-node/dist/config_types";
import { newClusters, newContexts, newUsers } from "@kubernetes/client-node/dist/config_types";
import { isDefined } from "./utils";
import { isDefined } from "@k8slens/utilities";
import Joi from "joi";
import type { PartialDeep } from "type-fest";
@@ -7,7 +7,7 @@ import { getInjectionToken } from "@ogre-tools/injectable";
import type { Asyncify } from "type-fest";
import type { RequestChannelHandler } from "../../main/utils/channel/channel-listeners/listener-tokens";
import type { ClusterId } from "../cluster-types";
import type { AsyncResult } from "../utils/async-result";
import type { AsyncResult } from "@k8slens/utilities";
import type { RequestChannel } from "../utils/channel/request-channel-listener-injection-token";
export interface KubectlApplyAllArgs {
@@ -2,7 +2,7 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverrideForFunction } from "./test-utils/get-global-override-for-function";
import { getGlobalOverrideForFunction } from "@k8slens/test-utils";
import logErrorInjectable from "./log-error.injectable";
// Note: this should remain as it is, and throw if called. Logging error is something
@@ -4,13 +4,12 @@
*/
import loggerInjectable from "./logger.injectable";
import { getGlobalOverride } from "./test-utils/get-global-override";
import { noop } from "./utils";
import { getGlobalOverride } from "@k8slens/test-utils";
export default getGlobalOverride(loggerInjectable, () => ({
warn: noop,
debug: noop,
error: noop,
info: noop,
silly: noop,
warn: () => {},
debug: () => {},
error: () => {},
info: () => {},
silly: () => {},
}));
@@ -6,7 +6,7 @@
import type { match } from "react-router";
import { matchPath } from "react-router";
import { countBy } from "lodash";
import { isDefined, iter } from "../utils";
import { isDefined, iter } from "@k8slens/utilities";
import { pathToRegexp } from "path-to-regexp";
import type Url from "url-parse";
import { RoutingError, RoutingErrorType } from "./error";
@@ -1,25 +0,0 @@
/**
* 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.`,
);
});
@@ -1,18 +0,0 @@
/**
* 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";
export interface GlobalOverride {
injectable: Injectable<any, any, any>;
overridingInstantiate: any;
}
export const getGlobalOverride = <T extends Injectable<any, any, any>>(
injectable: T,
overridingInstantiate: T["instantiate"],
) => ({
injectable,
overridingInstantiate,
});
@@ -5,7 +5,7 @@
import fse from "fs-extra";
import directoryForUserDataInjectable from "../app-paths/directory-for-user-data/directory-for-user-data.injectable";
import { isErrnoException } from "../utils";
import { isErrnoException } from "@k8slens/utilities";
import { getInjectable } from "@ogre-tools/injectable";
import joinPathsInjectable from "../path/join-paths.injectable";
@@ -6,7 +6,7 @@
import { action, observable, makeObservable, isObservableArray, isObservableSet, isObservableMap } from "mobx";
import type { BaseStoreDependencies } from "../base-store/base-store";
import { BaseStore } from "../base-store/base-store";
import { getOrInsertSet, toggle, toJS, object } from "../../renderer/utils";
import { getOrInsertSet, toggle, object } from "@k8slens/utilities";
import type { UserPreferencesModel, StoreType } from "./preferences-helpers";
import type { EmitAppEvent } from "../app-event-bus/emit-event.injectable";
@@ -14,6 +14,7 @@ import type { EmitAppEvent } from "../app-event-bus/emit-event.injectable";
import type { SelectedUpdateChannel } from "../../features/application-update/common/selected-update-channel/selected-update-channel.injectable";
import type { ReleaseChannel } from "../../features/application-update/common/update-channels";
import type { PreferenceDescriptors } from "./preference-descriptors.injectable";
import { toJS } from "../utils";
export interface UserStoreModel {
preferences: UserPreferencesModel;
@@ -1,128 +0,0 @@
/**
* 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();
});
});
@@ -1,94 +0,0 @@
/**
* 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");
});
});
});
@@ -1,512 +0,0 @@
/**
* 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 initializable", () => {
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 initializable", () => {
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,
});
});
});
@@ -1,68 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { join, nth, reduce, concat } from "@k8slens/utilities/src/iter";
describe("iter", () => {
describe("reduce", () => {
it("can reduce a value", () => {
expect(reduce([1, 2, 3], (acc: number[], current: number) => [current, ...acc], [0])).toEqual([3, 2, 1, 0]);
});
it("can reduce an empty iterable", () => {
expect(reduce([], (acc: number[], current: number) => [acc[0] + current], [])).toEqual([]);
});
});
describe("join", () => {
it("should not prefix the output by the seperator", () => {
expect(join(["a", "b", "c"].values(), " ")).toBe("a b c");
});
it("should return empty string if iterator is empty", () => {
expect(join([].values(), " ")).toBe("");
});
it("should return just first entry if iterator is of size 1", () => {
expect(join(["d"].values(), " ")).toBe("d");
});
});
describe("nth", () => {
it("should return undefined past the end of the iterator", () => {
expect(nth(["a"], 123)).toBeUndefined();
});
it("should by 0-indexing the index", () => {
expect(nth(["a", "b"], 0)).toBe("a");
});
});
describe("concat", () => {
it("should yield undefined for empty args", () => {
const iter = concat();
expect(iter.next()).toEqual({ done: true });
});
it("should yield undefined for only empty args", () => {
const iter = concat([].values(), [].values(), [].values(), [].values());
expect(iter.next()).toEqual({ done: true });
});
it("should yield all of the first and then all of the second", () => {
const iter = concat([1, 2, 3].values(), [4, 5, 6].values());
expect(iter.next()).toEqual({ done: false, value: 1 });
expect(iter.next()).toEqual({ done: false, value: 2 });
expect(iter.next()).toEqual({ done: false, value: 3 });
expect(iter.next()).toEqual({ done: false, value: 4 });
expect(iter.next()).toEqual({ done: false, value: 5 });
expect(iter.next()).toEqual({ done: false, value: 6 });
expect(iter.next()).toEqual({ done: true });
});
});
});
@@ -1,39 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { nFircate } from "../n-fircate";
describe("nFircate", () => {
it("should produce an empty array if no parts are provided", () => {
expect(nFircate([{ a: 1 }, { a: 2 }], "a", []).length).toBe(0);
});
it("should ignore non-matching parts", () => {
const res = 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 = 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 {
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);
}
});
});
@@ -1,66 +0,0 @@
/**
* 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]);
});
});
@@ -1,43 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { tuple } from "../../utils";
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]],
});
});
});
});
@@ -1,32 +0,0 @@
/**
* 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`);
});
});
@@ -1,58 +0,0 @@
/**
* 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),
};
}
+3
View File
@@ -13,6 +13,9 @@
import * as mobx from "mobx";
import { isObservable, observable } from "mobx";
/**
* @deprecated Switch to doing toJS on each field instead
*/
export function toJS<T>(data: T): T {
// make data observable for recursive toJS()-output
if (typeof data === "object" && !isObservable(data)) {
@@ -7,7 +7,7 @@ import type { ExtensionLoader } from "../extension-loader";
import extensionLoaderInjectable from "../extension-loader/extension-loader.injectable";
import { runInAction } from "mobx";
import updateExtensionsStateInjectable from "../extension-loader/update-extensions-state/update-extensions-state.injectable";
import { delay } from "../../renderer/utils";
import { delay } from "@k8slens/utilities";
import { getDiForUnitTesting } from "../../renderer/getDiForUnitTesting";
import ipcRendererInjectable from "../../renderer/utils/channel/ipc-renderer.injectable";
import type { IpcRenderer } from "electron";
@@ -8,11 +8,49 @@ import buildVersionInjectable from "../../main/vars/build-version/build-version.
import { asLegacyGlobalFunctionForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-function-for-extension-api";
import { getLegacyGlobalDiForExtensionApi } from "../as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
export { Singleton } from "../../common/utils";
export { prevDefault, stopPropagation } from "../../renderer/utils/prevDefault";
export { Singleton } from "../../common/utils/singleton";
export type { IClassName, IgnoredClassNames } from "../../renderer/utils";
export { cssNames } from "../../renderer/utils/cssNames";
export {
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
prevDefault,
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
stopPropagation,
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
cssNames,
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
disposer,
} from "@k8slens/utilities";
export type {
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
IClassName,
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
IgnoredClassNames,
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
Disposer,
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
Disposable,
/**
* @deprecated Switch to using the `@k8slens/utilities` package
*/
ExtendableDisposer,
} from "@k8slens/utilities";
export type { OpenLinkInBrowser } from "../../common/utils/open-link-in-browser.injectable";
@@ -24,6 +62,3 @@ export const getAppVersion = () => {
return di.inject(buildVersionInjectable).get();
};
export { disposer } from "../../common/utils";
export type { Disposer, Disposable, ExtendableDisposer } from "../../common/utils";
@@ -9,7 +9,7 @@ import extensionDiscoveryInjectable from "../extension-discovery/extension-disco
import type { ExtensionDiscovery } from "../extension-discovery/extension-discovery";
import installExtensionInjectable from "../install-extension/install-extension.injectable";
import directoryForUserDataInjectable from "../../common/app-paths/directory-for-user-data/directory-for-user-data.injectable";
import { delay } from "../../renderer/utils";
import { delay } from "@k8slens/utilities";
import { observable, runInAction, when } from "mobx";
import readJsonFileInjectable from "../../common/fs/read-json-file.injectable";
import pathExistsInjectable from "../../common/fs/path-exists.injectable";
@@ -7,7 +7,8 @@ import { ipcRenderer } from "electron";
import { EventEmitter } from "events";
import { makeObservable, observable, reaction, when } from "mobx";
import { broadcastMessage, ipcMainHandle, ipcRendererOn } from "../../common/ipc";
import { isErrnoException, toJS } from "../../common/utils";
import { toJS } from "../../common/utils";
import { isErrnoException } from "@k8slens/utilities";
import type { ExtensionsStore } from "../extensions-store/extensions-store";
import type { ExtensionLoader } from "../extension-loader";
import type { LensExtensionId, LensExtensionManifest } from "../lens-extension";
@@ -4,8 +4,8 @@
*/
import { action, computed, observable } from "mobx";
import { disposer } from "../../renderer/utils";
import type { ExtendableDisposer } from "../../renderer/utils";
import { disposer } from "@k8slens/utilities";
import type { ExtendableDisposer } from "@k8slens/utilities";
import * as uuid from "uuid";
import { broadcastMessage } from "../../common/ipc";
import { ipcRenderer } from "electron";
@@ -6,9 +6,9 @@
import { ipcMain, ipcRenderer } from "electron";
import { isEqual } from "lodash";
import type { ObservableMap } from "mobx";
import { action, computed, makeObservable, observable, observe, reaction, when } from "mobx";
import { action, computed, makeObservable, toJS, observable, observe, reaction, when } from "mobx";
import { broadcastMessage, ipcMainOn, ipcRendererOn, ipcMainHandle } from "../../common/ipc";
import { isDefined, toJS } from "../../common/utils";
import { isDefined } from "@k8slens/utilities";
import type { InstalledExtension } from "../extension-discovery/extension-discovery";
import type { LensExtension, LensExtensionConstructor, LensExtensionId } from "../lens-extension";
import type { LensExtensionState } from "../extensions-store/extensions-store";
@@ -6,7 +6,7 @@ import type { Injectable } from "@ogre-tools/injectable";
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
import { difference, find, map } from "lodash";
import { reaction, runInAction } from "mobx";
import { disposer } from "../../../common/utils/disposer";
import { disposer } from "@k8slens/utilities";
import type { LensExtension } from "../../lens-extension";
import { extensionRegistratorInjectionToken } from "../extension-registrator-injection-token";
@@ -43,7 +43,7 @@ const extensionInjectable = getInjectable({
reactionDisposer.push(
// injectables is either an array or a computed array, in which case
// we need to update the registered injectables with a reaction every time they change
// we need to update the registered injectables with a reaction every time they change
reaction(
() => Array.isArray(injectables) ? injectables : injectables.get(),
(currentInjectables, previousInjectables = []) => {
@@ -5,7 +5,7 @@
import { getInjectable } from "@ogre-tools/injectable";
import { getOrInsert } from "../../../common/utils";
import { getOrInsert } from "@k8slens/utilities";
import randomBytesInjectable from "../../../common/utils/random-bytes.injectable";
import joinPathsInjectable from "../../../common/path/join-paths.injectable";
import directoryForExtensionDataInjectable from "./directory-for-extension-data.injectable";
@@ -8,7 +8,6 @@ import { action, makeObservable } from "mobx";
import type { BaseStoreDependencies } from "../../../common/base-store/base-store";
import { BaseStore } from "../../../common/base-store/base-store";
import type { LensExtensionId } from "../../lens-extension";
import { toJS } from "../../../common/utils";
import type { EnsureHashedDirectoryForExtension } from "./ensure-hashed-directory-for-extension.injectable";
interface FSProvisionModel {
@@ -46,8 +45,8 @@ export class FileSystemProvisionerStore extends BaseStore<FSProvisionModel> {
}
toJSON(): FSProvisionModel {
return toJS({
extensions: Object.fromEntries(this.dependencies.registeredExtensions),
});
return {
extensions: Object.fromEntries(this.dependencies.registeredExtensions.toJSON()),
};
}
}
@@ -8,8 +8,8 @@ import { BaseStore } from "../common/base-store/base-store";
import * as path from "path";
import type { LensExtension } from "./lens-extension";
import assert from "assert";
import type { StaticThis } from "../common/utils";
import { getOrInsertWith } from "../common/utils";
import type { StaticThis } from "../common/utils/singleton";
import { getOrInsertWith } from "@k8slens/utilities";
import { getLegacyGlobalDiForExtensionApi } from "./as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import directoryForUserDataInjectable from "../common/app-paths/directory-for-user-data/directory-for-user-data.injectable";
import getConfigurationFileModelInjectable from "../common/get-configuration-file-model/get-configuration-file-model.injectable";
@@ -5,7 +5,6 @@
import type { LensExtensionId } from "../lens-extension";
import { action, computed, makeObservable, observable } from "mobx";
import { toJS } from "../../common/utils";
import type { BaseStoreDependencies } from "../../common/base-store/base-store";
import { BaseStore } from "../../common/base-store/base-store";
@@ -57,8 +56,8 @@ export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
}
toJSON(): LensExtensionsStoreModel {
return toJS({
extensions: Object.fromEntries(this.state),
});
return {
extensions: Object.fromEntries(this.state.toJSON()),
};
}
}
@@ -13,7 +13,7 @@ import joinPathsInjectable from "../../common/path/join-paths.injectable";
import type { PackageJson } from "../common-api";
import writeJsonFileInjectable from "../../common/fs/write-json-file.injectable";
import { once } from "lodash";
import { isErrnoException } from "../../common/utils";
import { isErrnoException } from "@k8slens/utilities";
const baseNpmInstallArgs = [
"install",
+1 -1
View File
@@ -6,7 +6,7 @@ import { ipcMain } from "electron";
import { IpcPrefix, IpcRegistrar } from "./ipc-registrar";
import { Disposers, lensExtensionDependencies } from "../lens-extension";
import type { LensMainExtension } from "../lens-main-extension";
import type { Disposer } from "../../common/utils";
import type { Disposer } from "@k8slens/utilities";
import { once } from "lodash";
import { ipcMainHandle } from "../../common/ipc";
@@ -2,7 +2,7 @@
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { Singleton } from "../../common/utils";
import { Singleton } from "../../common/utils/singleton";
import type { LensExtension } from "../lens-extension";
import { createHash } from "crypto";
import { broadcastMessage } from "../../common/ipc";
@@ -6,7 +6,7 @@ import { ipcRenderer } from "electron";
import { IpcPrefix, IpcRegistrar } from "./ipc-registrar";
import { Disposers } from "../lens-extension";
import type { LensRendererExtension } from "../lens-renderer-extension";
import type { Disposer } from "../../common/utils";
import type { Disposer } from "@k8slens/utilities";
import { once } from "lodash";
export abstract class IpcRenderer extends IpcRegistrar {
Loaded 100 of 410 files, more files were not shown because too many files have changed in this diff. Show more