diff --git a/.github/workflows/cicd.yml b/.github/workflows/cicd.yml index 284acd36..0d35cc84 100644 --- a/.github/workflows/cicd.yml +++ b/.github/workflows/cicd.yml @@ -15,19 +15,29 @@ jobs: steps: - name: Checkout this repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: lfs: true - - name: Checkout actions repository - uses: actions/checkout@v4 + - name: Checkout multi-consumer root + uses: actions/checkout@v7 with: - repository: Exabyte-io/actions + repository: mat3ra/web-app + # TODO: use main after references runner lands on web-app main + ref: chore/SOF-7942 token: ${{ secrets.BOT_GITHUB_TOKEN }} - path: actions + path: root + + - name: Initialize multi-consumer root + uses: ./root/.github/actions/init-multi-consumer-root + with: + multi-consumer-root: root + ssh-private-key: ${{ secrets.BOT_GITHUB_KEY }} + # TODO: drop actions-ref after post-npm-install lands on actions main + actions-ref: chore/SOF-7942 - name: Run ruff linter - uses: ./actions/py/lint + uses: ./root/reference/actions/py/lint with: python-version: ${{ matrix.python-version }} @@ -43,19 +53,27 @@ jobs: steps: - name: Checkout this repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: lfs: true - - name: Checkout actions repository - uses: actions/checkout@v4 + - name: Checkout multi-consumer root + uses: actions/checkout@v7 with: - repository: Exabyte-io/actions + repository: mat3ra/web-app + ref: chore/SOF-7942 token: ${{ secrets.BOT_GITHUB_TOKEN }} - path: actions + path: root + + - name: Initialize multi-consumer root + uses: ./root/.github/actions/init-multi-consumer-root + with: + multi-consumer-root: root + ssh-private-key: ${{ secrets.BOT_GITHUB_KEY }} + actions-ref: chore/SOF-7942 - name: Run python unit tests - uses: ./actions/py/pytest + uses: ./root/reference/actions/py/pytest with: python-version: ${{ matrix.python-version }} unit-test-directory: tests/py/unit @@ -70,28 +88,47 @@ jobs: - 22.x steps: - - name: Checkout this repository - uses: actions/checkout@v4 + - name: Checkout multi-consumer root + uses: actions/checkout@v7 with: + repository: mat3ra/web-app + # TODO: use main after references runner lands on web-app main + ref: chore/SOF-7942 + token: ${{ secrets.BOT_GITHUB_TOKEN }} + path: root lfs: true - - name: Checkout actions repository - uses: actions/checkout@v4 + - name: Checkout package under test + uses: actions/checkout@v7 with: - repository: Exabyte-io/actions - token: ${{ secrets.BOT_GITHUB_TOKEN }} - path: actions + path: root/reference/code + lfs: true + + - name: Initialize multi-consumer root + uses: ./root/.github/actions/init-multi-consumer-root + with: + multi-consumer-root: root + ssh-private-key: ${{ secrets.BOT_GITHUB_KEY }} + node-version: ${{ matrix.node-version }} + # TODO: drop actions-ref after post-npm-install lands on actions main + actions-ref: chore/SOF-7942 - name: Run JS validate - uses: ./actions/js/validate + uses: ./root/reference/actions/js/validate with: - node-version: "14.x" + node-version: ${{ matrix.node-version }} + package-directory: root/reference/code skip-eslint: "true" - name: Run JS tests - uses: ./actions/js/test + uses: ./root/reference/actions/js/test with: node-version: ${{ matrix.node-version }} + package-directory: root/reference/code + npm-options: "--legacy-peer-deps" + post-npm-install: | + npm run references:sync + npm run references:install publish-js-package: needs: @@ -103,17 +140,23 @@ jobs: steps: - name: Checkout this repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - - name: Checkout actions repository - uses: actions/checkout@v4 + - name: Checkout multi-consumer root + uses: actions/checkout@v7 with: - repository: Exabyte-io/actions + repository: mat3ra/web-app token: ${{ secrets.BOT_GITHUB_TOKEN }} - path: actions + path: root + + - name: Initialize multi-consumer root + uses: ./root/.github/actions/init-multi-consumer-root + with: + multi-consumer-root: root + ssh-private-key: ${{ secrets.BOT_GITHUB_KEY }} - name: Publish JS release - uses: ./actions/js/publish + uses: ./root/reference/actions/js/publish with: npm-token: ${{ secrets.NPM_TOKEN }} github-token: ${{ secrets.BOT_GITHUB_TOKEN }} @@ -128,54 +171,27 @@ jobs: steps: - name: Checkout this repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: lfs: true - - name: Checkout actions repository - uses: actions/checkout@v4 + - name: Checkout multi-consumer root + uses: actions/checkout@v7 with: - repository: Exabyte-io/actions + repository: mat3ra/web-app token: ${{ secrets.BOT_GITHUB_TOKEN }} - path: actions + path: root + + - name: Initialize multi-consumer root + uses: ./root/.github/actions/init-multi-consumer-root + with: + multi-consumer-root: root + ssh-private-key: ${{ secrets.BOT_GITHUB_KEY }} - name: Publish python release - uses: ./actions/py/publish + uses: ./root/reference/actions/py/publish with: python-version: 3.10.x github-token: ${{ secrets.BOT_GITHUB_TOKEN }} pypi-api-token: ${{ secrets.PYPI_API_TOKEN }} publish-tag: "false" -# TB disabled on 2024-03-21 as not practically useful at this time -# create-pr-in-a-dependant: -# needs: [publish-js-package] -# runs-on: ubuntu-latest -# if: (github.repository != 'Exabyte-io/template-definitions') && (github.ref_name == 'main') -# strategy: -# matrix: -# target-repository: -# - Exabyte-io/ade.js -# - Exabyte-io/application-flavors -# - Exabyte-io/ide.js -# - Exabyte-io/made.js -# - Exabyte-io/mode.js -# - Exabyte-io/prode.js -# - Exabyte-io/wode.js -# - Exabyte-io/materials-designer -# - Exabyte-io/web-app -# -# steps: -# - name: Checkout actions repository -# uses: actions/checkout@v4 -# with: -# repository: Exabyte-io/actions -# token: ${{ secrets.BOT_GITHUB_TOKEN }} -# path: actions -# -# - name: Create a PR -# uses: ./actions/git/pull-request -# with: -# github-token: ${{ secrets.BOT_GITHUB_TOKEN }} -# target-repository: ${{ matrix.target-repository }} -# source-package-name: "@exabyte-io/code.js" -# target-version: ${{ needs.publish-js-package.outputs.release-version }} diff --git a/.gitignore b/.gitignore index ac246a98..8bcf0372 100644 --- a/.gitignore +++ b/.gitignore @@ -11,8 +11,8 @@ __pycache__/ *.so # Distribution / packaging -# "dist" folder is not ignored on purpose to be able to install intermediate changes from github commits -# dist +# Built by `npm run transpile` (references:install / publish / local). +dist/ .Python build/ develop-eggs/ diff --git a/.husky/pre-commit b/.husky/pre-commit index 7584373c..6d395b88 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -2,5 +2,3 @@ . "$(dirname "$0")/_/husky.sh" npm run lint:fix -npm run transpile -git add dist diff --git a/dist/js/ArrayWithIds.d.ts b/dist/js/ArrayWithIds.d.ts deleted file mode 100644 index d5c6d322..00000000 --- a/dist/js/ArrayWithIds.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { RoundingOptions, ValueWithId } from "./ValueWithId"; -export declare class ArrayWithIds { - values: T[]; - ids: number[]; - constructor(values?: T[], ids?: number[]); - static fromValues>(this: new (values: U[], ids: number[]) => C, values: U[]): C; - static fromObjects>(this: new (values: U[], ids: number[]) => C, objects: { - id: number; - value: U; - }[]): C; - toJSON(): object[]; - toValueWithIdArray(): ValueWithId[]; - getElementValueById(id: number): T | undefined; - getElementValueByIndex(index: number): T | undefined; - getElementIdByIndex(index: number): number | undefined; - getElementIdByValue(value: T): number | undefined; - filterByValues(valuesToKeep: T | T[]): void; - filterByIndices(indices: number | number[]): void; - filterByIds(ids: number | number[], invert?: boolean): void; - equals(other: ArrayWithIds): boolean; - mapArrayInPlace(func: (value: T) => T): void; - addItem(value: T, id?: number): void; - removeItem(index: number, id?: number): void; -} -export declare class RoundedArrayWithIds extends ArrayWithIds { - readonly roundingOptions: RoundingOptions; - constructor(values?: T[], ids?: number[], options?: RoundingOptions); - toJSON(): object[]; -} diff --git a/dist/js/ArrayWithIds.js b/dist/js/ArrayWithIds.js deleted file mode 100644 index e227fc15..00000000 --- a/dist/js/ArrayWithIds.js +++ /dev/null @@ -1,119 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoundedArrayWithIds = exports.ArrayWithIds = void 0; -const ValueWithId_1 = require("./ValueWithId"); -class ArrayWithIds { - constructor(values = [], ids = []) { - if (values.length !== ids.length) { - throw new Error("Values and IDs must have the same length"); - } - this.values = [...values]; - this.ids = [...ids]; - } - static fromValues(values) { - const ids = values.map((_, i) => i); - return new this(values, ids); - } - static fromObjects(objects) { - const values = objects.map((obj) => obj.value); - const ids = objects.map((obj) => obj.id); - return new this(values, ids); - } - toJSON() { - return this.values.map((value, index) => ({ - id: this.ids[index], - value: value !== null && - typeof value === "object" && - "toJSON" in value && - typeof value.toJSON === "function" - ? value.toJSON() - : value, - })); - } - toValueWithIdArray() { - return this.values.map((value, index) => ValueWithId_1.ValueWithId.fromValueAndId(value, this.ids[index])); - } - getElementValueById(id) { - const index = this.ids.indexOf(id); - return index !== -1 ? this.values[index] : undefined; - } - getElementValueByIndex(index) { - return this.values[index]; - } - getElementIdByIndex(index) { - return this.ids[index] || undefined; - } - getElementIdByValue(value) { - const index = this.values.findIndex((v) => Array.isArray(v) && Array.isArray(value) - ? v.length === value.length && v.every((val, idx) => val === value[idx]) - : v === value); - return index !== -1 ? this.ids[index] : undefined; - } - filterByValues(valuesToKeep) { - const toHash = (v) => (Array.isArray(v) ? JSON.stringify(v) : String(v)); - const keepSet = new Set(Array.isArray(valuesToKeep) ? valuesToKeep.map(toHash) : [toHash(valuesToKeep)]); - const filtered = this.values - .map((value, i) => [value, this.ids[i]]) - .filter(([value]) => keepSet.has(toHash(value))); - this.values = filtered.map(([v]) => v); - this.ids = filtered.map(([_, id]) => id); - } - filterByIndices(indices) { - const keepSet = new Set(Array.isArray(indices) ? indices : [indices]); - this.values = this.values.filter((_, i) => keepSet.has(i)); - this.ids = this.ids.filter((_, i) => keepSet.has(i)); - } - filterByIds(ids, invert = false) { - const idSet = new Set(Array.isArray(ids) ? ids : [ids]); - const keep = invert - ? this.ids.map((id, i) => (idSet.has(id) ? -1 : i)).filter((i) => i >= 0) - : this.ids.map((id, i) => (idSet.has(id) ? i : -1)).filter((i) => i >= 0); - this.values = keep.map((i) => this.values[i]); - this.ids = keep.map((i) => this.ids[i]); - } - equals(other) { - if (!(other instanceof ArrayWithIds)) - return false; - if (this.values.length !== other.values.length) - return false; - if (this.ids.length !== other.ids.length) - return false; - return (this.values.every((v, i) => { - const ov = other.values[i]; - return Array.isArray(v) && Array.isArray(ov) - ? v.length === ov.length && v.every((val, idx) => val === ov[idx]) - : v === ov; - }) && this.ids.every((id, i) => id === other.ids[i])); - } - mapArrayInPlace(func) { - this.values = this.values.map(func); - } - addItem(value, id) { - const newId = id !== null && id !== void 0 ? id : Math.max(-1, ...this.ids) + 1; - this.values.push(value); - this.ids.push(newId); - } - removeItem(index, id) { - if (id !== undefined) { - index = this.ids.indexOf(id); - if (index === -1) - throw new Error("ID not found"); - } - if (index < 0 || index >= this.values.length) { - throw new Error("Index out of range"); - } - this.values.splice(index, 1); - this.ids.splice(index, 1); - } -} -exports.ArrayWithIds = ArrayWithIds; -class RoundedArrayWithIds extends ArrayWithIds { - constructor(values = [], ids = [], options = ValueWithId_1.defaultRoundingOptions) { - super(values, ids); - this.roundingOptions = options; - } - toJSON() { - return this.values.map((value, index) => new ValueWithId_1.RoundedValueWithId(this.ids[index], value, this.roundingOptions).toJSON()); - } -} -exports.RoundedArrayWithIds = RoundedArrayWithIds; diff --git a/dist/js/ValueWithId.d.ts b/dist/js/ValueWithId.d.ts deleted file mode 100644 index 2e3c67a2..00000000 --- a/dist/js/ValueWithId.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { ObjectWithIdAndValueSchema } from "@mat3ra/esse/dist/js/types"; -import { RoundingMethodEnum } from "./math"; -interface ValueWithIdSchema { - id: ObjectWithIdAndValueSchema["id"]; - value: T | null; -} -export declare class ValueWithId { - id: number; - value: T | null; - static defaultConfig: { - id: number; - value: null; - }; - static fromValueAndId>(this: new (args: { - id: number; - value: U; - }) => C, value: U, id?: number): C; - constructor({ id, value }?: ValueWithIdSchema); - /** - * Converts the instance to a plain JavaScript object. - */ - toJSON(): object; - /** - * Checks if this instance is equal to another ValueWithId. - */ - equals(other: ValueWithId): boolean; -} -export interface RoundingOptions { - precision: number; - roundingMethod: RoundingMethodEnum; -} -export declare const defaultRoundingOptions: RoundingOptions; -export declare class RoundedValueWithId extends ValueWithId { - readonly precision: number; - readonly roundingMethod: RoundingMethodEnum; - constructor(id: number, value: T, options?: RoundingOptions); - toJSON(): object; -} -export {}; diff --git a/dist/js/ValueWithId.js b/dist/js/ValueWithId.js deleted file mode 100644 index 0f4d19ba..00000000 --- a/dist/js/ValueWithId.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoundedValueWithId = exports.defaultRoundingOptions = exports.ValueWithId = void 0; -const math_1 = require("./math"); -class ValueWithId { - static fromValueAndId(value, id = 0) { - return new this({ id, value }); - } - constructor({ id, value } = ValueWithId.defaultConfig) { - this.id = id; - this.value = value; - } - /** - * Converts the instance to a plain JavaScript object. - */ - toJSON() { - if (this.value !== null && - typeof this.value === "object" && - "toJSON" in this.value && - typeof this.value.toJSON === "function") { - return { id: this.id, value: this.value.toJSON() }; - } - return { id: this.id, value: this.value }; - } - /** - * Checks if this instance is equal to another ValueWithId. - */ - equals(other) { - if (!(other instanceof ValueWithId)) - return false; - // because U may differ from T, we cast to unknown when comparing - const v1 = this.value; - const v2 = other.value; - if (Array.isArray(v1) && Array.isArray(v2)) { - if (v1.length !== v2.length) - return false; - for (let i = 0; i < v1.length; i++) { - if (v1[i] !== v2[i]) - return false; - } - return this.id === other.id; - } - return this.id === other.id && v1 === v2; - } -} -exports.ValueWithId = ValueWithId; -ValueWithId.defaultConfig = { - id: 0, - value: null, -}; -exports.defaultRoundingOptions = { - precision: 9, - roundingMethod: math_1.RoundingMethodEnum.HalfAwayFromZero, -}; -class RoundedValueWithId extends ValueWithId { - constructor(id, value, options = exports.defaultRoundingOptions) { - super({ id, value }); - this.precision = options.precision; - this.roundingMethod = options.roundingMethod; - } - toJSON() { - return { - id: this.id, - value: math_1.math.roundArrayOrNumber(this.value, this.precision, this.roundingMethod), - }; - } -} -exports.RoundedValueWithId = RoundedValueWithId; diff --git a/dist/js/constants.d.ts b/dist/js/constants.d.ts deleted file mode 100644 index eb129258..00000000 --- a/dist/js/constants.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -export declare enum Units { - bohr = "bohr", - angstrom = "angstrom", - degree = "degree", - radian = "radian", - alat = "alat" -} -/** - * @summary Coordinates units for a material's basis. - */ -export declare enum AtomicCoordinateUnits { - crystal = "crystal", - cartesian = "cartesian" -} -export declare enum Tolerance { - length = 0.01, - lengthAngstrom = 0.001, - pointsDistance = 0.001 -} -export declare enum Coefficients { - EV_TO_RY = 0.0734986176, - BOHR_TO_ANGSTROM = 0.52917721092, - ANGSTROM_TO_BOHR = 1.8897261245650618, - EV_A_TO_RY_BOHR = 0.03889379346800142 -} -export declare const HASH_TOLERANCE: 3; -export declare const coefficients: { - EV_TO_RY: number; - BOHR_TO_ANGSTROM: number; - ANGSTROM_TO_BOHR: number; - EV_A_TO_RY_BOHR: number; -}; -export declare const tolerance: { - length: number; - lengthAngstrom: number; - pointsDistance: number; -}; -export declare const units: { - bohr: string; - angstrom: string; - degree: string; - radian: string; - alat: string; -}; -/** - * @summary Coordinates units for a material's basis. - */ -export declare const ATOMIC_COORD_UNITS: { - crystal: string; - cartesian: string; -}; -declare const _default: { - coefficients: { - EV_TO_RY: number; - BOHR_TO_ANGSTROM: number; - ANGSTROM_TO_BOHR: number; - EV_A_TO_RY_BOHR: number; - }; - tolerance: { - length: number; - lengthAngstrom: number; - pointsDistance: number; - }; - units: { - bohr: string; - angstrom: string; - degree: string; - radian: string; - alat: string; - }; - ATOMIC_COORD_UNITS: { - crystal: string; - cartesian: string; - }; -}; -export default _default; diff --git a/dist/js/constants.js b/dist/js/constants.js deleted file mode 100644 index faf3bc3d..00000000 --- a/dist/js/constants.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ATOMIC_COORD_UNITS = exports.units = exports.tolerance = exports.coefficients = exports.HASH_TOLERANCE = exports.Coefficients = exports.Tolerance = exports.AtomicCoordinateUnits = exports.Units = void 0; -var Units; -(function (Units) { - Units["bohr"] = "bohr"; - Units["angstrom"] = "angstrom"; - Units["degree"] = "degree"; - Units["radian"] = "radian"; - Units["alat"] = "alat"; -})(Units || (exports.Units = Units = {})); -/** - * @summary Coordinates units for a material's basis. - */ -var AtomicCoordinateUnits; -(function (AtomicCoordinateUnits) { - AtomicCoordinateUnits["crystal"] = "crystal"; - AtomicCoordinateUnits["cartesian"] = "cartesian"; -})(AtomicCoordinateUnits || (exports.AtomicCoordinateUnits = AtomicCoordinateUnits = {})); -// in crystal coordinates -var Tolerance; -(function (Tolerance) { - Tolerance[Tolerance["length"] = 0.01] = "length"; - Tolerance[Tolerance["lengthAngstrom"] = 0.001] = "lengthAngstrom"; - Tolerance[Tolerance["pointsDistance"] = 0.001] = "pointsDistance"; -})(Tolerance || (exports.Tolerance = Tolerance = {})); -var Coefficients; -(function (Coefficients) { - Coefficients[Coefficients["EV_TO_RY"] = 0.0734986176] = "EV_TO_RY"; - Coefficients[Coefficients["BOHR_TO_ANGSTROM"] = 0.52917721092] = "BOHR_TO_ANGSTROM"; - Coefficients[Coefficients["ANGSTROM_TO_BOHR"] = 1.8897261245650618] = "ANGSTROM_TO_BOHR"; - Coefficients[Coefficients["EV_A_TO_RY_BOHR"] = 0.03889379346800142] = "EV_A_TO_RY_BOHR"; -})(Coefficients || (exports.Coefficients = Coefficients = {})); -// Only 3 digits will be considered for lattice and basis params on hashing -exports.HASH_TOLERANCE = 3; -// TODO: remove everything below this line -exports.coefficients = { - EV_TO_RY: 0.0734986176, - BOHR_TO_ANGSTROM: 0.52917721092, - ANGSTROM_TO_BOHR: 1 / 0.52917721092, - EV_A_TO_RY_BOHR: 1 / 25.71104309541616, -}; -exports.tolerance = { - // in crystal coordinates - length: 0.01, - lengthAngstrom: 0.001, - pointsDistance: 0.001, -}; -exports.units = { - bohr: "bohr", - angstrom: "angstrom", - degree: "degree", - radian: "radian", - alat: "alat", -}; -/** - * @summary Coordinates units for a material's basis. - */ -exports.ATOMIC_COORD_UNITS = { - crystal: "crystal", - cartesian: "cartesian", -}; -exports.default = { - coefficients: exports.coefficients, - tolerance: exports.tolerance, - units: exports.units, - ATOMIC_COORD_UNITS: exports.ATOMIC_COORD_UNITS, -}; diff --git a/dist/js/context/index.d.ts b/dist/js/context/index.d.ts deleted file mode 100644 index 1a1ae105..00000000 --- a/dist/js/context/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { JobContextPickKeysForMixin, WorkflowContextPickKeysForMixin } from "./pickers"; -export { JobContextPickKeysForMixin, WorkflowContextPickKeysForMixin }; diff --git a/dist/js/context/index.js b/dist/js/context/index.js deleted file mode 100644 index 40362a12..00000000 --- a/dist/js/context/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WorkflowContextPickKeysForMixin = exports.JobContextPickKeysForMixin = void 0; -const pickers_1 = require("./pickers"); -Object.defineProperty(exports, "JobContextPickKeysForMixin", { enumerable: true, get: function () { return pickers_1.JobContextPickKeysForMixin; } }); -Object.defineProperty(exports, "WorkflowContextPickKeysForMixin", { enumerable: true, get: function () { return pickers_1.WorkflowContextPickKeysForMixin; } }); diff --git a/dist/js/context/pickers.d.ts b/dist/js/context/pickers.d.ts deleted file mode 100644 index d199313b..00000000 --- a/dist/js/context/pickers.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export function WorkflowContextPickKeysForMixin(workflow: any): { - workflow: Pick; -}; -export function JobContextPickKeysForMixin(job: any): { - job: Pick; -}; diff --git a/dist/js/context/pickers.js b/dist/js/context/pickers.js deleted file mode 100644 index 469869c5..00000000 --- a/dist/js/context/pickers.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JobContextPickKeysForMixin = exports.WorkflowContextPickKeysForMixin = void 0; -const underscore_1 = __importDefault(require("underscore")); -const WorkflowContextPickKeysForMixin = (workflow) => { - return { - workflow: underscore_1.default.pick(workflow, ["hasRelaxation"]), - }; -}; -exports.WorkflowContextPickKeysForMixin = WorkflowContextPickKeysForMixin; -const JobContextPickKeysForMixin = (job) => { - return { - job: underscore_1.default.pick(job, ["parentJob"]), - }; -}; -exports.JobContextPickKeysForMixin = JobContextPickKeysForMixin; diff --git a/dist/js/entity/in_memory.d.ts b/dist/js/entity/in_memory.d.ts deleted file mode 100644 index 44075a26..00000000 --- a/dist/js/entity/in_memory.d.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { JSONSchema } from "@mat3ra/esse/dist/js/esse/utils"; -import { BaseInMemoryEntitySchema, EntityReferenceSchema } from "@mat3ra/esse/dist/js/types"; -export declare enum ValidationErrorCode { - IN_MEMORY_ENTITY_DATA_INVALID = "IN_MEMORY_ENTITY_DATA_INVALID", - ENTITY_REFERENCE_ERROR = "ENTITY_REFERENCE_ERROR", - REQUIRED_PROPERTY_MISSING = "REQUIRED_PROPERTY_MISSING" -} -interface ErrorDetails { - error?: object | null; - json: object; - schema: JSONSchema; -} -export declare class EntityError extends Error { - code: string; - details?: ErrorDetails; - constructor({ code, details }: { - code: ValidationErrorCode; - details?: ErrorDetails; - }); -} -type Schema = BaseInMemoryEntitySchema; -export declare class InMemoryEntity implements Schema { - static create>(config: Schema): T; - static _isDeepCloneRequired: boolean; - static allowJsonSchemaTypesCoercing: boolean; - static readonly jsonSchema?: JSONSchema; - _json: S; - constructor(config: NoInfer); - prop(name: K, defaultValue: S[K]): S[K]; - prop(name: K): S[K] | undefined; - /** - * @summary Return a required prop, throwing an error if it doesn't exist or is undefined/null - */ - requiredProp(name: K): S[K]; - /** - * @summary Set a prop - */ - setProp(name: keyof S, value: S[typeof name]): void; - /** - * @summary Remove a prop - */ - unsetProp(name: keyof S): void; - /** - * Updates internal JSON. Works the same as Mongo's $set operator - * @see https://www.mongodb.com/docs/manual/reference/operator/update/set/#-set - */ - setProps(json?: Partial): this; - /** - * @summary Array of fields to exclude from resulted JSON. - * JSON.stringify calls `toJSON(key)` with the parent property name (a string). - * Only an actual array is treated as an omit list — otherwise stringify would - * strip fields whose names match the property key (e.g. systemTeams.owner). - */ - toJSON(exclude?: (keyof S)[]): S; - toJSONSafe(exclude?: (keyof S)[]): S; - toJSONQuick(exclude?: (keyof S)[]): S; - /** - * @summary Clone this entity - */ - clone(extraContext?: object): this; - static validateData(data: object, clean?: boolean, jsonSchema?: import("json-schema").JSONSchema7 | undefined): object; - /** - * @summary Validate entity contents against schema - */ - validate(): void; - clean(config: S): S; - isValid(): boolean; - static get cls(): string; - get cls(): string; - getClsName(): string; - /** - * @summary get small identifying payload of object - * @param byIdOnly if true, return only the id - * @returns identifying data - */ - getAsEntityReference(byIdOnly: true): { - _id: NonNullable; - }; - getAsEntityReference(byIdOnly?: false): EntityReferenceSchema & { - _id: string; - cls: string; - }; - get id(): S["_id"]; - set id(id: S["_id"]); - get _id(): S["_id"]; - set _id(id: S["_id"]); - get schemaVersion(): S["schemaVersion"]; - set schemaVersion(schemaVersion: S["schemaVersion"]); - get systemName(): S["systemName"]; - set systemName(systemName: S["systemName"]); - get slug(): S["slug"] | undefined; - get isSystemEntity(): boolean; -} -export type InMemoryEntityConstructor = new (...args: any[]) => T; -export {}; diff --git a/dist/js/entity/in_memory.js b/dist/js/entity/in_memory.js deleted file mode 100644 index ea92daaa..00000000 --- a/dist/js/entity/in_memory.js +++ /dev/null @@ -1,268 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemoryEntity = exports.EntityError = exports.ValidationErrorCode = void 0; -const ajv = __importStar(require("@mat3ra/esse/dist/js/utils/ajv")); -const get_1 = __importDefault(require("lodash/get")); -const omit_1 = __importDefault(require("lodash/omit")); -const set_1 = __importDefault(require("lodash/set")); -const clone_1 = require("../utils/clone"); -var ValidationErrorCode; -(function (ValidationErrorCode) { - ValidationErrorCode["IN_MEMORY_ENTITY_DATA_INVALID"] = "IN_MEMORY_ENTITY_DATA_INVALID"; - ValidationErrorCode["ENTITY_REFERENCE_ERROR"] = "ENTITY_REFERENCE_ERROR"; - ValidationErrorCode["REQUIRED_PROPERTY_MISSING"] = "REQUIRED_PROPERTY_MISSING"; -})(ValidationErrorCode || (exports.ValidationErrorCode = ValidationErrorCode = {})); -class EntityError extends Error { - constructor({ code, details }) { - super(code); - this.code = code; - this.details = details; - } -} -exports.EntityError = EntityError; -class InMemoryEntity { - static create(config) { - return new this.prototype.constructor(config); - } - // NoInfer: keep default S (or an explicit type arg) instead of inferring S from the config literal. - constructor(config) { - this._json = this.constructor._isDeepCloneRequired - ? (0, clone_1.deepClone)(config) - : (0, clone_1.clone)(config); - } - /** - * @summary Return a prop or the default - */ - prop(name, defaultValue) { - var _a; - // `lodash.get` gets `null` when the value is `null`, but we still want a default value in this case, hence `??` - return (_a = (0, get_1.default)(this._json, name, defaultValue)) !== null && _a !== void 0 ? _a : defaultValue; - } - /** - * @summary Return a required prop, throwing an error if it doesn't exist or is undefined/null - */ - requiredProp(name) { - const value = this.prop(name); - if (value === undefined || value === null) { - throw new EntityError({ - code: ValidationErrorCode.REQUIRED_PROPERTY_MISSING, - details: { - error: null, - json: this._json, - schema: this.constructor.jsonSchema || {}, - }, - }); - } - return value; - } - /** - * @summary Set a prop - */ - setProp(name, value) { - // lodash.set is required to support dot-notation in keys (e.g. "compute.cluster.fqdn") - (0, set_1.default)(this._json, name, value); - } - /** - * @summary Remove a prop - */ - unsetProp(name) { - delete this._json[name]; - } - /** - * Updates internal JSON. Works the same as Mongo's $set operator - * @see https://www.mongodb.com/docs/manual/reference/operator/update/set/#-set - */ - setProps(json = {}) { - Object.entries(json).forEach(([key, value]) => { - const keyType = key; - this.setProp(keyType, value); - }); - return this; - } - /** - * @summary Array of fields to exclude from resulted JSON. - * JSON.stringify calls `toJSON(key)` with the parent property name (a string). - * Only an actual array is treated as an omit list — otherwise stringify would - * strip fields whose names match the property key (e.g. systemTeams.owner). - */ - toJSON(exclude = []) { - const omitKeys = Array.isArray(exclude) ? exclude : []; - return this.constructor._isDeepCloneRequired - ? this.toJSONSafe(omitKeys) - : this.toJSONQuick(omitKeys); - } - toJSONSafe(exclude = []) { - const omitKeys = Array.isArray(exclude) ? exclude : []; - return this.clean((0, clone_1.deepClone)((0, omit_1.default)(this._json, omitKeys))); - } - toJSONQuick(exclude = []) { - const omitKeys = Array.isArray(exclude) ? exclude : []; - return this.clean((0, clone_1.clone)((0, omit_1.default)(this._json, omitKeys))); - } - /** - * @summary Clone this entity - */ - clone(extraContext) { - return new this.constructor({ - ...this.toJSON(), - ...extraContext, - }); - } - static validateData(data, clean = false, jsonSchema = this.jsonSchema) { - if (!jsonSchema) { - return data; - } - const result = clean - ? ajv.validateAndClean(data, jsonSchema, { - coerceTypes: this.allowJsonSchemaTypesCoercing, - }) - : ajv.validate(data, jsonSchema); - if (!result.isValid) { - throw new EntityError({ - code: ValidationErrorCode.IN_MEMORY_ENTITY_DATA_INVALID, - details: { - error: result === null || result === void 0 ? void 0 : result.errors, - json: data, - schema: jsonSchema, - }, - }); - } - return data; - } - /** - * @summary Validate entity contents against schema - */ - validate() { - const ctr = this.constructor; - if (this._json) { - ctr.validateData(this._json); - } - } - clean(config) { - var _a, _b, _c; - try { - return this.constructor.validateData(config, true); - } - catch (err) { - if (err instanceof EntityError) { - console.error({ - error: JSON.stringify((_a = err.details) === null || _a === void 0 ? void 0 : _a.error), - json: JSON.stringify((_b = err.details) === null || _b === void 0 ? void 0 : _b.json), - schema: JSON.stringify((_c = err.details) === null || _c === void 0 ? void 0 : _c.schema), - }); - } - throw err; - } - } - isValid() { - try { - this.validate(); - return true; - } - catch (err) { - return false; - } - } - static get cls() { - return this.prototype.constructor.name; - } - get cls() { - return this.constructor.name; - } - // TODO: figure out why the above getter for `cls` returns `null` and use only one - getClsName() { - return this.constructor.name; - } - getAsEntityReference(byIdOnly = false) { - // Slug is usually present on entity references, but not required for all entities - // (e.g. workflows are not slugified). Only `_id` is required to form a reference. - if (!this._id) { - throw new EntityError({ - code: ValidationErrorCode.ENTITY_REFERENCE_ERROR, - details: { - json: this._json, - schema: this.constructor.jsonSchema || {}, - }, - }); - } - if (byIdOnly) { - return { _id: this._id }; - } - return { - _id: this._id, - ...(this.slug !== undefined ? { slug: this.slug } : {}), - cls: this.getClsName(), - }; - } - // Properties from BaseInMemoryEntitySchema - get id() { - return this.prop("_id"); - } - set id(id) { - this.setProp("_id", id); - } - get _id() { - return this.prop("_id"); - } - set _id(id) { - this.setProp("_id", id); - } - get schemaVersion() { - return this.prop("schemaVersion"); - } - set schemaVersion(schemaVersion) { - this.setProp("schemaVersion", schemaVersion); - } - get systemName() { - return this.prop("systemName"); - } - set systemName(systemName) { - this.setProp("systemName", systemName); - } - get slug() { - return this.prop("slug"); - } - get isSystemEntity() { - return Boolean(this.systemName); - } -} -exports.InMemoryEntity = InMemoryEntity; -// Override if deepClone of config is required -InMemoryEntity._isDeepCloneRequired = false; -InMemoryEntity.allowJsonSchemaTypesCoercing = false; diff --git a/dist/js/entity/index.d.ts b/dist/js/entity/index.d.ts deleted file mode 100644 index fee5d4c3..00000000 --- a/dist/js/entity/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { InMemoryEntity } from "./in_memory"; -import { DefaultableInMemoryEntity, HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity, HasMetadataNamedDefaultableInMemoryEntity, NamedDefaultableInMemoryEntity, NamedInMemoryEntity } from "./other"; -import { ENTITY_SET_TYPES } from "./set/enums"; -import { InMemoryEntitySetMixin } from "./set/mixins"; -import { orderedEntityInSetMixin, orderedEntitySetMixin } from "./set/ordered/mixins"; -import * as selectorsForEntitySet from "./set/selectors"; -export { InMemoryEntity, NamedInMemoryEntity, DefaultableInMemoryEntity, NamedDefaultableInMemoryEntity, HasMetadataNamedDefaultableInMemoryEntity, HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity, ENTITY_SET_TYPES, selectorsForEntitySet, InMemoryEntitySetMixin, orderedEntitySetMixin, orderedEntityInSetMixin, }; diff --git a/dist/js/entity/index.js b/dist/js/entity/index.js deleted file mode 100644 index 1c56aaef..00000000 --- a/dist/js/entity/index.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.orderedEntityInSetMixin = exports.orderedEntitySetMixin = exports.InMemoryEntitySetMixin = exports.selectorsForEntitySet = exports.ENTITY_SET_TYPES = exports.HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity = exports.HasMetadataNamedDefaultableInMemoryEntity = exports.NamedDefaultableInMemoryEntity = exports.DefaultableInMemoryEntity = exports.NamedInMemoryEntity = exports.InMemoryEntity = void 0; -const in_memory_1 = require("./in_memory"); -Object.defineProperty(exports, "InMemoryEntity", { enumerable: true, get: function () { return in_memory_1.InMemoryEntity; } }); -const other_1 = require("./other"); -Object.defineProperty(exports, "DefaultableInMemoryEntity", { enumerable: true, get: function () { return other_1.DefaultableInMemoryEntity; } }); -Object.defineProperty(exports, "HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity", { enumerable: true, get: function () { return other_1.HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity; } }); -Object.defineProperty(exports, "HasMetadataNamedDefaultableInMemoryEntity", { enumerable: true, get: function () { return other_1.HasMetadataNamedDefaultableInMemoryEntity; } }); -Object.defineProperty(exports, "NamedDefaultableInMemoryEntity", { enumerable: true, get: function () { return other_1.NamedDefaultableInMemoryEntity; } }); -Object.defineProperty(exports, "NamedInMemoryEntity", { enumerable: true, get: function () { return other_1.NamedInMemoryEntity; } }); -const enums_1 = require("./set/enums"); -Object.defineProperty(exports, "ENTITY_SET_TYPES", { enumerable: true, get: function () { return enums_1.ENTITY_SET_TYPES; } }); -const mixins_1 = require("./set/mixins"); -Object.defineProperty(exports, "InMemoryEntitySetMixin", { enumerable: true, get: function () { return mixins_1.InMemoryEntitySetMixin; } }); -const mixins_2 = require("./set/ordered/mixins"); -Object.defineProperty(exports, "orderedEntityInSetMixin", { enumerable: true, get: function () { return mixins_2.orderedEntityInSetMixin; } }); -Object.defineProperty(exports, "orderedEntitySetMixin", { enumerable: true, get: function () { return mixins_2.orderedEntitySetMixin; } }); -const selectorsForEntitySet = __importStar(require("./set/selectors")); -exports.selectorsForEntitySet = selectorsForEntitySet; diff --git a/dist/js/entity/mixins/BankableEntityMixin.d.ts b/dist/js/entity/mixins/BankableEntityMixin.d.ts deleted file mode 100644 index 97b48825..00000000 --- a/dist/js/entity/mixins/BankableEntityMixin.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { type BankableSchemaMixin } from "../../generated/BankableSchemaMixin"; -import type { Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -import { type HashedEntity } from "./HashedEntityMixin"; -export type BankableEntity = BankableSchemaMixin & HashedEntity; -export type BankableInMemoryEntityConstructor = Constructor; -export declare function bankableEntityMixin(item: T): asserts item is T & BankableEntity; diff --git a/dist/js/entity/mixins/BankableEntityMixin.js b/dist/js/entity/mixins/BankableEntityMixin.js deleted file mode 100644 index 1e31441b..00000000 --- a/dist/js/entity/mixins/BankableEntityMixin.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bankableEntityMixin = bankableEntityMixin; -const BankableSchemaMixin_1 = require("../../generated/BankableSchemaMixin"); -const HashedEntityMixin_1 = require("./HashedEntityMixin"); -function bankableEntityMixin(item) { - (0, BankableSchemaMixin_1.bankableSchemaMixin)(item); - (0, HashedEntityMixin_1.hashedEntityMixin)(item); -} diff --git a/dist/js/entity/mixins/DefaultableMixin.d.ts b/dist/js/entity/mixins/DefaultableMixin.d.ts deleted file mode 100644 index ccc28681..00000000 --- a/dist/js/entity/mixins/DefaultableMixin.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { type DefaultableSchemaMixin } from "../../generated/DefaultableSchemaMixin"; -import type { AbstractConstructor, Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -export type Defaultable = DefaultableSchemaMixin; -export type DefaultableInMemoryStaticEntity = { - createDefault: () => InMemoryEntity & Defaultable; -}; -export type DefaultableInMemoryEntityConstructor = Constructor & DefaultableInMemoryStaticEntity; -export declare function defaultableEntityMixin(Item: AbstractConstructor): void; diff --git a/dist/js/entity/mixins/DefaultableMixin.js b/dist/js/entity/mixins/DefaultableMixin.js deleted file mode 100644 index af808ac6..00000000 --- a/dist/js/entity/mixins/DefaultableMixin.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultableEntityMixin = defaultableEntityMixin; -const DefaultableSchemaMixin_1 = require("../../generated/DefaultableSchemaMixin"); -function defaultableEntityStaticMixin(Item) { - // @ts-expect-error - const staticProperties = { - createDefault() { - return new this(this.defaultConfig); - }, - }; - Object.defineProperties(Item, Object.getOwnPropertyDescriptors(staticProperties)); - return staticProperties; -} -function defaultableEntityMixin(Item) { - (0, DefaultableSchemaMixin_1.defaultableSchemaMixin)(Item.prototype); - defaultableEntityStaticMixin(Item); -} diff --git a/dist/js/entity/mixins/HasConsistencyChecksMixin.d.ts b/dist/js/entity/mixins/HasConsistencyChecksMixin.d.ts deleted file mode 100644 index 2aa7725a..00000000 --- a/dist/js/entity/mixins/HasConsistencyChecksMixin.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { ConsistencyCheck } from "@mat3ra/esse/dist/js/types"; -import { type HasConsistencyChecksSchemaMixin } from "../../generated/HasConsistencyChecksSchemaMixin"; -import type { Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -type HasConsistencyChecksProperties = { - addConsistencyChecks: (array: ConsistencyCheck[]) => void; -}; -export type HasConsistencyChecks = HasConsistencyChecksSchemaMixin & HasConsistencyChecksProperties; -export type HasConsistencyChecksInMemoryEntityConstructor = Constructor; -export declare function hasConsistencyChecksMixin(item: T): asserts item is T & HasConsistencyChecks; -export {}; diff --git a/dist/js/entity/mixins/HasConsistencyChecksMixin.js b/dist/js/entity/mixins/HasConsistencyChecksMixin.js deleted file mode 100644 index 1e4d7889..00000000 --- a/dist/js/entity/mixins/HasConsistencyChecksMixin.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hasConsistencyChecksMixin = hasConsistencyChecksMixin; -const HasConsistencyChecksSchemaMixin_1 = require("../../generated/HasConsistencyChecksSchemaMixin"); -function hasConsistencyChecksMixin(item) { - (0, HasConsistencyChecksSchemaMixin_1.hasConsistencyChecksSchemaMixin)(item); - // @ts-expect-error - const properties = { - addConsistencyChecks(array) { - this.consistencyChecks = [...(this.consistencyChecks || []), ...array]; - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/entity/mixins/HasDescriptionMixin.d.ts b/dist/js/entity/mixins/HasDescriptionMixin.d.ts deleted file mode 100644 index 8de49b3b..00000000 --- a/dist/js/entity/mixins/HasDescriptionMixin.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { type HasDescriptionSchemaMixin, hasDescriptionSchemaMixin } from "../../generated/HasDescriptionSchemaMixin"; -export type HasDescription = HasDescriptionSchemaMixin; -export declare const hasDescriptionMixin: typeof hasDescriptionSchemaMixin; diff --git a/dist/js/entity/mixins/HasDescriptionMixin.js b/dist/js/entity/mixins/HasDescriptionMixin.js deleted file mode 100644 index c535ac9e..00000000 --- a/dist/js/entity/mixins/HasDescriptionMixin.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hasDescriptionMixin = void 0; -const HasDescriptionSchemaMixin_1 = require("../../generated/HasDescriptionSchemaMixin"); -exports.hasDescriptionMixin = HasDescriptionSchemaMixin_1.hasDescriptionSchemaMixin; diff --git a/dist/js/entity/mixins/HasMetadataMixin.d.ts b/dist/js/entity/mixins/HasMetadataMixin.d.ts deleted file mode 100644 index e439a82d..00000000 --- a/dist/js/entity/mixins/HasMetadataMixin.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { MetadataSchema } from "@mat3ra/esse/dist/js/types"; -import type { Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -type Metadata = MetadataSchema["metadata"]; -type HasMetadataSchema = { - metadata?: M; -}; -export type HasMetadata = HasMetadataSchema & { - updateMetadata: (object: M) => void; -}; -export type HasMetadataInMemoryEntityConstructor = Constructor>; -export declare function hasMetadataMixin(item: T): asserts item is T & HasMetadata; -export {}; diff --git a/dist/js/entity/mixins/HasMetadataMixin.js b/dist/js/entity/mixins/HasMetadataMixin.js deleted file mode 100644 index cb9338b4..00000000 --- a/dist/js/entity/mixins/HasMetadataMixin.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hasMetadataMixin = hasMetadataMixin; -function hasMetadataPropertiesMixin(item) { - // @ts-expect-error - const properties = { - get metadata() { - return this.prop("metadata"); - }, - set metadata(value) { - this.setProp("metadata", value); - }, - updateMetadata(object) { - this.setProp("metadata", { ...this.metadata, ...object }); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} -function hasMetadataMixin(item) { - hasMetadataPropertiesMixin(item); -} diff --git a/dist/js/entity/mixins/HasScopeTrackMixin.d.ts b/dist/js/entity/mixins/HasScopeTrackMixin.d.ts deleted file mode 100644 index b03d276f..00000000 --- a/dist/js/entity/mixins/HasScopeTrackMixin.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { InMemoryEntity } from "../in_memory"; -type ScopeTrackSchema = { - scopeTrack?: unknown[]; -}; -type ScopeTrackDescriptor = { - get scopeTrack(): unknown[]; - set scopeTrack(array: unknown[]); -}; -export declare function hasScopeTrackMixin(item: InMemoryEntity): InMemoryEntity & ScopeTrackDescriptor; -export type HasScopeTrackInMemoryEntity = ReturnType; -export {}; diff --git a/dist/js/entity/mixins/HasScopeTrackMixin.js b/dist/js/entity/mixins/HasScopeTrackMixin.js deleted file mode 100644 index 35bd2f2a..00000000 --- a/dist/js/entity/mixins/HasScopeTrackMixin.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hasScopeTrackMixin = hasScopeTrackMixin; -function schemaMixin(item) { - // @ts-expect-error - const properties = { - get scopeTrack() { - var _a; - return (_a = this.prop("scopeTrack")) !== null && _a !== void 0 ? _a : []; - }, - set scopeTrack(array) { - this.setProp("scopeTrack", array); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); - return properties; -} -function hasScopeTrackMixin(item) { - return schemaMixin(item); -} diff --git a/dist/js/entity/mixins/HashedEntityMixin.d.ts b/dist/js/entity/mixins/HashedEntityMixin.d.ts deleted file mode 100644 index 253c0d82..00000000 --- a/dist/js/entity/mixins/HashedEntityMixin.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { type HashedSchemaMixin } from "../../generated/HashedSchemaMixin"; -import type { Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -export type HashedEntity = HashedSchemaMixin & { - calculateHash(): string; - getHashObject?(): object; -}; -export type HashedInMemoryEntityConstructor = Constructor; -export declare function hashedEntityMixin(item: T): asserts item is T & HashedEntity; diff --git a/dist/js/entity/mixins/HashedEntityMixin.js b/dist/js/entity/mixins/HashedEntityMixin.js deleted file mode 100644 index c4debfbc..00000000 --- a/dist/js/entity/mixins/HashedEntityMixin.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hashedEntityMixin = hashedEntityMixin; -const HashedSchemaMixin_1 = require("../../generated/HashedSchemaMixin"); -const hash_1 = require("../../utils/hash"); -function hashedEntityMixin(item) { - (0, HashedSchemaMixin_1.hashedSchemaMixin)(item); - // @ts-expect-error - const properties = { - /** - * @summary Calculates hash based on meaningful fields and unit-specific fields. Unit-specific fields are - * separated into _typeSpecificHash function which can be overwritten by child classes. - * head and next are also important but not considered since they are included in subworkflow hash. - */ - calculateHash() { - var _a, _b; - return (0, hash_1.calculateHashFromObject)((_b = (_a = this.getHashObject) === null || _a === void 0 ? void 0 : _a.call(this)) !== null && _b !== void 0 ? _b : {}); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/entity/mixins/NamedEntityMixin.d.ts b/dist/js/entity/mixins/NamedEntityMixin.d.ts deleted file mode 100644 index e11a74f2..00000000 --- a/dist/js/entity/mixins/NamedEntityMixin.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { type NamedEntitySchemaMixin } from "../../generated/NamedEntitySchemaMixin"; -import type { Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -type NamedEntityProperties = { - setName: (name: string) => void; -}; -export type NamedEntity = NamedEntitySchemaMixin & NamedEntityProperties; -export type NamedInMemoryEntityConstructor = Constructor; -export declare function namedEntityMixin(item: T): asserts item is T & NamedEntity; -export {}; diff --git a/dist/js/entity/mixins/NamedEntityMixin.js b/dist/js/entity/mixins/NamedEntityMixin.js deleted file mode 100644 index 8884807d..00000000 --- a/dist/js/entity/mixins/NamedEntityMixin.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.namedEntityMixin = namedEntityMixin; -const NamedEntitySchemaMixin_1 = require("../../generated/NamedEntitySchemaMixin"); -function namedEntityPropertiesMixin(item) { - // @ts-expect-error - const properties = { - setName(name) { - this.setProp("name", name); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} -function namedEntityMixin(item) { - (0, NamedEntitySchemaMixin_1.namedEntitySchemaMixin)(item); - namedEntityPropertiesMixin(item); -} diff --git a/dist/js/entity/mixins/RuntimeItemsMixin.d.ts b/dist/js/entity/mixins/RuntimeItemsMixin.d.ts deleted file mode 100644 index 9bf97071..00000000 --- a/dist/js/entity/mixins/RuntimeItemsMixin.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { type RuntimeItemsSchemaMixin } from "../../generated/RuntimeItemsSchemaMixin"; -import type { Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -type RuntimeItemsProperties = { - hashObjectFromRuntimeItems: { - results: RuntimeItemsSchemaMixin["results"]; - preProcessors: RuntimeItemsSchemaMixin["preProcessors"]; - postProcessors: RuntimeItemsSchemaMixin["postProcessors"]; - }; -}; -export type RuntimeItems = RuntimeItemsSchemaMixin & RuntimeItemsProperties; -export type RuntimeItemsInMemoryEntityConstructor = Constructor; -export declare function runtimeItemsMixin(item: T): asserts item is T & RuntimeItems; -export {}; diff --git a/dist/js/entity/mixins/RuntimeItemsMixin.js b/dist/js/entity/mixins/RuntimeItemsMixin.js deleted file mode 100644 index 28ebc9cf..00000000 --- a/dist/js/entity/mixins/RuntimeItemsMixin.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.runtimeItemsMixin = runtimeItemsMixin; -const RuntimeItemsSchemaMixin_1 = require("../../generated/RuntimeItemsSchemaMixin"); -function runtimeItemsPropertiesMixin(item) { - // @ts-expect-error - const properties = { - get hashObjectFromRuntimeItems() { - return { - results: this.results, - preProcessors: this.preProcessors, - postProcessors: this.postProcessors, - }; - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} -function runtimeItemsMixin(item) { - (0, RuntimeItemsSchemaMixin_1.runtimeItemsSchemaMixin)(item); - runtimeItemsPropertiesMixin(item); -} diff --git a/dist/js/entity/mixins/TaggableMixin.d.ts b/dist/js/entity/mixins/TaggableMixin.d.ts deleted file mode 100644 index a8b7cff5..00000000 --- a/dist/js/entity/mixins/TaggableMixin.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { type TaggableSchemaMixin } from "../../generated/TaggableSchemaMixin"; -import type { Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -type TaggableProperties = { - setTags: (array: string[]) => void; -}; -export type Taggable = TaggableSchemaMixin & TaggableProperties; -export type TaggableInMemoryEntityConstructor = Constructor; -export declare function taggableMixin(item: T): asserts item is T & Taggable; -export {}; diff --git a/dist/js/entity/mixins/TaggableMixin.js b/dist/js/entity/mixins/TaggableMixin.js deleted file mode 100644 index a8bf3ab3..00000000 --- a/dist/js/entity/mixins/TaggableMixin.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.taggableMixin = taggableMixin; -const TaggableSchemaMixin_1 = require("../../generated/TaggableSchemaMixin"); -function taggablePropertiesMixin(item) { - // @ts-expect-error - const properties = { - setTags(array) { - this.tags = array.filter((value, index, self) => self.indexOf(value) === index); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} -function taggableMixin(item) { - (0, TaggableSchemaMixin_1.taggableSchemaMixin)(item); - taggablePropertiesMixin(item); -} diff --git a/dist/js/entity/mixins/ValidatableMixin.d.ts b/dist/js/entity/mixins/ValidatableMixin.d.ts deleted file mode 100644 index db9792a0..00000000 --- a/dist/js/entity/mixins/ValidatableMixin.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { JSONSchema } from "@mat3ra/esse/dist/js/esse/utils"; -import type { AbstractConstructor, Constructor } from "../../utils/types"; -import { InMemoryEntity } from "../in_memory"; -export type Validatable = { - validate(): void; - isValid(): boolean; - clean(config: T): T; -}; -export type ValidatableInMemoryStaticEntity = { - validateData(data: object, clean?: boolean, jsonSchema?: JSONSchema): object; - allowJsonSchemaTypesCoercing: boolean; - readonly jsonSchema?: JSONSchema; -}; -export type ValidatableInMemoryEntityConstructor = Constructor & ValidatableInMemoryStaticEntity; -/** - * Opt-in AJV validation for InMemoryEntity subclasses. - * - * Apply on the constructor (adds static + prototype members): - * - * ```ts - * interface MyEntity extends Validatable {} - * class MyEntity extends InMemoryEntity { - * static readonly jsonSchema = mySchema; - * } - * validatableEntityMixin(MyEntity); - * ``` - * - * Idempotent: safe to call more than once on the same class. - */ -export declare function validatableEntityMixin(Item: AbstractConstructor): void; diff --git a/dist/js/entity/mixins/ValidatableMixin.js b/dist/js/entity/mixins/ValidatableMixin.js deleted file mode 100644 index 9fabe9f4..00000000 --- a/dist/js/entity/mixins/ValidatableMixin.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validatableEntityMixin = validatableEntityMixin; -const omit_1 = __importDefault(require("lodash/omit")); -const clone_1 = require("../../utils/clone"); -const in_memory_1 = require("../in_memory"); -const validateEntityData_1 = require("../validateEntityData"); -const validatableEntityMixinApplied = Symbol("validatableEntityMixinApplied"); -function validatableEntityStaticMixin(Item) { - // @ts-expect-error — assigning mixin statics onto constructor - const staticProperties = { - allowJsonSchemaTypesCoercing: false, - validateData(data, clean, jsonSchema) { - return (0, validateEntityData_1.validateEntityData)(data, jsonSchema !== null && jsonSchema !== void 0 ? jsonSchema : this.jsonSchema, { - clean: clean !== null && clean !== void 0 ? clean : false, - coerceTypes: this.allowJsonSchemaTypesCoercing, - }); - }, - }; - Object.defineProperties(Item, Object.getOwnPropertyDescriptors(staticProperties)); -} -function validatableEntityInstanceMixin(item) { - // @ts-expect-error — assigning mixin instance methods onto prototype - const properties = { - validate() { - const ctr = this.constructor; - if (this._json) { - ctr.validateData(this._json); - } - }, - isValid() { - try { - this.validate(); - return true; - } - catch (_a) { - return false; - } - }, - clean(config) { - var _a, _b, _c; - try { - const ctr = this.constructor; - return ctr.validateData(config, true); - } - catch (err) { - if (err instanceof in_memory_1.EntityError) { - console.error({ - error: JSON.stringify((_a = err.details) === null || _a === void 0 ? void 0 : _a.error), - json: JSON.stringify((_b = err.details) === null || _b === void 0 ? void 0 : _b.json), - schema: JSON.stringify((_c = err.details) === null || _c === void 0 ? void 0 : _c.schema), - }); - } - throw err; - } - }, - toJSON(exclude = []) { - const ctr = this.constructor; - const json = ctr._isDeepCloneRequired - ? (0, clone_1.deepClone)((0, omit_1.default)(this._json, exclude)) - : (0, clone_1.clone)((0, omit_1.default)(this._json, exclude)); - return this.clean(json); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} -/** - * Opt-in AJV validation for InMemoryEntity subclasses. - * - * Apply on the constructor (adds static + prototype members): - * - * ```ts - * interface MyEntity extends Validatable {} - * class MyEntity extends InMemoryEntity { - * static readonly jsonSchema = mySchema; - * } - * validatableEntityMixin(MyEntity); - * ``` - * - * Idempotent: safe to call more than once on the same class. - */ -function validatableEntityMixin(Item) { - const ctor = Item; - if (ctor[validatableEntityMixinApplied]) { - return; - } - validatableEntityStaticMixin(Item); - validatableEntityInstanceMixin(Item.prototype); - ctor[validatableEntityMixinApplied] = true; -} diff --git a/dist/js/entity/other.d.ts b/dist/js/entity/other.d.ts deleted file mode 100644 index 73c0ac32..00000000 --- a/dist/js/entity/other.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { InMemoryEntity } from "./in_memory"; -import { type DefaultableInMemoryEntityConstructor } from "./mixins/DefaultableMixin"; -import { type HasConsistencyChecksInMemoryEntityConstructor } from "./mixins/HasConsistencyChecksMixin"; -import { type HasMetadataInMemoryEntityConstructor } from "./mixins/HasMetadataMixin"; -import { type NamedInMemoryEntityConstructor } from "./mixins/NamedEntityMixin"; -type DefaultableBase = typeof InMemoryEntity & DefaultableInMemoryEntityConstructor; -type NamedBase = typeof InMemoryEntity & NamedInMemoryEntityConstructor; -type NamedDefaultableBase = typeof InMemoryEntity & DefaultableInMemoryEntityConstructor & NamedInMemoryEntityConstructor; -type HasMetadataNamedDefaultableBase = typeof InMemoryEntity & DefaultableInMemoryEntityConstructor & NamedInMemoryEntityConstructor & HasMetadataInMemoryEntityConstructor; -type HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntityBase = typeof InMemoryEntity & DefaultableInMemoryEntityConstructor & NamedInMemoryEntityConstructor & HasConsistencyChecksInMemoryEntityConstructor; -declare const DefaultableInMemoryEntity_base: DefaultableBase; -export declare class DefaultableInMemoryEntity extends DefaultableInMemoryEntity_base { -} -declare const NamedInMemoryEntity_base: NamedBase; -export declare class NamedInMemoryEntity extends NamedInMemoryEntity_base { -} -declare const NamedDefaultableInMemoryEntity_base: NamedDefaultableBase; -export declare class NamedDefaultableInMemoryEntity extends NamedDefaultableInMemoryEntity_base { -} -declare const HasMetadataNamedDefaultableInMemoryEntity_base: HasMetadataNamedDefaultableBase; -export declare class HasMetadataNamedDefaultableInMemoryEntity extends HasMetadataNamedDefaultableInMemoryEntity_base { -} -declare const HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity_base: HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntityBase; -export declare class HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity extends HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity_base { -} -export {}; diff --git a/dist/js/entity/other.js b/dist/js/entity/other.js deleted file mode 100644 index a093c094..00000000 --- a/dist/js/entity/other.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity = exports.HasMetadataNamedDefaultableInMemoryEntity = exports.NamedDefaultableInMemoryEntity = exports.NamedInMemoryEntity = exports.DefaultableInMemoryEntity = void 0; -const in_memory_1 = require("./in_memory"); -const DefaultableMixin_1 = require("./mixins/DefaultableMixin"); -const HasConsistencyChecksMixin_1 = require("./mixins/HasConsistencyChecksMixin"); -const HasMetadataMixin_1 = require("./mixins/HasMetadataMixin"); -const NamedEntityMixin_1 = require("./mixins/NamedEntityMixin"); -class DefaultableInMemoryEntity extends in_memory_1.InMemoryEntity { -} -exports.DefaultableInMemoryEntity = DefaultableInMemoryEntity; -(0, DefaultableMixin_1.defaultableEntityMixin)(DefaultableInMemoryEntity); -class NamedInMemoryEntity extends in_memory_1.InMemoryEntity { -} -exports.NamedInMemoryEntity = NamedInMemoryEntity; -(0, NamedEntityMixin_1.namedEntityMixin)(NamedInMemoryEntity.prototype); -class NamedDefaultableInMemoryEntity extends in_memory_1.InMemoryEntity { -} -exports.NamedDefaultableInMemoryEntity = NamedDefaultableInMemoryEntity; -(0, NamedEntityMixin_1.namedEntityMixin)(NamedDefaultableInMemoryEntity.prototype); -(0, DefaultableMixin_1.defaultableEntityMixin)(NamedDefaultableInMemoryEntity); -class HasMetadataNamedDefaultableInMemoryEntity extends in_memory_1.InMemoryEntity { -} -exports.HasMetadataNamedDefaultableInMemoryEntity = HasMetadataNamedDefaultableInMemoryEntity; -(0, NamedEntityMixin_1.namedEntityMixin)(HasMetadataNamedDefaultableInMemoryEntity.prototype); -(0, DefaultableMixin_1.defaultableEntityMixin)(HasMetadataNamedDefaultableInMemoryEntity); -(0, HasMetadataMixin_1.hasMetadataMixin)(HasMetadataNamedDefaultableInMemoryEntity.prototype); -class HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity extends in_memory_1.InMemoryEntity { -} -exports.HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity = HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity; -(0, NamedEntityMixin_1.namedEntityMixin)(HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity.prototype); -(0, DefaultableMixin_1.defaultableEntityMixin)(HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity); -(0, HasMetadataMixin_1.hasMetadataMixin)(HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity.prototype); -(0, HasConsistencyChecksMixin_1.hasConsistencyChecksMixin)(HasConsistencyChecksHasMetadataNamedDefaultableInMemoryEntity.prototype); diff --git a/dist/js/entity/set/InMemoryEntityInSetMixin.d.ts b/dist/js/entity/set/InMemoryEntityInSetMixin.d.ts deleted file mode 100644 index 785474f9..00000000 --- a/dist/js/entity/set/InMemoryEntityInSetMixin.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { SystemInSetSchema } from "@mat3ra/esse/dist/js/types"; -import { type InMemoryEntity } from "../in_memory"; -export type SystemInSet = Required; -export type InSet = SystemInSet["inSet"][0]; -export declare function inMemoryEntityInSetMixin(item: E): asserts item is E & InMemoryEntityInSet; -export type InSetPropertiesInMemoryEntity = { - getInSetFilteredByCls: (cls: string) => InSet[]; - parentEntitySetReference: InSet | undefined; -}; -export type InMemoryEntityInSet = SystemInSet & InSetPropertiesInMemoryEntity; diff --git a/dist/js/entity/set/InMemoryEntityInSetMixin.js b/dist/js/entity/set/InMemoryEntityInSetMixin.js deleted file mode 100644 index e1fd21d9..00000000 --- a/dist/js/entity/set/InMemoryEntityInSetMixin.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.inMemoryEntityInSetMixin = inMemoryEntityInSetMixin; -const InSetSchemaMixin_1 = require("../../generated/InSetSchemaMixin"); -function inMemoryEntityInSetMixin(item) { - (0, InSetSchemaMixin_1.inSetSchemaMixin)(item); - // @ts-expect-error - const properties = { - getInSetFilteredByCls(cls) { - return this.inSet.filter((ref) => ref.cls === cls); - }, - // finds a parent entity set of the same cls (hence `cls` field is absent) - // NOTE: assumes that only one entry of this kind is present => gets the first one - get parentEntitySetReference() { - return this.inSet.find((inSetItem) => inSetItem._id && !inSetItem.cls); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/entity/set/InMemoryEntitySetBaseMixin.d.ts b/dist/js/entity/set/InMemoryEntitySetBaseMixin.d.ts deleted file mode 100644 index ff1cac00..00000000 --- a/dist/js/entity/set/InMemoryEntitySetBaseMixin.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { type BaseInMemoryEntitySchema, type EntitySetSchema, SystemInSetSchema } from "@mat3ra/esse/dist/js/types"; -import { type InMemoryEntity } from "../in_memory"; -export type SystemInSet = Required; -export type InSet = SystemInSet["inSet"][0]; -type EntitySetEntitySchema = BaseInMemoryEntitySchema & EntitySetSchema; -export declare enum EntitySetType { - ordered = "ordered", - unordered = "unordered" -} -type EntitySetBaseMethodsDescriptor = { - toJSONForInclusionInEntity(): { - _id: string; - type: string; - }; -}; -/** Mixin shape only — safe to merge into schema-generic subclasses (no baked-in `_json`). */ -export type InMemoryEntitySetBaseMixin = EntitySetSchema & EntitySetBaseMethodsDescriptor; -/** Instance type with default entity-set schema (includes `InMemoryEntity<_json>`). */ -export type InMemoryEntitySetBase = InMemoryEntity & InMemoryEntitySetBaseMixin; -export declare function inMemoryEntitySetBaseMixin(item: T): asserts item is T & InMemoryEntitySetBaseMixin; -export {}; diff --git a/dist/js/entity/set/InMemoryEntitySetBaseMixin.js b/dist/js/entity/set/InMemoryEntitySetBaseMixin.js deleted file mode 100644 index d2995b6b..00000000 --- a/dist/js/entity/set/InMemoryEntitySetBaseMixin.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EntitySetType = void 0; -exports.inMemoryEntitySetBaseMixin = inMemoryEntitySetBaseMixin; -var EntitySetType; -(function (EntitySetType) { - EntitySetType["ordered"] = "ordered"; - EntitySetType["unordered"] = "unordered"; -})(EntitySetType || (exports.EntitySetType = EntitySetType = {})); -function schemaMixin(item) { - // @ts-expect-error - const properties = { - get isEntitySet() { - return this.prop("isEntitySet", false); - }, - get entitySetType() { - return this.prop("entitySetType", EntitySetType.unordered); - }, - get entityCls() { - return this.prop("entityCls"); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); - return properties; -} -function methodsMixin(item) { - const originalCls = item.cls; - // @ts-expect-error - const properties = { - get cls() { - return this.entityCls || originalCls; - }, - toJSONForInclusionInEntity() { - const { _id, type } = this.toJSON(); - return { _id, type }; - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); - return properties; -} -function inMemoryEntitySetBaseMixin(item) { - schemaMixin(item); - methodsMixin(item); -} diff --git a/dist/js/entity/set/InMemoryEntitySetMixin.d.ts b/dist/js/entity/set/InMemoryEntitySetMixin.d.ts deleted file mode 100644 index ca94a280..00000000 --- a/dist/js/entity/set/InMemoryEntitySetMixin.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { SystemInSetSchema } from "@mat3ra/esse/dist/js/types"; -import { type InMemoryEntity } from "../in_memory"; -export type SystemInSet = Required; -export type InSet = SystemInSet["inSet"][0]; -export type InMemoryEntitySet = { - containsEntity(entity?: SystemInSetSchema): boolean; -}; -export declare function inMemoryEntitySetMixin(item: T): InMemoryEntity & InMemoryEntitySet; diff --git a/dist/js/entity/set/InMemoryEntitySetMixin.js b/dist/js/entity/set/InMemoryEntitySetMixin.js deleted file mode 100644 index 42e2b0d2..00000000 --- a/dist/js/entity/set/InMemoryEntitySetMixin.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.inMemoryEntitySetMixin = inMemoryEntitySetMixin; -function inMemoryEntitySetMixin(item) { - // @ts-expect-error - const properties = { - containsEntity(entity) { - var _a; - return Boolean((_a = entity === null || entity === void 0 ? void 0 : entity.inSet) === null || _a === void 0 ? void 0 : _a.some((ref) => ref._id === this.id)); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); - return properties; -} diff --git a/dist/js/entity/set/enums.d.ts b/dist/js/entity/set/enums.d.ts deleted file mode 100644 index 30ed93b5..00000000 --- a/dist/js/entity/set/enums.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare const ENTITY_SET_TYPES: { - readonly unordered: "unordered"; - readonly ordered: "ordered"; -}; diff --git a/dist/js/entity/set/enums.js b/dist/js/entity/set/enums.js deleted file mode 100644 index 5ee0ae29..00000000 --- a/dist/js/entity/set/enums.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ENTITY_SET_TYPES = void 0; -exports.ENTITY_SET_TYPES = { - unordered: "unordered", - ordered: "ordered", -}; diff --git a/dist/js/entity/set/mixins.d.ts b/dist/js/entity/set/mixins.d.ts deleted file mode 100644 index 204e09f4..00000000 --- a/dist/js/entity/set/mixins.d.ts +++ /dev/null @@ -1 +0,0 @@ -export { inMemoryEntitySetMixin, inMemoryEntitySetMixin as InMemoryEntitySetMixin, } from "./InMemoryEntitySetMixin"; diff --git a/dist/js/entity/set/mixins.js b/dist/js/entity/set/mixins.js deleted file mode 100644 index 17e87381..00000000 --- a/dist/js/entity/set/mixins.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemoryEntitySetMixin = exports.inMemoryEntitySetMixin = void 0; -var InMemoryEntitySetMixin_1 = require("./InMemoryEntitySetMixin"); -Object.defineProperty(exports, "inMemoryEntitySetMixin", { enumerable: true, get: function () { return InMemoryEntitySetMixin_1.inMemoryEntitySetMixin; } }); -Object.defineProperty(exports, "InMemoryEntitySetMixin", { enumerable: true, get: function () { return InMemoryEntitySetMixin_1.inMemoryEntitySetMixin; } }); diff --git a/dist/js/entity/set/ordered/OrderedInMemoryEntityInSetMixin.d.ts b/dist/js/entity/set/ordered/OrderedInMemoryEntityInSetMixin.d.ts deleted file mode 100644 index 82724c32..00000000 --- a/dist/js/entity/set/ordered/OrderedInMemoryEntityInSetMixin.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { type InMemoryEntity } from "../../in_memory"; -import type { InMemoryEntityInSet } from "../InMemoryEntityInSetMixin"; -export type OrderedInMemoryEntityInSet = { - getIndexByIdInOrderedSet(setId: string): number; -}; -export declare function orderedEntityInSetMixin(item: T): asserts item is T & OrderedInMemoryEntityInSet; diff --git a/dist/js/entity/set/ordered/OrderedInMemoryEntityInSetMixin.js b/dist/js/entity/set/ordered/OrderedInMemoryEntityInSetMixin.js deleted file mode 100644 index ba6a355e..00000000 --- a/dist/js/entity/set/ordered/OrderedInMemoryEntityInSetMixin.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.orderedEntityInSetMixin = orderedEntityInSetMixin; -function orderedEntityInSetMixin(item) { - // @ts-expect-error - const properties = { - getIndexByIdInOrderedSet(setId) { - const setData = this.inSet.find((s) => s._id === setId); - return (setData === null || setData === void 0 ? void 0 : setData.index) || 0; - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/entity/set/ordered/OrderedInMemoryEntitySetMixin.d.ts b/dist/js/entity/set/ordered/OrderedInMemoryEntitySetMixin.d.ts deleted file mode 100644 index 32526ca1..00000000 --- a/dist/js/entity/set/ordered/OrderedInMemoryEntitySetMixin.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { type InMemoryEntity } from "../../in_memory"; -import type { InMemoryEntitySetBase } from "../InMemoryEntitySetBaseMixin"; -export type OrderedInMemoryEntitySet = { - get isOrderedSet(): boolean; -}; -export declare function orderedEntitySetMixin(item: T): asserts item is T & OrderedInMemoryEntitySet; diff --git a/dist/js/entity/set/ordered/OrderedInMemoryEntitySetMixin.js b/dist/js/entity/set/ordered/OrderedInMemoryEntitySetMixin.js deleted file mode 100644 index 1eea8a0b..00000000 --- a/dist/js/entity/set/ordered/OrderedInMemoryEntitySetMixin.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.orderedEntitySetMixin = orderedEntitySetMixin; -const enums_1 = require("../enums"); -function orderedEntitySetMixin(item) { - // @ts-expect-error - const properties = { - get isOrderedSet() { - return this.entitySetType === enums_1.ENTITY_SET_TYPES.ordered; - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/entity/set/ordered/mixins.d.ts b/dist/js/entity/set/ordered/mixins.d.ts deleted file mode 100644 index ecadbc4b..00000000 --- a/dist/js/entity/set/ordered/mixins.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { orderedEntityInSetMixin } from "./OrderedInMemoryEntityInSetMixin"; -import { orderedEntitySetMixin } from "./OrderedInMemoryEntitySetMixin"; -export { orderedEntityInSetMixin, orderedEntitySetMixin }; diff --git a/dist/js/entity/set/ordered/mixins.js b/dist/js/entity/set/ordered/mixins.js deleted file mode 100644 index 98576112..00000000 --- a/dist/js/entity/set/ordered/mixins.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.orderedEntitySetMixin = exports.orderedEntityInSetMixin = void 0; -const OrderedInMemoryEntityInSetMixin_1 = require("./OrderedInMemoryEntityInSetMixin"); -Object.defineProperty(exports, "orderedEntityInSetMixin", { enumerable: true, get: function () { return OrderedInMemoryEntityInSetMixin_1.orderedEntityInSetMixin; } }); -const OrderedInMemoryEntitySetMixin_1 = require("./OrderedInMemoryEntitySetMixin"); -Object.defineProperty(exports, "orderedEntitySetMixin", { enumerable: true, get: function () { return OrderedInMemoryEntitySetMixin_1.orderedEntitySetMixin; } }); diff --git a/dist/js/entity/set/ordered/utils.d.ts b/dist/js/entity/set/ordered/utils.d.ts deleted file mode 100644 index 7cde31f7..00000000 --- a/dist/js/entity/set/ordered/utils.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { OrderedInMemoryEntityInSet } from "./OrderedInMemoryEntityInSetMixin"; -/** - * A comparison function to sort inSet entities by setId and index (descending by default). - * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more info. - */ -export declare const compareEntitiesInOrderedSetForSorting: (a: OrderedInMemoryEntityInSet, b: OrderedInMemoryEntityInSet, setId: string, descending?: boolean) => number; diff --git a/dist/js/entity/set/ordered/utils.js b/dist/js/entity/set/ordered/utils.js deleted file mode 100644 index 6495da1c..00000000 --- a/dist/js/entity/set/ordered/utils.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.compareEntitiesInOrderedSetForSorting = void 0; -/** - * A comparison function to sort inSet entities by setId and index (descending by default). - * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more info. - */ -const compareEntitiesInOrderedSetForSorting = (a, b, setId, descending = true) => { - // eslint-disable-next-line no-nested-ternary - const aIndex = a - ? a.getIndexByIdInOrderedSet(setId) - : descending - ? Number.POSITIVE_INFINITY - : Number.NEGATIVE_INFINITY; - // eslint-disable-next-line no-nested-ternary - const bIndex = b - ? b.getIndexByIdInOrderedSet(setId) - : descending - ? Number.POSITIVE_INFINITY - : Number.NEGATIVE_INFINITY; - return descending ? bIndex - aIndex : aIndex - bIndex; -}; -exports.compareEntitiesInOrderedSetForSorting = compareEntitiesInOrderedSetForSorting; diff --git a/dist/js/entity/set/selectors.d.ts b/dist/js/entity/set/selectors.d.ts deleted file mode 100644 index 93c8ed87..00000000 --- a/dist/js/entity/set/selectors.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -declare const getInSetEntrySelectorBuilder: (config: object) => { - inSet: { - $elemMatch: object; - }; -}; -declare const getInSetEntrySelectorByIdsCls: (ids: string[], cls?: string | null) => { - inSet: { - $elemMatch: object; - }; -}; -declare const getInSetEntrySelectorByIds: (ids: string[]) => { - inSet: { - $elemMatch: object; - }; -}; -declare const getInSetEntrySelector: (cls?: string, _id?: string) => { - inSet: { - $elemMatch: { - _id?: string | undefined; - cls?: string | undefined; - }; - }; -}; -declare const getInSetEntryWithoutClsOnly: { - inSet: { - $not: { - $elemMatch: { - cls: { - $exists: boolean; - }; - }; - }; - }; -}; -export { getInSetEntrySelectorByIdsCls, getInSetEntryWithoutClsOnly, getInSetEntrySelectorByIds, getInSetEntrySelectorBuilder, getInSetEntrySelector, }; diff --git a/dist/js/entity/set/selectors.js b/dist/js/entity/set/selectors.js deleted file mode 100644 index 59009141..00000000 --- a/dist/js/entity/set/selectors.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getInSetEntrySelector = exports.getInSetEntrySelectorBuilder = exports.getInSetEntrySelectorByIds = exports.getInSetEntryWithoutClsOnly = exports.getInSetEntrySelectorByIdsCls = void 0; -const utils_1 = require("../../utils"); -const getInSetEntrySelectorBuilder = (config) => { - return { - inSet: { - $elemMatch: config, - }, - }; -}; -exports.getInSetEntrySelectorBuilder = getInSetEntrySelectorBuilder; -const getInSetEntrySelectorByIdsCls = (ids, cls = "Team") => { - const newIds = (0, utils_1.safeMakeArray)(ids); - const config = { - _id: { $in: newIds }, - ...(cls ? { cls } : {}), - }; - return getInSetEntrySelectorBuilder(config); -}; -exports.getInSetEntrySelectorByIdsCls = getInSetEntrySelectorByIdsCls; -const getInSetEntrySelectorByIds = (ids) => getInSetEntrySelectorByIdsCls(ids, null); -exports.getInSetEntrySelectorByIds = getInSetEntrySelectorByIds; -const getInSetEntrySelector = (cls, _id) => { - return { - inSet: { - $elemMatch: { - ...(cls ? { cls } : {}), - ...(_id ? { _id } : {}), - }, - }, - }; -}; -exports.getInSetEntrySelector = getInSetEntrySelector; -const getInSetEntryWithoutClsOnly = { - inSet: { $not: { $elemMatch: { cls: { $exists: false } } } }, -}; -exports.getInSetEntryWithoutClsOnly = getInSetEntryWithoutClsOnly; diff --git a/dist/js/entity/validateEntityData.d.ts b/dist/js/entity/validateEntityData.d.ts deleted file mode 100644 index cb070978..00000000 --- a/dist/js/entity/validateEntityData.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { JSONSchema } from "@mat3ra/esse/dist/js/esse/utils"; -export type ValidateEntityDataOptions = { - clean?: boolean; - coerceTypes?: boolean; -}; -/** - * Validate (and optionally clean) entity data against a JSON schema. - * Returns `data` unchanged when no schema is provided. - */ -export declare function validateEntityData(data: object, jsonSchema: JSONSchema | undefined, options?: ValidateEntityDataOptions): object; diff --git a/dist/js/entity/validateEntityData.js b/dist/js/entity/validateEntityData.js deleted file mode 100644 index 90aeeac0..00000000 --- a/dist/js/entity/validateEntityData.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validateEntityData = validateEntityData; -const ajv = __importStar(require("@mat3ra/esse/dist/js/utils/ajv")); -const in_memory_1 = require("./in_memory"); -/** - * Validate (and optionally clean) entity data against a JSON schema. - * Returns `data` unchanged when no schema is provided. - */ -function validateEntityData(data, jsonSchema, options = {}) { - if (!jsonSchema) { - return data; - } - const { clean = false, coerceTypes = false } = options; - const result = clean - ? ajv.validateAndClean(data, jsonSchema, { coerceTypes }) - : ajv.validate(data, jsonSchema); - if (!result.isValid) { - throw new in_memory_1.EntityError({ - code: in_memory_1.ValidationErrorCode.IN_MEMORY_ENTITY_DATA_INVALID, - details: { - error: result === null || result === void 0 ? void 0 : result.errors, - json: data, - schema: jsonSchema, - }, - }); - } - return data; -} diff --git a/dist/js/generateSchemaMixin.d.ts b/dist/js/generateSchemaMixin.d.ts deleted file mode 100644 index 09714f4c..00000000 --- a/dist/js/generateSchemaMixin.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node -import type { JSONSchema7 } from "json-schema"; -/** - * Generates mixins for multiple schemas - * @param schemas - Array of JSON schemas to use for generation - * @param outputPaths - Object mapping schema IDs to output file paths - * @param skipFields - Array of field names to skip during generation - * @param from - Import path for the schema type (default: "@mat3ra/esse/dist/js/types") - * @param entityFrom - Import path for the entity type (default: "@mat3ra/code/dist/js/entity") - * @returns - Object with success and error counts - */ -declare function generateShemaMixin(schemas: JSONSchema7[], outputPaths: Record, skipFields?: string[], from?: string, entityFrom?: string): { - successCount: number; - errorCount: number; -}; -/** - * @example - * ```ts - * import generateShemaMixin from "@mat3ra/code/dist/js/generateSchemaMixin"; - * import allSchemas from "@mat3ra/esse/dist/js/schemas.json"; - * - * const result = generateShemaMixin(allSchemas, OUTPUT_PATHS, SKIP_FIELDS); - * - * if (result.errorCount > 0) { - * process.exit(1); - * } - * ``` - */ -export default generateShemaMixin; diff --git a/dist/js/generateSchemaMixin.js b/dist/js/generateSchemaMixin.js deleted file mode 100644 index e6d168f5..00000000 --- a/dist/js/generateSchemaMixin.js +++ /dev/null @@ -1,256 +0,0 @@ -#!/usr/bin/env node -"use strict"; -/* eslint-disable no-restricted-syntax */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Script to generate mixin properties from JSON schema - * - * This script generates mixin functions for property/holder, property/meta_holder, - * and property/proto_holder schemas automatically. - * - * Usage: - * node scripts/generate-mixin-properties.js - */ -const JSONSchemasInterface_1 = __importDefault(require("@mat3ra/esse/dist/js/esse/JSONSchemasInterface")); -const child_process_1 = require("child_process"); -const fs_1 = __importDefault(require("fs")); -/** - * Determines if a property should use requiredProp() or prop() - * @param propertyName - Name of the property - * @param requiredProperties - Array of required property names - * @returns - True if property is required - */ -function isRequiredProperty(propertyName, requiredProperties) { - return requiredProperties.includes(propertyName); -} -/** - * Generates TypeScript type annotation for a property - * @param propertyName - The property name - * @param schemaName - Name of the schema (for type reference) - * @returns - TypeScript type annotation - */ -function generateTypeAnnotation(propertyName, schemaName) { - return `${schemaName}["${propertyName}"]`; -} -/** - * Extracts properties from a schema, handling allOf if present - * @param schema - The JSON schema - * @returns - Object with properties and required fields - */ -function extractSchemaProperties(schema) { - let properties = {}; - let required = []; - // Handle allOf by merging properties from all schemas - if (schema.allOf && Array.isArray(schema.allOf)) { - for (const subSchema of schema.allOf) { - const extracted = extractSchemaProperties(subSchema); - properties = { ...properties, ...extracted.properties }; - required = [...required, ...extracted.required]; - } - } - // Add properties from current schema - if (schema.properties) { - properties = { ...properties, ...schema.properties }; - } - if (schema.required) { - required = [...required, ...schema.required]; - } - return { properties, required }; -} -/** - * Generates the complete mixin function - * @param schema - The JSON schema - * @param schemaName - Name of the schema - * @param mixinTypeName - Name of the mixin type - * @param entityTypeName - Name of the entity type - * @param skipFields - Array of field names to skip - * @param from - Import path for the schema type (default: "@mat3ra/esse/dist/js/types") - * @param entityFrom - Import path for the entity type (default: "@mat3ra/code/dist/js/entity") - * @returns - Generated TypeScript code - */ -function generateMixinFunction(schema, schemaName, mixinTypeName, entityTypeName, skipFields = [], from = "@mat3ra/esse/dist/js/types", entityFrom = "@mat3ra/code/dist/js/entity") { - // Convert mixin type name to camelCase for function name - const functionName = mixinTypeName.charAt(0).toLowerCase() + mixinTypeName.slice(1); - // Extract properties, handling allOf if present - const { properties, required } = extractSchemaProperties(schema); - if (Object.keys(properties).length === 0) { - throw new Error("No properties found in schema"); - } - // Filter out skip fields - const propertyEntries = Object.entries(properties).filter(([propertyName]) => !skipFields.includes(propertyName)); - let code = `import type { InMemoryEntity } from "${entityFrom}";\n`; - code += `import type { BaseInMemoryEntitySchema, ${schemaName} } from "${from}";\n\n`; - // Generate the mixin type - only use Omit if skipFields has values - if (skipFields && skipFields.length > 0) { - const skipFieldNames = skipFields.map((field) => `"${field}"`).join(" | "); - code += `export type ${mixinTypeName} = Omit<${schemaName}, ${skipFieldNames}>;\n\n`; - } - else { - code += `export type ${mixinTypeName} = ${schemaName};\n\n`; - } - // Entity schema must include base fields so `_json` / `toJSON` stay compatible with InMemoryEntity - code += `export type ${entityTypeName} = InMemoryEntity;\n\n`; - code += `export function ${functionName}(\n`; - code += ` item: InMemoryEntity,\n`; - code += `): asserts item is T & ${mixinTypeName} {\n`; - code += ` // @ts-expect-error\n`; - code += ` const properties: InMemoryEntity<${mixinTypeName}> & ${mixinTypeName} = {\n`; - for (let i = 0; i < propertyEntries.length; i++) { - const [propertyName] = propertyEntries[i]; - const isRequired = isRequiredProperty(propertyName, required); - const methodName = isRequired ? "requiredProp" : "prop"; - const typeAnnotation = generateTypeAnnotation(propertyName, schemaName); - code += `get ${propertyName}() {\n`; - code += `return this.${methodName}("${propertyName}");\n`; - code += `},\n`; - code += `set ${propertyName}(value: ${typeAnnotation}) {\n`; - code += `this.setProp("${propertyName}", value);\n`; - code += `}`; - // Add comma for all properties except the last one - if (i < propertyEntries.length - 1) { - code += `,\n`; - } - else { - code += `,\n`; - } - } - code += ` };\n\n`; - code += ` Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties));\n`; - code += `}\n`; - return code; -} -/** - * Generates mixin function for a given schema ID - * @param schemaId - The schema ID (e.g., "property/holder") - * @param outputPath - The output file path - * @param skipFields - Array of field names to skip - * @param from - Import path for the schema type (default: "@mat3ra/esse/dist/js/types") - * @param entityFrom - Import path for the entity type (default: "@mat3ra/code/dist/js/entity") - * @returns - Generated TypeScript code - */ -function generateMixinFromSchemaId(schemaId, outputPath, skipFields = [], from = "@mat3ra/esse/dist/js/types", entityFrom = "@mat3ra/code/dist/js/entity") { - var _a, _b; - // Get the resolved schema by ID - const schema = JSONSchemasInterface_1.default.getSchemaById(schemaId); - if (!schema) { - throw new Error(`Schema not found with ID: ${schemaId}`); - } - // Extract schema name from title for import - let schemaName; - if (schema.title) { - // Split on spaces and hyphens so titles like "System in-set schema" become SystemInSetSchema, - // not SystemIn-setSchema (hyphens are not valid in TS identifiers). - schemaName = schema.title - .split(/\s+/) - .flatMap((word) => word.split("-")) - .filter((segment) => segment.length > 0) - .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) - .join(""); - } - else { - // Convert schema ID to proper schema name - schemaName = - schemaId - .split(/[/-]/) - .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) - .join("") + "Schema"; - } - // Extract type names from output file path - const fileName = (_b = (_a = outputPath.split("/").pop()) === null || _a === void 0 ? void 0 : _a.replace(".ts", "")) !== null && _b !== void 0 ? _b : ""; - if (!fileName) { - throw new Error(`Invalid output path: ${outputPath}`); - } - const mixinTypeName = fileName; - const entityTypeName = fileName.replace("SchemaMixin", "InMemoryEntity"); - // Generate the complete mixin function - return generateMixinFunction(schema, schemaName, mixinTypeName, entityTypeName, skipFields, from, entityFrom); -} -/** - * Runs ESLint autofix on generated files - * @param filePaths - Array of file paths to fix - */ -function runESLintAutofix(filePaths) { - if (filePaths.length === 0) - return; - try { - console.log("Running ESLint autofix on generated files..."); - const filesToFix = filePaths.join(" "); - (0, child_process_1.execSync)(`npx eslint --fix ${filesToFix}`, { stdio: "inherit" }); - console.log("✓ ESLint autofix completed successfully"); - } - catch (error) { - console.warn("⚠ ESLint autofix failed:", error instanceof Error ? error.message : String(error)); - // Don't fail the entire process if ESLint autofix fails - } -} -/** - * Generates mixins for multiple schemas - * @param schemas - Array of JSON schemas to use for generation - * @param outputPaths - Object mapping schema IDs to output file paths - * @param skipFields - Array of field names to skip during generation - * @param from - Import path for the schema type (default: "@mat3ra/esse/dist/js/types") - * @param entityFrom - Import path for the entity type (default: "@mat3ra/code/dist/js/entity") - * @returns - Object with success and error counts - */ -function generateShemaMixin(schemas, outputPaths, skipFields = [], from = "@mat3ra/esse/dist/js/types", entityFrom = "@mat3ra/code/dist/js/entity") { - // Setup schemas - JSONSchemasInterface_1.default.setSchemas(schemas); - console.log("Generating mixin properties for all schemas..."); - const schemaIds = Object.keys(outputPaths); - let successCount = 0; - let errorCount = 0; - const generatedFiles = []; - for (const schemaId of schemaIds) { - try { - console.log(`\nProcessing schema: ${schemaId}`); - const outputPath = outputPaths[schemaId]; - if (!outputPath) { - throw new Error(`No output path defined for schema: ${schemaId}`); - } - const generatedCode = generateMixinFromSchemaId(schemaId, outputPath, skipFields, from, entityFrom); - // Ensure the directory exists - const dir = outputPath.substring(0, outputPath.lastIndexOf("/")); - if (!fs_1.default.existsSync(dir)) { - fs_1.default.mkdirSync(dir, { recursive: true }); - } - fs_1.default.writeFileSync(outputPath, generatedCode); - console.log(`✓ Generated mixin written to: ${outputPath}`); - generatedFiles.push(outputPath); - successCount += 1; - } - catch (error) { - console.error(`✗ Error processing schema ${schemaId}: ${error instanceof Error ? error.message : String(error)}`); - errorCount += 1; - } - } - // Run ESLint autofix on generated files - if (generatedFiles.length > 0) { - runESLintAutofix(generatedFiles); - } - console.log(`\n=== Summary ===`); - console.log(`Successfully generated: ${successCount} mixins`); - if (errorCount > 0) { - console.log(`Errors: ${errorCount} schemas failed`); - } - else { - console.log("All mixins generated successfully!"); - } - return { successCount, errorCount }; -} -/** - * @example - * ```ts - * import generateShemaMixin from "@mat3ra/code/dist/js/generateSchemaMixin"; - * import allSchemas from "@mat3ra/esse/dist/js/schemas.json"; - * - * const result = generateShemaMixin(allSchemas, OUTPUT_PATHS, SKIP_FIELDS); - * - * if (result.errorCount > 0) { - * process.exit(1); - * } - * ``` - */ -exports.default = generateShemaMixin; diff --git a/dist/js/generated/BankableSchemaMixin.d.ts b/dist/js/generated/BankableSchemaMixin.d.ts deleted file mode 100644 index b5177b25..00000000 --- a/dist/js/generated/BankableSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BankableSchema, BaseInMemoryEntitySchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type BankableSchemaMixin = BankableSchema; -export type BankableInMemoryEntity = InMemoryEntity; -export declare function bankableSchemaMixin(item: InMemoryEntity): asserts item is T & BankableSchemaMixin; diff --git a/dist/js/generated/BankableSchemaMixin.js b/dist/js/generated/BankableSchemaMixin.js deleted file mode 100644 index 7350b8ea..00000000 --- a/dist/js/generated/BankableSchemaMixin.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.bankableSchemaMixin = bankableSchemaMixin; -function bankableSchemaMixin(item) { - // @ts-expect-error - const properties = { - get exabyteId() { - return this.requiredProp("exabyteId"); - }, - set exabyteId(value) { - this.setProp("exabyteId", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/DefaultableSchemaMixin.d.ts b/dist/js/generated/DefaultableSchemaMixin.d.ts deleted file mode 100644 index bf608636..00000000 --- a/dist/js/generated/DefaultableSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, DefaultableEntitySchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type DefaultableSchemaMixin = DefaultableEntitySchema; -export type DefaultableInMemoryEntity = InMemoryEntity; -export declare function defaultableSchemaMixin(item: InMemoryEntity): asserts item is T & DefaultableSchemaMixin; diff --git a/dist/js/generated/DefaultableSchemaMixin.js b/dist/js/generated/DefaultableSchemaMixin.js deleted file mode 100644 index c9c276f1..00000000 --- a/dist/js/generated/DefaultableSchemaMixin.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultableSchemaMixin = defaultableSchemaMixin; -function defaultableSchemaMixin(item) { - // @ts-expect-error - const properties = { - get isDefault() { - return this.prop("isDefault"); - }, - set isDefault(value) { - this.setProp("isDefault", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/HasConsistencyChecksSchemaMixin.d.ts b/dist/js/generated/HasConsistencyChecksSchemaMixin.d.ts deleted file mode 100644 index 599f9735..00000000 --- a/dist/js/generated/HasConsistencyChecksSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, HasConsistencyCheckSchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type HasConsistencyChecksSchemaMixin = HasConsistencyCheckSchema; -export type HasConsistencyChecksInMemoryEntity = InMemoryEntity; -export declare function hasConsistencyChecksSchemaMixin(item: InMemoryEntity): asserts item is T & HasConsistencyChecksSchemaMixin; diff --git a/dist/js/generated/HasConsistencyChecksSchemaMixin.js b/dist/js/generated/HasConsistencyChecksSchemaMixin.js deleted file mode 100644 index 5db5cf1e..00000000 --- a/dist/js/generated/HasConsistencyChecksSchemaMixin.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hasConsistencyChecksSchemaMixin = hasConsistencyChecksSchemaMixin; -function hasConsistencyChecksSchemaMixin(item) { - // @ts-expect-error - const properties = { - get consistencyChecks() { - return this.prop("consistencyChecks"); - }, - set consistencyChecks(value) { - this.setProp("consistencyChecks", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/HasDescriptionSchemaMixin.d.ts b/dist/js/generated/HasDescriptionSchemaMixin.d.ts deleted file mode 100644 index bc7b4609..00000000 --- a/dist/js/generated/HasDescriptionSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, DescriptionSchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type HasDescriptionSchemaMixin = DescriptionSchema; -export type HasDescriptionInMemoryEntity = InMemoryEntity; -export declare function hasDescriptionSchemaMixin(item: InMemoryEntity): asserts item is T & HasDescriptionSchemaMixin; diff --git a/dist/js/generated/HasDescriptionSchemaMixin.js b/dist/js/generated/HasDescriptionSchemaMixin.js deleted file mode 100644 index 78f97154..00000000 --- a/dist/js/generated/HasDescriptionSchemaMixin.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hasDescriptionSchemaMixin = hasDescriptionSchemaMixin; -function hasDescriptionSchemaMixin(item) { - // @ts-expect-error - const properties = { - get description() { - return this.prop("description"); - }, - set description(value) { - this.setProp("description", value); - }, - get descriptionObject() { - return this.prop("descriptionObject"); - }, - set descriptionObject(value) { - this.setProp("descriptionObject", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/HashedSchemaMixin.d.ts b/dist/js/generated/HashedSchemaMixin.d.ts deleted file mode 100644 index 355e3e7b..00000000 --- a/dist/js/generated/HashedSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, HashedSchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type HashedSchemaMixin = HashedSchema; -export type HashedInMemoryEntity = InMemoryEntity; -export declare function hashedSchemaMixin(item: InMemoryEntity): asserts item is T & HashedSchemaMixin; diff --git a/dist/js/generated/HashedSchemaMixin.js b/dist/js/generated/HashedSchemaMixin.js deleted file mode 100644 index eb97531b..00000000 --- a/dist/js/generated/HashedSchemaMixin.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hashedSchemaMixin = hashedSchemaMixin; -function hashedSchemaMixin(item) { - // @ts-expect-error - const properties = { - get hash() { - return this.requiredProp("hash"); - }, - set hash(value) { - this.setProp("hash", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/InSetSchemaMixin.d.ts b/dist/js/generated/InSetSchemaMixin.d.ts deleted file mode 100644 index 52ed1f69..00000000 --- a/dist/js/generated/InSetSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, SystemInSetSchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type InSetSchemaMixin = SystemInSetSchema; -export type InSetInMemoryEntity = InMemoryEntity; -export declare function inSetSchemaMixin(item: InMemoryEntity): asserts item is T & InSetSchemaMixin; diff --git a/dist/js/generated/InSetSchemaMixin.js b/dist/js/generated/InSetSchemaMixin.js deleted file mode 100644 index d1a14a22..00000000 --- a/dist/js/generated/InSetSchemaMixin.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.inSetSchemaMixin = inSetSchemaMixin; -function inSetSchemaMixin(item) { - // @ts-expect-error - const properties = { - get inSet() { - return this.requiredProp("inSet"); - }, - set inSet(value) { - this.setProp("inSet", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/NamedEntitySchemaMixin.d.ts b/dist/js/generated/NamedEntitySchemaMixin.d.ts deleted file mode 100644 index b75a5d18..00000000 --- a/dist/js/generated/NamedEntitySchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, NameEntitySchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type NamedEntitySchemaMixin = NameEntitySchema; -export type NamedEntityInMemoryEntity = InMemoryEntity; -export declare function namedEntitySchemaMixin(item: InMemoryEntity): asserts item is T & NamedEntitySchemaMixin; diff --git a/dist/js/generated/NamedEntitySchemaMixin.js b/dist/js/generated/NamedEntitySchemaMixin.js deleted file mode 100644 index 6b701eb9..00000000 --- a/dist/js/generated/NamedEntitySchemaMixin.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.namedEntitySchemaMixin = namedEntitySchemaMixin; -function namedEntitySchemaMixin(item) { - // @ts-expect-error - const properties = { - get name() { - return this.requiredProp("name"); - }, - set name(value) { - this.setProp("name", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/RuntimeItemsSchemaMixin.d.ts b/dist/js/generated/RuntimeItemsSchemaMixin.d.ts deleted file mode 100644 index d56e0901..00000000 --- a/dist/js/generated/RuntimeItemsSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, RuntimeItemsSchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type RuntimeItemsSchemaMixin = RuntimeItemsSchema; -export type RuntimeItemsInMemoryEntity = InMemoryEntity; -export declare function runtimeItemsSchemaMixin(item: InMemoryEntity): asserts item is T & RuntimeItemsSchemaMixin; diff --git a/dist/js/generated/RuntimeItemsSchemaMixin.js b/dist/js/generated/RuntimeItemsSchemaMixin.js deleted file mode 100644 index 88ea0b29..00000000 --- a/dist/js/generated/RuntimeItemsSchemaMixin.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.runtimeItemsSchemaMixin = runtimeItemsSchemaMixin; -function runtimeItemsSchemaMixin(item) { - // @ts-expect-error - const properties = { - get preProcessors() { - return this.requiredProp("preProcessors"); - }, - set preProcessors(value) { - this.setProp("preProcessors", value); - }, - get postProcessors() { - return this.requiredProp("postProcessors"); - }, - set postProcessors(value) { - this.setProp("postProcessors", value); - }, - get monitors() { - return this.requiredProp("monitors"); - }, - set monitors(value) { - this.setProp("monitors", value); - }, - get results() { - return this.requiredProp("results"); - }, - set results(value) { - this.setProp("results", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/generated/TaggableSchemaMixin.d.ts b/dist/js/generated/TaggableSchemaMixin.d.ts deleted file mode 100644 index e1417801..00000000 --- a/dist/js/generated/TaggableSchemaMixin.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { BaseInMemoryEntitySchema, EntityTagsSchema } from "@mat3ra/esse/dist/js/types"; -import type { InMemoryEntity } from "../entity/in_memory"; -export type TaggableSchemaMixin = EntityTagsSchema; -export type TaggableInMemoryEntity = InMemoryEntity; -export declare function taggableSchemaMixin(item: InMemoryEntity): asserts item is T & TaggableSchemaMixin; diff --git a/dist/js/generated/TaggableSchemaMixin.js b/dist/js/generated/TaggableSchemaMixin.js deleted file mode 100644 index 86018a67..00000000 --- a/dist/js/generated/TaggableSchemaMixin.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.taggableSchemaMixin = taggableSchemaMixin; -function taggableSchemaMixin(item) { - // @ts-expect-error - const properties = { - get tags() { - return this.prop("tags"); - }, - set tags(value) { - this.setProp("tags", value); - }, - }; - Object.defineProperties(item, Object.getOwnPropertyDescriptors(properties)); -} diff --git a/dist/js/index.d.ts b/dist/js/index.d.ts deleted file mode 100644 index 4eaa4bef..00000000 --- a/dist/js/index.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { ArrayWithIds, RoundedArrayWithIds } from "./ArrayWithIds"; -import * as context from "./context"; -import * as entity from "./entity"; -import * as utils from "./utils"; -import * as validator from "./validator"; -import { RoundedValueWithId, ValueWithId } from "./ValueWithId"; -import { RoundedVector3D, Vector3D } from "./vector"; -export { ArrayWithIds, ValueWithId, RoundedValueWithId, RoundedArrayWithIds, RoundedVector3D, Vector3D, }; -export { entity, context, utils, validator }; -export { JsonSchemaValidator, jsonSchemaValidator } from "./validator"; -declare const Code: { - ArrayWithIds: typeof ArrayWithIds; - ValueWithId: typeof ValueWithId; - RoundedArrayWithIds: typeof RoundedArrayWithIds; - RoundedValueWithId: typeof RoundedValueWithId; - RoundedVector3D: typeof RoundedVector3D; - Vector3D: typeof Vector3D; - entity: typeof entity; - context: typeof context; - utils: typeof utils; - validator: typeof validator; -}; -export type CodeType = typeof Code; -export default Code; diff --git a/dist/js/index.js b/dist/js/index.js deleted file mode 100644 index 6fbe16c2..00000000 --- a/dist/js/index.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.jsonSchemaValidator = exports.JsonSchemaValidator = exports.validator = exports.utils = exports.context = exports.entity = exports.Vector3D = exports.RoundedVector3D = exports.RoundedArrayWithIds = exports.RoundedValueWithId = exports.ValueWithId = exports.ArrayWithIds = void 0; -const ArrayWithIds_1 = require("./ArrayWithIds"); -Object.defineProperty(exports, "ArrayWithIds", { enumerable: true, get: function () { return ArrayWithIds_1.ArrayWithIds; } }); -Object.defineProperty(exports, "RoundedArrayWithIds", { enumerable: true, get: function () { return ArrayWithIds_1.RoundedArrayWithIds; } }); -const context = __importStar(require("./context")); -exports.context = context; -const entity = __importStar(require("./entity")); -exports.entity = entity; -const utils = __importStar(require("./utils")); -exports.utils = utils; -const validator = __importStar(require("./validator")); -exports.validator = validator; -const ValueWithId_1 = require("./ValueWithId"); -Object.defineProperty(exports, "RoundedValueWithId", { enumerable: true, get: function () { return ValueWithId_1.RoundedValueWithId; } }); -Object.defineProperty(exports, "ValueWithId", { enumerable: true, get: function () { return ValueWithId_1.ValueWithId; } }); -const vector_1 = require("./vector"); -Object.defineProperty(exports, "RoundedVector3D", { enumerable: true, get: function () { return vector_1.RoundedVector3D; } }); -Object.defineProperty(exports, "Vector3D", { enumerable: true, get: function () { return vector_1.Vector3D; } }); -var validator_1 = require("./validator"); -Object.defineProperty(exports, "JsonSchemaValidator", { enumerable: true, get: function () { return validator_1.JsonSchemaValidator; } }); -Object.defineProperty(exports, "jsonSchemaValidator", { enumerable: true, get: function () { return validator_1.jsonSchemaValidator; } }); -const Code = { - ArrayWithIds: ArrayWithIds_1.ArrayWithIds, - ValueWithId: ValueWithId_1.ValueWithId, - RoundedArrayWithIds: ArrayWithIds_1.RoundedArrayWithIds, - RoundedValueWithId: ValueWithId_1.RoundedValueWithId, - RoundedVector3D: vector_1.RoundedVector3D, - Vector3D: vector_1.Vector3D, - entity, - context, - utils, - validator, -}; -exports.default = Code; diff --git a/dist/js/math.d.ts b/dist/js/math.d.ts deleted file mode 100644 index 6abf0ed7..00000000 --- a/dist/js/math.d.ts +++ /dev/null @@ -1,504 +0,0 @@ -import mathjs from "mathjs"; -/** - * This module is intended to be used instead of the original mathjs package, hence we need to reexport all original functions and all TS types. - * Export of all mathjs types one by one is required as we don't have a way to re-export them automatically in TS v4.5. - * This can be changed in TS version 5.0 and higher. - */ -export type MathArray = mathjs.MathArray; -export type MathType = mathjs.MathType; -export type MathExpression = mathjs.MathExpression; -export type MathJsStatic = mathjs.MathJsStatic; -export type Matrix = mathjs.Matrix; -export type BigNumber = mathjs.BigNumber; -export type Fraction = mathjs.Fraction; -export type Complex = mathjs.Complex; -export type PolarCoordinates = mathjs.PolarCoordinates; -export type MathJSON = mathjs.MathJSON; -export type Unit = mathjs.Unit; -export type CreateUnitOptions = mathjs.CreateUnitOptions; -export type UnitDefinition = mathjs.UnitDefinition; -export type Index = mathjs.Index; -export type EvalFunction = mathjs.EvalFunction; -export type MathNode = mathjs.MathNode; -export type Parser = mathjs.Parser; -export type Distribution = mathjs.Distribution; -export type FormatOptions = mathjs.FormatOptions; -export type Help = mathjs.Help; -export type MathJsChain = mathjs.MathJsChain; -export type MathJsJson = mathjs.MathJsJson; -export declare enum RoundingMethodEnum { - Bankers = "bankers", - HalfAwayFromZero = "halfAwayFromZero" -} -export declare const roundCustom: (value: number, decimals?: number, method?: RoundingMethodEnum) => number; -export declare const roundArrayOrNumber: (value: unknown, decimals?: number, method?: RoundingMethodEnum) => unknown; -/** - * @summary Wrapper for native [Number.toPrecision](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision) method. - * Returns a string representing the Number object to the specified precision. - * @memberOf Helpers - * @package exabyte:core - * @locus Client - * @method - * @name toPrecision - * @param number - * @param precision Optional. An integer specifying the number of significant digits. - */ -export declare function numberToPrecision(number: number | string, precision?: number): string; -export declare const math: { - PI: number; - trunc: (x: number) => number; - product: (v1: number[], v2: number[]) => number; - vlen: (v: number[]) => number; - angle: (a: number[], b: number[], unit: string) => number; - angleUpTo90: (a: number[], b: number[], unit: string) => number; - vDist: (v1: number[], v2: number[]) => number | undefined; - vEqualWithTolerance: (vec1: number[], vec2: number[], tolerance?: number) => boolean; - mod: (num: number, tolerance?: number) => number; - isBetweenZeroInclusiveAndOne: (number: number, tolerance?: number) => boolean; - cartesianProduct: (...arg: number[][]) => number[][]; - almostEqual: (a: number, b: number, tolerance?: number) => boolean; - combinations: (a: number, b: number, c: number) => number[][]; - combinationsFromIntervals: (arrA: number[], arrB: number[], arrC: number[]) => number[][]; - calculateSegmentsBetweenPoints3D: (point1: (string | number)[], point2: (string | number)[], n: number | string) => number[][]; - roundToZero: (n: number) => number; - precise: (x: number, n?: number) => number; - roundValueToNDecimals: (value: number, decimals?: number) => number; - numberToPrecision: typeof numberToPrecision; - roundCustom: (value: number, decimals?: number, method?: RoundingMethodEnum) => number; - RoundingMethod: typeof RoundingMethodEnum; - roundArrayOrNumber: (value: unknown, decimals?: number, method?: RoundingMethodEnum) => unknown; - e: number; - pi: number; - i: number; - Infinity: number; - LN2: number; - LN10: number; - LOG2E: number; - LOG10E: number; - NaN: number; - null: number; - phi: number; - SQRT1_2: number; - SQRT2: number; - tau: number; - uninitialized: any; - version: string; - expression: mathjs.MathNode; - json: mathjs.MathJsJson; - config: (options: mathjs.ConfigOptions) => mathjs.ConfigOptions; - typed: (name: string, signatures: Record any>) => ((...args: any[]) => any); - bignumber(x?: number | string | mathjs.Fraction | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix | boolean | mathjs.Fraction | null): mathjs.BigNumber; - boolean(x: string | number | boolean | mathjs.MathArray | mathjs.Matrix | null): boolean | mathjs.MathArray | mathjs.Matrix; - chain(value?: any): mathjs.MathJsChain; - complex(arg?: mathjs.Complex | string | mathjs.PolarCoordinates): mathjs.Complex; - complex(arg?: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - complex(re: number, im: number): mathjs.Complex; - createUnit(name: string, definition?: string | mathjs.UnitDefinition, options?: mathjs.CreateUnitOptions): mathjs.Unit; - createUnit(units: Record, options?: mathjs.CreateUnitOptions): mathjs.Unit; - fraction(args: mathjs.Fraction | mathjs.MathArray | mathjs.Matrix): mathjs.Fraction | mathjs.MathArray | mathjs.Matrix; - fraction(numerator: number | string | mathjs.MathArray | mathjs.Matrix, denominator?: number | string | mathjs.MathArray | mathjs.Matrix): mathjs.Fraction | mathjs.MathArray | mathjs.Matrix; - index(...ranges: any[]): mathjs.Index; - matrix(format?: "sparse" | "dense"): mathjs.Matrix; - matrix(data: mathjs.MathArray | mathjs.Matrix, format?: "sparse" | "dense", dataType?: string): mathjs.Matrix; - number(value?: string | number | mathjs.BigNumber | mathjs.Fraction | boolean | mathjs.MathArray | mathjs.Matrix | mathjs.Unit | null): number | mathjs.MathArray | mathjs.Matrix; - number(unit: mathjs.Unit, valuelessUnit: mathjs.Unit | string): number; - sparse(data?: mathjs.MathArray | mathjs.Matrix, dataType?: string): mathjs.Matrix; - splitUnit(unit: mathjs.Unit, parts: mathjs.Unit[]): mathjs.Unit[]; - string(value: mathjs.MathType | null): string | mathjs.MathArray | mathjs.Matrix; - unit(unit: string): mathjs.Unit; - unit(value: number | mathjs.MathArray | mathjs.Matrix, unit: string): mathjs.Unit; - compile(expr: mathjs.MathExpression): mathjs.EvalFunction; - compile(exprs: mathjs.MathExpression[]): mathjs.EvalFunction[]; - eval(expr: mathjs.MathExpression | mathjs.MathExpression[] | mathjs.Matrix, scope?: object): any; - help(search: () => any): mathjs.Help; - parse(expr: mathjs.MathExpression, options?: any): mathjs.MathNode; - parse(exprs: mathjs.MathExpression[], options?: any): mathjs.MathNode[]; - parser(): mathjs.Parser; - derivative(expr: mathjs.MathNode | string, variable: mathjs.MathNode | string, options?: { - simplify: boolean; - }): mathjs.MathNode; - lsolve(L: mathjs.Matrix | mathjs.MathArray, b: mathjs.Matrix | mathjs.MathArray): mathjs.Matrix | mathjs.MathArray; - lup(A?: mathjs.Matrix | mathjs.MathArray): { - L: mathjs.MathArray | mathjs.Matrix; - U: mathjs.MathArray | mathjs.Matrix; - P: number[]; - }; - lusolve(A: mathjs.Matrix | mathjs.MathArray | number, b: mathjs.Matrix | mathjs.MathArray, order?: number, threshold?: number): mathjs.Matrix | mathjs.MathArray; - qr(A: mathjs.Matrix | mathjs.MathArray): { - Q: mathjs.MathArray | mathjs.Matrix; - R: mathjs.MathArray | mathjs.Matrix; - }; - rationalize(expr: mathjs.MathNode | string, optional?: object | boolean, detailed?: true): { - expression: mathjs.MathNode | string; - variables: string[]; - coefficients: mathjs.MathType[]; - }; - rationalize(expr: mathjs.MathNode | string, optional?: object | boolean, detailed?: false): mathjs.MathNode; - simplify(expr: mathjs.MathNode | string, rules?: Array<({ - l: string; - r: string; - } | string | ((node: mathjs.MathNode) => mathjs.MathNode))>, scope?: object): mathjs.MathNode; - slu(A: mathjs.Matrix, order: number, threshold: number): object; - usolve(U: mathjs.Matrix | mathjs.MathArray, b: mathjs.Matrix | mathjs.MathArray): mathjs.Matrix | mathjs.MathArray; - abs(x: number): number; - abs(x: mathjs.BigNumber): mathjs.BigNumber; - abs(x: mathjs.Fraction): mathjs.Fraction; - abs(x: mathjs.Complex): mathjs.Complex; - abs(x: mathjs.MathArray): mathjs.MathArray; - abs(x: mathjs.Matrix): mathjs.Matrix; - abs(x: mathjs.Unit): mathjs.Unit; - add(x: mathjs.MathType, y: mathjs.MathType): mathjs.MathType; - cbrt(x: number, allRoots?: boolean): number; - cbrt(x: mathjs.BigNumber, allRoots?: boolean): mathjs.BigNumber; - cbrt(x: mathjs.Fraction, allRoots?: boolean): mathjs.Fraction; - cbrt(x: mathjs.Complex, allRoots?: boolean): mathjs.Complex; - cbrt(x: mathjs.MathArray, allRoots?: boolean): mathjs.MathArray; - cbrt(x: mathjs.Matrix, allRoots?: boolean): mathjs.Matrix; - cbrt(x: mathjs.Unit, allRoots?: boolean): mathjs.Unit; - ceil(x: number): number; - ceil(x: mathjs.BigNumber): mathjs.BigNumber; - ceil(x: mathjs.Fraction): mathjs.Fraction; - ceil(x: mathjs.Complex): mathjs.Complex; - ceil(x: mathjs.MathArray): mathjs.MathArray; - ceil(x: mathjs.Matrix): mathjs.Matrix; - ceil(x: mathjs.Unit): mathjs.Unit; - cube(x: number): number; - cube(x: mathjs.BigNumber): mathjs.BigNumber; - cube(x: mathjs.Fraction): mathjs.Fraction; - cube(x: mathjs.Complex): mathjs.Complex; - cube(x: mathjs.MathArray): mathjs.MathArray; - cube(x: mathjs.Matrix): mathjs.Matrix; - cube(x: mathjs.Unit): mathjs.Unit; - divide(x: mathjs.Unit, y: mathjs.Unit): mathjs.Unit; - divide(x: number, y: number): number; - divide(x: mathjs.MathType, y: mathjs.MathType): mathjs.MathType; - dotDivide(x: mathjs.MathType, y: mathjs.MathType): mathjs.MathType; - dotMultiply(x: mathjs.MathType, y: mathjs.MathType): mathjs.MathType; - dotPow(x: mathjs.MathType, y: mathjs.MathType): mathjs.MathType; - exp(x: number): number; - exp(x: mathjs.BigNumber): mathjs.BigNumber; - exp(x: mathjs.Complex): mathjs.Complex; - exp(x: mathjs.MathArray): mathjs.MathArray; - exp(x: mathjs.Matrix): mathjs.Matrix; - expm1(x: number): number; - expm1(x: mathjs.BigNumber): mathjs.BigNumber; - expm1(x: mathjs.Complex): mathjs.Complex; - expm1(x: mathjs.MathArray): mathjs.MathArray; - expm1(x: mathjs.Matrix): mathjs.Matrix; - fix(x: number): number; - fix(x: mathjs.BigNumber): mathjs.BigNumber; - fix(x: mathjs.Fraction): mathjs.Fraction; - fix(x: mathjs.Complex): mathjs.Complex; - fix(x: mathjs.MathArray): mathjs.MathArray; - fix(x: mathjs.Matrix): mathjs.Matrix; - floor(x: number): number; - floor(x: mathjs.BigNumber): mathjs.BigNumber; - floor(x: mathjs.Fraction): mathjs.Fraction; - floor(x: mathjs.Complex): mathjs.Complex; - floor(x: mathjs.MathArray): mathjs.MathArray; - floor(x: mathjs.Matrix): mathjs.Matrix; - gcd(...args: number[]): number; - gcd(...args: mathjs.BigNumber[]): mathjs.BigNumber; - gcd(...args: mathjs.Fraction[]): mathjs.Fraction; - gcd(...args: mathjs.MathArray[]): mathjs.MathArray; - gcd(...args: mathjs.Matrix[]): mathjs.Matrix; - hypot(...args: number[]): number; - hypot(...args: mathjs.BigNumber[]): mathjs.BigNumber; - lcm(a: number, b: number): number; - lcm(a: mathjs.BigNumber, b: mathjs.BigNumber): mathjs.BigNumber; - lcm(a: mathjs.MathArray, b: mathjs.MathArray): mathjs.MathArray; - lcm(a: mathjs.Matrix, b: mathjs.Matrix): mathjs.Matrix; - log(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.MathArray | mathjs.Matrix, base?: number | mathjs.BigNumber | mathjs.Complex): number | mathjs.BigNumber | mathjs.Complex | mathjs.MathArray | mathjs.Matrix; - log10(x: number): number; - log10(x: mathjs.BigNumber): mathjs.BigNumber; - log10(x: mathjs.Complex): mathjs.Complex; - log10(x: mathjs.MathArray): mathjs.MathArray; - log10(x: mathjs.Matrix): mathjs.Matrix; - log1p(x: number, base?: number | mathjs.BigNumber | mathjs.Complex): number; - log1p(x: mathjs.BigNumber, base?: number | mathjs.BigNumber | mathjs.Complex): mathjs.BigNumber; - log1p(x: mathjs.Complex, base?: number | mathjs.BigNumber | mathjs.Complex): mathjs.Complex; - log1p(x: mathjs.MathArray, base?: number | mathjs.BigNumber | mathjs.Complex): mathjs.MathArray; - log1p(x: mathjs.Matrix, base?: number | mathjs.BigNumber | mathjs.Complex): mathjs.Matrix; - log2(x: number): number; - log2(x: mathjs.BigNumber): mathjs.BigNumber; - log2(x: mathjs.Complex): mathjs.Complex; - log2(x: mathjs.MathArray): mathjs.MathArray; - log2(x: mathjs.Matrix): mathjs.Matrix; - multiply(x: mathjs.Matrix | mathjs.MathArray, y: mathjs.MathType): mathjs.Matrix | mathjs.MathArray; - multiply(x: mathjs.Unit, y: mathjs.Unit): mathjs.Unit; - multiply(x: number, y: number): number; - multiply(x: mathjs.MathType, y: mathjs.MathType): mathjs.MathType; - norm(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.MathArray | mathjs.Matrix, p?: number | mathjs.BigNumber | string): number | mathjs.BigNumber; - nthRoot(a: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix | mathjs.Complex, root?: number | mathjs.BigNumber): number | mathjs.Complex | mathjs.MathArray | mathjs.Matrix; - pow(x: mathjs.MathType, y: number | mathjs.BigNumber | mathjs.Complex): mathjs.MathType; - round(x: number | mathjs.BigNumber | mathjs.Fraction | mathjs.Complex | mathjs.MathArray | mathjs.Matrix, n?: number | mathjs.BigNumber | mathjs.MathArray): number | mathjs.BigNumber | mathjs.Fraction | mathjs.Complex | mathjs.MathArray | mathjs.Matrix; - sign(x: number): number; - sign(x: mathjs.BigNumber): mathjs.BigNumber; - sign(x: mathjs.Fraction): mathjs.Fraction; - sign(x: mathjs.Complex): mathjs.Complex; - sign(x: mathjs.MathArray): mathjs.MathArray; - sign(x: mathjs.Matrix): mathjs.Matrix; - sign(x: mathjs.Unit): mathjs.Unit; - sqrt(x: number): number; - sqrt(x: mathjs.BigNumber): mathjs.BigNumber; - sqrt(x: mathjs.Complex): mathjs.Complex; - sqrt(x: mathjs.MathArray): mathjs.MathArray; - sqrt(x: mathjs.Matrix): mathjs.Matrix; - sqrt(x: mathjs.Unit): mathjs.Unit; - square(x: number): number; - square(x: mathjs.BigNumber): mathjs.BigNumber; - square(x: mathjs.Fraction): mathjs.Fraction; - square(x: mathjs.Complex): mathjs.Complex; - square(x: mathjs.MathArray): mathjs.MathArray; - square(x: mathjs.Matrix): mathjs.Matrix; - square(x: mathjs.Unit): mathjs.Unit; - subtract(x: mathjs.MathType, y: mathjs.MathType): mathjs.MathType; - unaryMinus(x: number): number; - unaryMinus(x: mathjs.BigNumber): mathjs.BigNumber; - unaryMinus(x: mathjs.Fraction): mathjs.Fraction; - unaryMinus(x: mathjs.Complex): mathjs.Complex; - unaryMinus(x: mathjs.MathArray): mathjs.MathArray; - unaryMinus(x: mathjs.Matrix): mathjs.Matrix; - unaryMinus(x: mathjs.Unit): mathjs.Unit; - unaryPlus(x: number): number; - unaryPlus(x: mathjs.BigNumber): mathjs.BigNumber; - unaryPlus(x: mathjs.Fraction): mathjs.Fraction; - unaryPlus(x: string): string; - unaryPlus(x: mathjs.Complex): mathjs.Complex; - unaryPlus(x: mathjs.MathArray): mathjs.MathArray; - unaryPlus(x: mathjs.Matrix): mathjs.Matrix; - unaryPlus(x: mathjs.Unit): mathjs.Unit; - xgcd(a: number | mathjs.BigNumber, b: number | mathjs.BigNumber): mathjs.MathArray; - bitAnd(x: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix, y: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix): number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix; - bitNot(x: number): number; - bitNot(x: mathjs.BigNumber): mathjs.BigNumber; - bitNot(x: mathjs.MathArray): mathjs.MathArray; - bitNot(x: mathjs.Matrix): mathjs.Matrix; - bitOr(x: number, y: number): number; - bitOr(x: mathjs.BigNumber, y: mathjs.BigNumber): mathjs.BigNumber; - bitOr(x: mathjs.MathArray, y: mathjs.MathArray): mathjs.MathArray; - bitOr(x: mathjs.Matrix, y: mathjs.Matrix): mathjs.Matrix; - bitXor(x: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix, y: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix): number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix; - leftShift(x: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix, y: number | mathjs.BigNumber): number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix; - rightArithShift(x: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix, y: number | mathjs.BigNumber): number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix; - rightLogShift(x: number | mathjs.MathArray | mathjs.Matrix, y: number): number | mathjs.MathArray | mathjs.Matrix; - bellNumbers(n: number): number; - bellNumbers(n: mathjs.BigNumber): mathjs.BigNumber; - catalan(n: number): number; - catalan(n: mathjs.BigNumber): mathjs.BigNumber; - composition(n: number | mathjs.BigNumber, k: number | mathjs.BigNumber): number | mathjs.BigNumber; - stirlingS2(n: number | mathjs.BigNumber, k: number | mathjs.BigNumber): number | mathjs.BigNumber; - arg(x: number | mathjs.Complex): number; - arg(x: mathjs.BigNumber | mathjs.Complex): mathjs.BigNumber; - arg(x: mathjs.MathArray): mathjs.MathArray; - arg(x: mathjs.Matrix): mathjs.Matrix; - conj(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.MathArray | mathjs.Matrix): number | mathjs.BigNumber | mathjs.Complex | mathjs.MathArray | mathjs.Matrix; - im(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.MathArray | mathjs.Matrix): number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix; - re(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.MathArray | mathjs.Matrix): number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix; - distance(x: mathjs.MathArray | mathjs.Matrix | object, y: mathjs.MathArray | mathjs.Matrix | object): number | mathjs.BigNumber; - intersect(w: mathjs.MathArray | mathjs.Matrix, x: mathjs.MathArray | mathjs.Matrix, y: mathjs.MathArray | mathjs.Matrix, z: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray; - and(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix, y: number | mathjs.BigNumber | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix): boolean | mathjs.MathArray | mathjs.Matrix; - not(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix): boolean | mathjs.MathArray | mathjs.Matrix; - or(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix, y: number | mathjs.BigNumber | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix): boolean | mathjs.MathArray | mathjs.Matrix; - xor(x: number | mathjs.BigNumber | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix, y: number | mathjs.BigNumber | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix): boolean | mathjs.MathArray | mathjs.Matrix; - concat(...args: Array): mathjs.MathArray | mathjs.Matrix; - cross(x: mathjs.MathArray | mathjs.Matrix, y: mathjs.MathArray | mathjs.Matrix): mathjs.Matrix | mathjs.MathArray; - det(x: mathjs.MathArray | mathjs.Matrix): number; - diag(X: mathjs.MathArray | mathjs.Matrix, format?: string): mathjs.Matrix; - diag(X: mathjs.MathArray | mathjs.Matrix, k: number | mathjs.BigNumber, format?: string): mathjs.Matrix | mathjs.MathArray; - dot(x: mathjs.MathArray | mathjs.Matrix, y: mathjs.MathArray | mathjs.Matrix): number; - expm(x: mathjs.Matrix): mathjs.Matrix; - identity(size: number | number[] | mathjs.Matrix | mathjs.MathArray, format?: string): mathjs.Matrix | mathjs.MathArray | number; - identity(m: number, n: number, format?: string): mathjs.Matrix | mathjs.MathArray | number; - filter(x: mathjs.Matrix | mathjs.MathArray | string[], test: ((value: any, index: any, matrix: mathjs.Matrix | mathjs.MathArray | string[]) => boolean) | RegExp): mathjs.Matrix | mathjs.MathArray; - flatten(x: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - forEach(x: mathjs.Matrix | mathjs.MathArray, callback: ((value: any, index: any, matrix: mathjs.Matrix | mathjs.MathArray) => void)): void; - inv(x: number | mathjs.Complex | mathjs.MathArray | mathjs.Matrix): number | mathjs.Complex | mathjs.MathArray | mathjs.Matrix; - kron(x: mathjs.Matrix | mathjs.MathArray, y: mathjs.Matrix | mathjs.MathArray): mathjs.Matrix; - map(x: mathjs.Matrix | mathjs.MathArray, callback: ((value: any, index: any, matrix: mathjs.Matrix | mathjs.MathArray) => mathjs.MathType | string)): mathjs.Matrix | mathjs.MathArray; - ones(size: number | number[], format?: string): mathjs.MathArray | mathjs.Matrix; - ones(m: number, n: number, format?: string): mathjs.MathArray | mathjs.Matrix; - partitionSelect(x: mathjs.MathArray | mathjs.Matrix, k: number, compare?: "asc" | "desc" | ((a: any, b: any) => number)): any; - range(str: string, includeEnd?: boolean): mathjs.Matrix; - range(start: number | mathjs.BigNumber, end: number | mathjs.BigNumber, includeEnd?: boolean): mathjs.Matrix; - range(start: number | mathjs.BigNumber, end: number | mathjs.BigNumber, step: number | mathjs.BigNumber, includeEnd?: boolean): mathjs.Matrix; - reshape(x: mathjs.MathArray | mathjs.Matrix, sizes: number[]): mathjs.MathArray | mathjs.Matrix; - resize(x: mathjs.MathArray | mathjs.Matrix, size: mathjs.MathArray | mathjs.Matrix, defaultValue?: number | string): mathjs.MathArray | mathjs.Matrix; - size(x: boolean | number | mathjs.Complex | mathjs.Unit | string | mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - sort(x: mathjs.Matrix | mathjs.MathArray, compare: ((a: any, b: any) => number) | "asc" | "desc" | "natural"): mathjs.Matrix | mathjs.MathArray; - sqrtm(A: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - squeeze(x: mathjs.MathArray | mathjs.Matrix): mathjs.Matrix | mathjs.MathArray; - subset(value: mathjs.MathArray | mathjs.Matrix | string, index: mathjs.Index, replacement?: any, defaultValue?: any): mathjs.MathArray | mathjs.Matrix | string; - trace(x: mathjs.MathArray | mathjs.Matrix): number; - transpose(x: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - zeros(size: number | number[], format?: string): mathjs.MathArray | mathjs.Matrix; - zeros(m: number, n: number, format?: string): mathjs.MathArray | mathjs.Matrix; - factorial(n: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix): number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix; - gamma(n: number | mathjs.MathArray | mathjs.Matrix): number | mathjs.MathArray | mathjs.Matrix; - kldivergence(q: mathjs.MathArray | mathjs.Matrix, p: mathjs.MathArray | mathjs.Matrix): number; - multinomial(a: number[] | mathjs.BigNumber[]): number | mathjs.BigNumber; - permutations(n: number | mathjs.BigNumber, k?: number | mathjs.BigNumber): number | mathjs.BigNumber; - pickRandom(array: number[], number?: number, weights?: number[]): number; - random(min?: number, max?: number): number; - random(size: mathjs.MathArray | mathjs.Matrix, min?: number, max?: number): mathjs.MathArray | mathjs.Matrix; - randomInt(min: number, max?: number): number; - randomInt(size: mathjs.MathArray | mathjs.Matrix, min?: number, max?: number): mathjs.MathArray | mathjs.Matrix; - compare(x: mathjs.MathType | string, y: mathjs.MathType | string): number | mathjs.BigNumber | mathjs.Fraction | mathjs.MathArray | mathjs.Matrix; - compareNatural(x: any, y: any): number; - compareText(x: string | mathjs.MathArray | mathjs.Matrix, y: string | mathjs.MathArray | mathjs.Matrix): number | mathjs.MathArray | mathjs.Matrix; - deepEqual(x: mathjs.MathType, y: mathjs.MathType): number | mathjs.BigNumber | mathjs.Fraction | mathjs.Complex | mathjs.Unit | mathjs.MathArray | mathjs.Matrix; - equal(x: mathjs.MathType | string, y: mathjs.MathType | string): boolean | mathjs.MathArray | mathjs.Matrix; - equalText(x: string | mathjs.MathArray | mathjs.Matrix, y: string | mathjs.MathArray | mathjs.Matrix): number | mathjs.MathArray | mathjs.Matrix; - larger(x: mathjs.MathType | string, y: mathjs.MathType | string): boolean | mathjs.MathArray | mathjs.Matrix; - largerEq(x: mathjs.MathType | string, y: mathjs.MathType | string): boolean | mathjs.MathArray | mathjs.Matrix; - smaller(x: mathjs.MathType | string, y: mathjs.MathType | string): boolean | mathjs.MathArray | mathjs.Matrix; - smallerEq(x: mathjs.MathType | string, y: mathjs.MathType | string): boolean | mathjs.MathArray | mathjs.Matrix; - unequal(x: mathjs.MathType | string, y: mathjs.MathType | string): boolean | mathjs.MathArray | mathjs.Matrix; - setCartesian(a1: mathjs.MathArray | mathjs.Matrix, a2: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - setDifference(a1: mathjs.MathArray | mathjs.Matrix, a2: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - setDistinct(a: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - setIntersect(a1: mathjs.MathArray | mathjs.Matrix, a2: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - setIsSubset(a1: mathjs.MathArray | mathjs.Matrix, a2: mathjs.MathArray | mathjs.Matrix): boolean; - setMultiplicity(e: number | mathjs.BigNumber | mathjs.Fraction | mathjs.Complex, a: mathjs.MathArray | mathjs.Matrix): number; - setPowerset(a: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - setSize(a: mathjs.MathArray | mathjs.Matrix): number; - setSymDifference(a1: mathjs.MathArray | mathjs.Matrix, a2: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - setUnion(a1: mathjs.MathArray | mathjs.Matrix, a2: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - erf(x: number | mathjs.MathArray | mathjs.Matrix): number | mathjs.MathArray | mathjs.Matrix; - mad(array: mathjs.MathArray | mathjs.Matrix): any; - max(...args: mathjs.MathType[]): any; - max(A: mathjs.MathArray | mathjs.Matrix, dim?: number): any; - mean(...args: mathjs.MathType[]): any; - mean(A: mathjs.MathArray | mathjs.Matrix, dim?: number): any; - median(...args: mathjs.MathType[]): any; - min(...args: mathjs.MathType[]): any; - min(A: mathjs.MathArray | mathjs.Matrix, dim?: number): any; - mode(...args: mathjs.MathType[]): any; - prod(...args: mathjs.MathType[]): any; - quantileSeq(A: mathjs.MathArray | mathjs.Matrix, prob: number | mathjs.BigNumber | mathjs.MathArray, sorted?: boolean): number | mathjs.BigNumber | mathjs.Unit | mathjs.MathArray; - std(array: mathjs.MathArray | mathjs.Matrix, normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased"): number; - sum(...args: Array): any; - sum(array: mathjs.MathArray | mathjs.Matrix): any; - var(...args: Array): any; - var(array: mathjs.MathArray | mathjs.Matrix, normalization?: "unbiased" | "uncorrected" | "biased" | "unbiased"): any; - format(value: any, options?: mathjs.FormatOptions | number | ((item: any) => string), callback?: ((value: any) => string)): string; - print(template: string, values: any, precision?: number, options?: number | object): void; - acos(x: number): number; - acos(x: mathjs.BigNumber): mathjs.BigNumber; - acos(x: mathjs.Complex): mathjs.Complex; - acos(x: mathjs.MathArray): mathjs.MathArray; - acos(x: mathjs.Matrix): mathjs.Matrix; - acosh(x: number): number; - acosh(x: mathjs.BigNumber): mathjs.BigNumber; - acosh(x: mathjs.Complex): mathjs.Complex; - acosh(x: mathjs.MathArray): mathjs.MathArray; - acosh(x: mathjs.Matrix): mathjs.Matrix; - acot(x: number): number; - acot(x: mathjs.BigNumber): mathjs.BigNumber; - acot(x: mathjs.MathArray): mathjs.MathArray; - acot(x: mathjs.Matrix): mathjs.Matrix; - acoth(x: number): number; - acoth(x: mathjs.BigNumber): mathjs.BigNumber; - acoth(x: mathjs.MathArray): mathjs.MathArray; - acoth(x: mathjs.Matrix): mathjs.Matrix; - acsc(x: number): number; - acsc(x: mathjs.BigNumber): mathjs.BigNumber; - acsc(x: mathjs.MathArray): mathjs.MathArray; - acsc(x: mathjs.Matrix): mathjs.Matrix; - acsch(x: number): number; - acsch(x: mathjs.BigNumber): mathjs.BigNumber; - acsch(x: mathjs.MathArray): mathjs.MathArray; - acsch(x: mathjs.Matrix): mathjs.Matrix; - asec(x: number): number; - asec(x: mathjs.BigNumber): mathjs.BigNumber; - asec(x: mathjs.MathArray): mathjs.MathArray; - asec(x: mathjs.Matrix): mathjs.Matrix; - asech(x: number): number; - asech(x: mathjs.BigNumber): mathjs.BigNumber; - asech(x: mathjs.MathArray): mathjs.MathArray; - asech(x: mathjs.Matrix): mathjs.Matrix; - asin(x: number): number; - asin(x: mathjs.BigNumber): mathjs.BigNumber; - asin(x: mathjs.Complex): mathjs.Complex; - asin(x: mathjs.MathArray): mathjs.MathArray; - asin(x: mathjs.Matrix): mathjs.Matrix; - asinh(x: number): number; - asinh(x: mathjs.BigNumber): mathjs.BigNumber; - asinh(x: mathjs.MathArray): mathjs.MathArray; - asinh(x: mathjs.Matrix): mathjs.Matrix; - atan(x: number): number; - atan(x: mathjs.BigNumber): mathjs.BigNumber; - atan(x: mathjs.MathArray): mathjs.MathArray; - atan(x: mathjs.Matrix): mathjs.Matrix; - atan2(y: number, x: number): number; - atan2(y: mathjs.MathArray | mathjs.Matrix, x: mathjs.MathArray | mathjs.Matrix): mathjs.MathArray | mathjs.Matrix; - atanh(x: number): number; - atanh(x: mathjs.BigNumber): mathjs.BigNumber; - atanh(x: mathjs.MathArray): mathjs.MathArray; - atanh(x: mathjs.Matrix): mathjs.Matrix; - cos(x: number | mathjs.Unit): number; - cos(x: mathjs.BigNumber): mathjs.BigNumber; - cos(x: mathjs.Complex): mathjs.Complex; - cos(x: mathjs.MathArray): mathjs.MathArray; - cos(x: mathjs.Matrix): mathjs.Matrix; - cosh(x: number | mathjs.Unit): number; - cosh(x: mathjs.BigNumber): mathjs.BigNumber; - cosh(x: mathjs.Complex): mathjs.Complex; - cosh(x: mathjs.MathArray): mathjs.MathArray; - cosh(x: mathjs.Matrix): mathjs.Matrix; - cot(x: number | mathjs.Unit): number; - cot(x: mathjs.Complex): mathjs.Complex; - cot(x: mathjs.MathArray): mathjs.MathArray; - cot(x: mathjs.Matrix): mathjs.Matrix; - coth(x: number | mathjs.Unit): number; - coth(x: mathjs.Complex): mathjs.Complex; - coth(x: mathjs.MathArray): mathjs.MathArray; - coth(x: mathjs.Matrix): mathjs.Matrix; - csc(x: number | mathjs.Unit): number; - csc(x: mathjs.Complex): mathjs.Complex; - csc(x: mathjs.MathArray): mathjs.MathArray; - csc(x: mathjs.Matrix): mathjs.Matrix; - csch(x: number | mathjs.Unit): number; - csch(x: mathjs.Complex): mathjs.Complex; - csch(x: mathjs.MathArray): mathjs.MathArray; - csch(x: mathjs.Matrix): mathjs.Matrix; - sec(x: number | mathjs.Unit): number; - sec(x: mathjs.Complex): mathjs.Complex; - sec(x: mathjs.MathArray): mathjs.MathArray; - sec(x: mathjs.Matrix): mathjs.Matrix; - sech(x: number | mathjs.Unit): number; - sech(x: mathjs.Complex): mathjs.Complex; - sech(x: mathjs.MathArray): mathjs.MathArray; - sech(x: mathjs.Matrix): mathjs.Matrix; - sin(x: number | mathjs.Unit): number; - sin(x: mathjs.BigNumber): mathjs.BigNumber; - sin(x: mathjs.Complex): mathjs.Complex; - sin(x: mathjs.MathArray): mathjs.MathArray; - sin(x: mathjs.Matrix): mathjs.Matrix; - sinh(x: number | mathjs.Unit): number; - sinh(x: mathjs.BigNumber): mathjs.BigNumber; - sinh(x: mathjs.Complex): mathjs.Complex; - sinh(x: mathjs.MathArray): mathjs.MathArray; - sinh(x: mathjs.Matrix): mathjs.Matrix; - tan(x: number | mathjs.Unit): number; - tan(x: mathjs.BigNumber): mathjs.BigNumber; - tan(x: mathjs.Complex): mathjs.Complex; - tan(x: mathjs.MathArray): mathjs.MathArray; - tan(x: mathjs.Matrix): mathjs.Matrix; - tanh(x: number | mathjs.Unit): number; - tanh(x: mathjs.BigNumber): mathjs.BigNumber; - tanh(x: mathjs.Complex): mathjs.Complex; - tanh(x: mathjs.MathArray): mathjs.MathArray; - tanh(x: mathjs.Matrix): mathjs.Matrix; - to(x: mathjs.Unit | mathjs.MathArray | mathjs.Matrix, unit: mathjs.Unit | string): mathjs.Unit | mathjs.MathArray | mathjs.Matrix; - clone(x: any): any; - isInteger(x: number | mathjs.BigNumber | mathjs.Fraction | mathjs.MathArray | mathjs.Matrix): boolean; - isNaN(x: number | mathjs.BigNumber | mathjs.Fraction | mathjs.MathArray | mathjs.Matrix | mathjs.Unit): boolean; - isNegative(x: number | mathjs.BigNumber | mathjs.Fraction | mathjs.MathArray | mathjs.Matrix | mathjs.Unit): boolean; - isNumeric(x: any): x is number | mathjs.BigNumber | mathjs.Fraction | boolean; - isPositive(x: number | mathjs.BigNumber | mathjs.Fraction | mathjs.MathArray | mathjs.Matrix | mathjs.Unit): boolean; - isPrime(x: number | mathjs.BigNumber | mathjs.MathArray | mathjs.Matrix): boolean; - isZero(x: number | mathjs.BigNumber | mathjs.Fraction | mathjs.MathArray | mathjs.Matrix | mathjs.Unit | mathjs.Complex): boolean; - typeof(x: any): string; - import(object: mathjs.ImportObject | mathjs.ImportObject[], options: mathjs.ImportOptions): void; -}; diff --git a/dist/js/math.js b/dist/js/math.js deleted file mode 100644 index e92525c5..00000000 --- a/dist/js/math.js +++ /dev/null @@ -1,276 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.math = exports.roundArrayOrNumber = exports.roundCustom = exports.RoundingMethodEnum = void 0; -exports.numberToPrecision = numberToPrecision; -/* eslint-disable */ -const mathjs_1 = __importDefault(require("mathjs")); -const underscore_1 = __importDefault(require("underscore")); -const constants_1 = require("./constants"); -/** - * @summary Zero threshold. Numbers below it are put to zero exactly. - * Used to avoid math.js bug in treating zero as X.XXe-16. - */ -const EPSILON = 1e-8; -/** - * @summary Returns scalar product of vectors - * @param v1 Vector 1 - * @param v2 Vector 2 - */ -const product = (v1, v2) => { - if (v1.length !== v2.length) { - throw new Error("Vectors must be of the same length"); - } - return Number(exports.math.multiply(v1, exports.math.transpose(v2))); -}; -/** - * @summary Returns length of a vector. - * @param v Vector - */ -const vlen = (v) => { - return exports.math.sqrt(product(v, v)); -}; -/** - * @summary Returns angle between `a` and `b` vectors. - * @param a Vector a - * @param b Vector b - * @param unit `rad`, `deg` - */ -const angle = (a, b, unit) => { - const lenA = vlen(a); - const lenB = vlen(b); - // @ts-ignore - return exports.math.unit(exports.math.acos(product(a, b) / (lenA * lenB)), "rad").toNumber(unit || "deg"); -}; -const angleUpTo90 = (a, b, unit) => { - const angleUpTo180 = angle(a, b, unit); - return angleUpTo180 < 90 ? angleUpTo180 : 180 - angleUpTo180; -}; -/** - * @summary Returns distance between 2 vectors. - * @param v1 {Number[]} Vector - * @param v2 {Number[]} Vector - * @return {Number} - */ -const vDist = (v1, v2) => { - if (v1.length !== v2.length) { - console.error("Attempting to calculate distance between vectors of different dimensionality"); - return; - } - return vlen(v1.map((coordinate, index) => coordinate - v2[index])); -}; -/** - * @summary Returns checks whether 2 vector are equal within tolerance. - * @param vec1 {Number[]} Vector - * @param vec2 {Number[]} Vector - * @param tolerance {Number} Tolerance - * @return {Number} - */ -const vEqualWithTolerance = (vec1, vec2, tolerance = constants_1.tolerance.pointsDistance) => { - const val = vDist(vec1, vec2); - if (typeof val === "undefined") { - return false; - } - // @ts-ignore - return val <= tolerance; -}; -/** - * @summary Returns 0 if passed number is less than Made.math.EPSILON. - * @param n {Number} - * @return {Number} - */ -const roundToZero = (n) => { - return Math.abs(n) < EPSILON ? 0 : n; -}; -/** - * @summary Returns number with specified precision. - */ -const precise = (x, n = 7) => { - return Number(x.toPrecision(n)); -}; -/** - * @summary Returns mod of the passed value with the specified tolerance. - */ -const mod = (num, tolerance = 0.001) => { - const m = num % 1; - const x = num >= 0 ? m : 1 + m; - if (exports.math.smallerEq(Math.abs(x - 1), tolerance) || exports.math.smallerEq(Math.abs(x), tolerance)) { - return 0; - } - return x; -}; -/** - * @summary Returns cartesian of passed arrays. - * @example combinations([1,2], [4,5], [6]) = [[1,4,6], [1,5,6], [2,4,6], [2,5,6]]; - */ -const cartesianProduct = (...arg) => { - const r = []; - const max = arg.length - 1; - const helper = (arr, i) => { - for (let j = 0, l = arg[i].length; j < l; j++) { - const a = arr.slice(0); // clone arr - a.push(arg[i][j]); - if (i === max) { - r.push(a); - } - else { - helper(a, i + 1); - } - } - }; - helper([], 0); - return r; -}; -/** - * @summary Returns all possible positive integer combinations where each value changes from 0 to a, b, c. - */ -const almostEqual = (a, b, tolerance = constants_1.tolerance.pointsDistance) => { - return Math.abs(a - b) < tolerance; -}; -/** - * @summary Returns true if number is 0 <= x < 1, inclusive, otherwise false. - * Helper to deal with JS arithmetic artifacts. - */ -const isBetweenZeroInclusiveAndOne = (number, tolerance = constants_1.tolerance.length) => { - return roundToZero(number) >= 0 && !almostEqual(number, 1, tolerance) && number < 1; -}; -/** - * @summary Returns all possible positive integer combinations where each value changes from 0 to a, b, c. - * @example - * var comb = combinations(1, 2, 0); - * // [[0, 0, 0], [0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 1, 0], [1, 2, 0]] - * @param a - * @param b - * @param c - */ -const combinations = (a, b, c) => { - const combs = []; - for (let i = 0; i <= a; i++) { - for (let j = 0; j <= b; j++) { - for (let k = 0; k <= c; k++) { - combs.push([i, j, k]); - } - } - } - return combs; -}; -/* - * @summary Same as `combinations` but accepting intervals (tuples) of integers: eg. [-3, 4] - */ -const combinationsFromIntervals = (arrA, arrB, arrC) => { - const combs = []; - for (let i = arrA[0]; i <= arrA[1]; i++) { - for (let j = arrB[0]; j <= arrB[1]; j++) { - for (let k = arrC[0]; k <= arrC[1]; k++) { - combs.push([i, j, k]); - } - } - } - return combs; -}; -const roundValueToNDecimals = (value, decimals = 3) => { - return parseFloat(value.toFixed(decimals)); -}; -// See: https://en.wikipedia.org/wiki/Rounding -var RoundingMethodEnum; -(function (RoundingMethodEnum) { - RoundingMethodEnum["Bankers"] = "bankers"; - RoundingMethodEnum["HalfAwayFromZero"] = "halfAwayFromZero"; -})(RoundingMethodEnum || (exports.RoundingMethodEnum = RoundingMethodEnum = {})); -const roundCustom = (value, decimals = 0, method = RoundingMethodEnum.HalfAwayFromZero) => { - const factor = Math.pow(10, decimals); - const scaledValue = value * factor; - const absValue = Math.abs(scaledValue); - const sign = scaledValue < 0 ? -1 : 1; - let roundedAbs; - switch (method) { - case RoundingMethodEnum.HalfAwayFromZero: - roundedAbs = Math.round(absValue); - break; - case RoundingMethodEnum.Bankers: - const floorValue = Math.floor(absValue); - const fractional = absValue - floorValue; - if (Math.abs(fractional - 0.5) < Number.EPSILON) { - // Round to even - roundedAbs = floorValue % 2 === 0 ? floorValue : floorValue + 1; - } - else { - roundedAbs = Math.round(absValue); - } - break; - default: - throw new Error(`Unsupported rounding method: ${method}`); - } - return (roundedAbs * sign) / factor; -}; -exports.roundCustom = roundCustom; -const roundArrayOrNumber = (value, decimals = 9, method = RoundingMethodEnum.HalfAwayFromZero) => { - if (Array.isArray(value)) { - return value.map((v) => (typeof v === "number" ? (0, exports.roundCustom)(v, decimals, method) : v)); - } - return typeof value === "number" ? (0, exports.roundCustom)(value, decimals, method) : value; -}; -exports.roundArrayOrNumber = roundArrayOrNumber; -/** - * @summary Returns n splits of the passed segment. - */ -const calculateSegmentsBetweenPoints3D = (point1, point2, n) => { - // safely parse if passed strings - const point1_ = point1.map((x) => (typeof x === "string" ? parseFloat(x) : x)); - const point2_ = point2.map((x) => (typeof x === "string" ? parseFloat(x) : x)); - const n_ = typeof n === "string" ? parseInt(n) : n; - const result = []; - for (let i = 1; i < n_; i++) { - const lambda = i / (n_ - i); - result.push([ - (point1_[0] + lambda * point2_[0]) / (1 + lambda), - (point1_[1] + lambda * point2_[1]) / (1 + lambda), - (point1_[2] + lambda * point2_[2]) / (1 + lambda), - ]); - } - return result; -}; -/** - * @summary Wrapper for native [Number.toPrecision](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision) method. - * Returns a string representing the Number object to the specified precision. - * @memberOf Helpers - * @package exabyte:core - * @locus Client - * @method - * @name toPrecision - * @param number - * @param precision Optional. An integer specifying the number of significant digits. - */ -function numberToPrecision(number, precision) { - if (underscore_1.default.isNumber(number)) { - return number.toPrecision(precision); - } - return number; -} -exports.math = { - ...mathjs_1.default, - PI: Math.PI, - trunc: Math.trunc, - product, - vlen, - angle, - angleUpTo90, - vDist, - vEqualWithTolerance, - mod, - isBetweenZeroInclusiveAndOne, - cartesianProduct, - almostEqual, - combinations, - combinationsFromIntervals, - calculateSegmentsBetweenPoints3D, - roundToZero, - precise, - roundValueToNDecimals, - numberToPrecision, - roundCustom: exports.roundCustom, - RoundingMethod: RoundingMethodEnum, - roundArrayOrNumber: exports.roundArrayOrNumber, -}; diff --git a/dist/js/utils/array.d.ts b/dist/js/utils/array.d.ts deleted file mode 100644 index 28e88b91..00000000 --- a/dist/js/utils/array.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export function safeMakeArray(x: any): any[]; -/** - * @summary Returns objects array in compact csv format. E.g.: - * [{a: 1, b: 2}, {a: 2, d: 3}] -> [['a','b','d'],[1, 2, null], [2, null, 3]] - * @param objects - */ -export function convertToCompactCSVArrayOfObjects(objects: any): any[][]; diff --git a/dist/js/utils/array.js b/dist/js/utils/array.js deleted file mode 100644 index 7a85370d..00000000 --- a/dist/js/utils/array.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.safeMakeArray = safeMakeArray; -exports.convertToCompactCSVArrayOfObjects = convertToCompactCSVArrayOfObjects; -const lodash_1 = __importDefault(require("lodash")); -const underscore_1 = __importDefault(require("underscore")); -function safeMakeArray(x) { - if (!lodash_1.default.isArray(x)) - return [x]; - return x; -} -/** - * @summary Returns objects array in compact csv format. E.g.: - * [{a: 1, b: 2}, {a: 2, d: 3}] -> [['a','b','d'],[1, 2, null], [2, null, 3]] - * @param objects - */ -function convertToCompactCSVArrayOfObjects(objects) { - const headers = underscore_1.default.uniq(underscore_1.default.flatten(objects.map((x) => underscore_1.default.keys(x)))); - const result = [headers]; - objects.forEach((x) => { - const row = []; - headers.forEach((header) => { - // eslint-disable-next-line no-prototype-builtins - row.push(x.hasOwnProperty(header) ? x[header] : null); - }); - result.push(row); - }); - return result; -} diff --git a/dist/js/utils/class.d.ts b/dist/js/utils/class.d.ts deleted file mode 100644 index 14881af0..00000000 --- a/dist/js/utils/class.d.ts +++ /dev/null @@ -1 +0,0 @@ -export function cloneClass(classToClone: any): any; diff --git a/dist/js/utils/class.js b/dist/js/utils/class.js deleted file mode 100644 index 33539174..00000000 --- a/dist/js/utils/class.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.cloneClass = cloneClass; -function cloneClass(classToClone) { - return Object.assign(Object.create(Object.getPrototypeOf(classToClone)), classToClone); -} diff --git a/dist/js/utils/clone.d.ts b/dist/js/utils/clone.d.ts deleted file mode 100644 index 5e5d9dd8..00000000 --- a/dist/js/utils/clone.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export function deepClone(obj: any): any; -export function clone(obj: any): any; diff --git a/dist/js/utils/clone.js b/dist/js/utils/clone.js deleted file mode 100644 index a8c6fa50..00000000 --- a/dist/js/utils/clone.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.deepClone = deepClone; -exports.clone = clone; -function deepClone(obj) { - return structuredClone(obj); -} -function clone(obj) { - return { ...obj }; -} diff --git a/dist/js/utils/codemirror.d.ts b/dist/js/utils/codemirror.d.ts deleted file mode 100644 index a5244e46..00000000 --- a/dist/js/utils/codemirror.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const refreshCodeMirror: (containerId: string) => void; diff --git a/dist/js/utils/codemirror.js b/dist/js/utils/codemirror.js deleted file mode 100644 index 9c98ba75..00000000 --- a/dist/js/utils/codemirror.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.refreshCodeMirror = void 0; -const forEach_1 = __importDefault(require("lodash/forEach")); -const refreshCodeMirror = (containerId) => { - const container = document.getElementById(containerId); - const editors = container === null || container === void 0 ? void 0 : container.getElementsByClassName("CodeMirror"); - // @ts-ignore - (0, forEach_1.default)(editors, (cm) => cm.CodeMirror.refresh()); -}; -exports.refreshCodeMirror = refreshCodeMirror; diff --git a/dist/js/utils/file.d.ts b/dist/js/utils/file.d.ts deleted file mode 100644 index 8c83adb4..00000000 --- a/dist/js/utils/file.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @summary Identifies language by file extension. Uses 'fortran' by default. - * @param filename {String} - * @param defaultLanguage {String} - */ -export function getProgrammingLanguageFromFileExtension(filename: string, defaultLanguage?: string): any; -/** - * @summary Formats a given file size. - * @param size {Number} file size. - * @param decimals {Number} number of decimals to round. - */ -export function formatFileSize(size: number, decimals?: number): string; -/** Get list of paths for files in a directory and filter by file extensions if provided. - * @param {string} dirPath - Path to current directory, i.e. $PWD - * @param {string[]} fileExtensions - File extensions to filter, e.g. `.yml` - * @param {boolean} resolvePath - whether to resolve the paths of files - * @returns {string[]} - Array of file paths - */ -export function getFilesInDirectory(dirPath: string, fileExtensions?: string[], resolvePath?: boolean): string[]; -/** - * Get list of directories contained in current directory. - * @param {string} currentPath - current directory - * @return {*} - */ -export function getDirectories(currentPath: string): any; -/** - * Construct object path compatible with lodash.get/lodash.set from file path. - * Note: if no root path is provided the file's dirname is taken instead. - * @param {string} filePath - Path to file. - * @param {string} root - Path to a parent directory to construct relative path. - * @return {string} - Object path reflecting file path. - * @example - * createObjectPathFromFilePath("/a/b/c/d/e.yml", "/a/b"); - * // "['c']['d']['e']" - */ -export function createObjectPathFromFilePath(filePath: string, root: string): string; diff --git a/dist/js/utils/file.js b/dist/js/utils/file.js deleted file mode 100644 index ecfd45da..00000000 --- a/dist/js/utils/file.js +++ /dev/null @@ -1,84 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getProgrammingLanguageFromFileExtension = getProgrammingLanguageFromFileExtension; -exports.formatFileSize = formatFileSize; -exports.getFilesInDirectory = getFilesInDirectory; -exports.getDirectories = getDirectories; -exports.createObjectPathFromFilePath = createObjectPathFromFilePath; -const fs_1 = __importDefault(require("fs")); -const path_1 = __importDefault(require("path")); -const FILE_EXTENSION_TO_PROGRAMMING_LANGUAGE_MAP = { - in: "fortran", - sh: "shell", - bash: "shell", - zsh: "shell", - pbs: "shell", - py: "python", -}; -/** - * @summary Identifies language by file extension. Uses 'fortran' by default. - * @param filename {String} - * @param defaultLanguage {String} - */ -function getProgrammingLanguageFromFileExtension(filename, defaultLanguage = "fortran") { - const fileExt = filename.split(".").pop().toLowerCase(); - return FILE_EXTENSION_TO_PROGRAMMING_LANGUAGE_MAP[fileExt] || defaultLanguage; -} -/** - * @summary Formats a given file size. - * @param size {Number} file size. - * @param decimals {Number} number of decimals to round. - */ -function formatFileSize(size, decimals = 2) { - if (size === 0) - return "0 Bytes"; - const index = Math.floor(Math.log(size) / Math.log(1024)); - const units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; - return parseFloat((size / 1024 ** index).toFixed(decimals)) + " " + units[index]; -} -/** Get list of paths for files in a directory and filter by file extensions if provided. - * @param {string} dirPath - Path to current directory, i.e. $PWD - * @param {string[]} fileExtensions - File extensions to filter, e.g. `.yml` - * @param {boolean} resolvePath - whether to resolve the paths of files - * @returns {string[]} - Array of file paths - */ -function getFilesInDirectory(dirPath, fileExtensions = [], resolvePath = true) { - let fileNames = fs_1.default.readdirSync(dirPath); - if (fileExtensions.length) { - fileNames = fileNames.filter((dirItem) => fileExtensions.includes(path_1.default.extname(dirItem))); - } - if (resolvePath) - return fileNames.map((fileName) => path_1.default.resolve(dirPath, fileName)); - return fileNames; -} -/** - * Get list of directories contained in current directory. - * @param {string} currentPath - current directory - * @return {*} - */ -function getDirectories(currentPath) { - return fs_1.default - .readdirSync(currentPath, { withFileTypes: true }) - .filter((dirent) => dirent.isDirectory()) - .map((dirent) => dirent.name); -} -/** - * Construct object path compatible with lodash.get/lodash.set from file path. - * Note: if no root path is provided the file's dirname is taken instead. - * @param {string} filePath - Path to file. - * @param {string} root - Path to a parent directory to construct relative path. - * @return {string} - Object path reflecting file path. - * @example - * createObjectPathFromFilePath("/a/b/c/d/e.yml", "/a/b"); - * // "['c']['d']['e']" - */ -function createObjectPathFromFilePath(filePath, root) { - const dirname = path_1.default.dirname(filePath); - const extension = path_1.default.extname(filePath); - const basename = path_1.default.basename(filePath, extension); - const parentDirs = root ? path_1.default.relative(root, dirname).split(path_1.default.sep) : []; - return [...parentDirs, basename].map((item) => `['${item}']`).join(""); -} diff --git a/dist/js/utils/filter.d.ts b/dist/js/utils/filter.d.ts deleted file mode 100644 index dda623bd..00000000 --- a/dist/js/utils/filter.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -interface PathObject { - path: string; -} -export interface FilterObject { - path?: string; - regex?: RegExp; -} -interface FilterEntityListProps { - entitiesOrPaths: PathObject[]; - filterObjects?: FilterObject[]; - multiPathSeparator?: string; -} -/** - * Filter list of entity paths or entities by paths and regular expressions. - * @return {Object[]} - filtered entity path objects or entities - */ -export declare function filterEntityList({ entitiesOrPaths, filterObjects, multiPathSeparator, }: FilterEntityListProps): PathObject[]; -export {}; diff --git a/dist/js/utils/filter.js b/dist/js/utils/filter.js deleted file mode 100644 index 645d7c16..00000000 --- a/dist/js/utils/filter.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.filterEntityList = filterEntityList; -const uniqBy_1 = __importDefault(require("lodash/uniqBy")); -/** - * Check if one path matches regular expression or exact string. - */ -function isPathSupported(pathObject, filterObjects) { - return filterObjects.some((filterObj) => { - if (filterObj.path) { - return filterObj.path === pathObject.path; - } - if (filterObj.regex) { - return filterObj.regex.test(pathObject.path); - } - return false; - }); -} -/** - * Check if _all_ paths in concatenated path match filtering conditions. - * @param {{path: string}} pathObject - Path object with concatenated path (multipath) - * @param {string} multiPathSeparator - String sequence used for concatenation of paths - * @param {Array<{path: string}|{regex: RegExp}>} filterObjects - Filter conditions - * @return {boolean} - */ -function isMultiPathSupported(pathObject, multiPathSeparator, filterObjects) { - const expandedPaths = pathObject.path.split(multiPathSeparator).map((p) => ({ path: p })); - return expandedPaths.every((expandedPath) => isPathSupported(expandedPath, filterObjects)); -} -/** - * Filter list of entity paths or entities by paths and regular expressions. - * @return {Object[]} - filtered entity path objects or entities - */ -function filterEntityList({ entitiesOrPaths, filterObjects = [], multiPathSeparator = "", }) { - if (!filterObjects || !filterObjects.length) - return []; - const filterObjects_ = filterObjects.map((o) => (o.regex ? { regex: new RegExp(o.regex) } : o)); - let filtered; - if (multiPathSeparator) { - filtered = entitiesOrPaths.filter((e) => isMultiPathSupported(e, multiPathSeparator, filterObjects_)); - } - else { - filtered = entitiesOrPaths.filter((e) => isPathSupported(e, filterObjects_)); - } - return (0, uniqBy_1.default)(filtered, "path"); -} diff --git a/dist/js/utils/github.d.ts b/dist/js/utils/github.d.ts deleted file mode 100644 index e0346bb6..00000000 --- a/dist/js/utils/github.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Fetches file metadata from a GitHub repository using the GitHub API. - * - * The GitHub API returns an array of file objects in the repository. Each file object includes details such as - * the file name, download URL, Git data URL, HTML URL, file path, SHA hash, size, type, and metadata URL. - * - * @param {string} url - The URL of the GitHub API endpoint to fetch the files from. - * @returns {Promise>} - * - A promise that resolves to an array of objects. Each object contains the properties `name`, `download_url`, - * `git_url`, `html_url`, `path`, `sha`, `size`, `type`, and `url`. - * @throws {Error} - Rethrows any error encountered during the fetch operation or data processing, - * allowing the caller of the function to handle it as needed. - * - * @example - * // Example URL for GitHub API - * const url = "https://api.github.com/repos/username/repo/contents/path/to/directory"; - * fetchFiles(url).then(files => { - * files.forEach(file => { - * console.log(`File Name: ${file.name}, Download URL: ${file.download_url}`); - * // Other properties can also be accessed here - * }); - * }).catch(error => { - * console.error("Error fetching files:", error); - * }); - */ -export function fetchFilesFromGitHubAPI(url: string): Promise>; diff --git a/dist/js/utils/github.js b/dist/js/utils/github.js deleted file mode 100644 index 3362ad57..00000000 --- a/dist/js/utils/github.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fetchFilesFromGitHubAPI = fetchFilesFromGitHubAPI; -/** - * Fetches file metadata from a GitHub repository using the GitHub API. - * - * The GitHub API returns an array of file objects in the repository. Each file object includes details such as - * the file name, download URL, Git data URL, HTML URL, file path, SHA hash, size, type, and metadata URL. - * - * @param {string} url - The URL of the GitHub API endpoint to fetch the files from. - * @returns {Promise>} - * - A promise that resolves to an array of objects. Each object contains the properties `name`, `download_url`, - * `git_url`, `html_url`, `path`, `sha`, `size`, `type`, and `url`. - * @throws {Error} - Rethrows any error encountered during the fetch operation or data processing, - * allowing the caller of the function to handle it as needed. - * - * @example - * // Example URL for GitHub API - * const url = "https://api.github.com/repos/username/repo/contents/path/to/directory"; - * fetchFiles(url).then(files => { - * files.forEach(file => { - * console.log(`File Name: ${file.name}, Download URL: ${file.download_url}`); - * // Other properties can also be accessed here - * }); - * }).catch(error => { - * console.error("Error fetching files:", error); - * }); - */ -async function fetchFilesFromGitHubAPI(url) { - try { - const response = await fetch(url); - const data = await response.json(); - return data.map((file) => ({ - name: file.name, - download_url: file.download_url, - })); - } - catch (error) { - console.error("Error fetching files:", error); - throw error; - } -} diff --git a/dist/js/utils/graph.d.ts b/dist/js/utils/graph.d.ts deleted file mode 100644 index 0c53651d..00000000 --- a/dist/js/utils/graph.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { SubworkflowUnitSchema } from "@mat3ra/esse/dist/js/types"; -import { InMemoryEntity } from "../entity/in_memory"; -export type UnitEntity = SubworkflowUnitSchema & InMemoryEntity; -/** - * @summary Set the head of an array of units - */ -export declare function setUnitsHead(units: UnitEntity[]): UnitEntity[]; -/** - * @summary Re-establishes the linked `next => flowchartId` logic in an array of units - */ -export declare function setNextLinks(units: UnitEntity[]): UnitEntity[]; -/** - * Add unit to unit graph (by index or appending). - */ -export declare function addUnit(units: UnitEntity[], unit: UnitEntity, index?: number): UnitEntity[]; -/** - * Remove unit based on flowchartId from unit graph. - * @param {Unit[]} units - * @param {string} flowchartId - * @returns {Array} - */ -export declare function removeUnit(units: UnitEntity[], flowchartId: string): UnitEntity[]; -/** - * Replace a unit in a unit graph by index. - * @param {Unit[]} units - * @param {Unit} unit - * @param {Number} index - */ -export declare function replaceUnit(units: UnitEntity[], unit: UnitEntity, index: number): UnitEntity[]; diff --git a/dist/js/utils/graph.js b/dist/js/utils/graph.js deleted file mode 100644 index d1aea1d0..00000000 --- a/dist/js/utils/graph.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.setUnitsHead = setUnitsHead; -exports.setNextLinks = setNextLinks; -exports.addUnit = addUnit; -exports.removeUnit = removeUnit; -exports.replaceUnit = replaceUnit; -/** - * @summary Set the head of an array of units - */ -function setUnitsHead(units) { - const [first, ...tail] = units; - if (units.length > 0) { - first.head = true; - tail.map((x) => (x.head = false)); - } - return units; -} -/** - * @summary Re-establishes the linked `next => flowchartId` logic in an array of units - */ -function setNextLinks(units) { - const flowchartIds = units.map((u) => u.flowchartId); - for (let i = 0; i < units.length - 1; i++) { - if (!units[i].next) { - // newly added units don't have next set yet => set it - units[i].next = units[i + 1].flowchartId; - if (i > 0) - units[i - 1].next = units[i].flowchartId; - } - else if (!flowchartIds.includes(units[i].next || "")) { - // newly removed units may create broken next links => fix it - units[i].next = units[i + 1].flowchartId; - } - } - return units; -} -/** - * Add unit to unit graph (by index or appending). - */ -function addUnit(units, unit, index = -1) { - if (index >= 0 && index < units.length) { - units.splice(index, 0, unit); - } - else { - units.push(unit); - } - return setNextLinks(setUnitsHead(units)); -} -/** - * Remove unit based on flowchartId from unit graph. - * @param {Unit[]} units - * @param {string} flowchartId - * @returns {Array} - */ -function removeUnit(units, flowchartId) { - const previousUnit = units.find((x) => x.next === flowchartId); - if (previousUnit) - previousUnit.unsetProp("next"); - // TODO: remove the setNextLinks and setUnitsHead and handle the logic via flowchart designer - return setNextLinks(setUnitsHead(units.filter((x) => x.flowchartId !== flowchartId))); -} -/** - * Replace a unit in a unit graph by index. - * @param {Unit[]} units - * @param {Unit} unit - * @param {Number} index - */ -function replaceUnit(units, unit, index) { - units[index] = unit; - return setNextLinks(setUnitsHead(units)); -} diff --git a/dist/js/utils/hash.d.ts b/dist/js/utils/hash.d.ts deleted file mode 100644 index 92f035a7..00000000 --- a/dist/js/utils/hash.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * @summary Calculates hash of a given text. - */ -export declare function calculateHashFromString(message: string, hashFunction?: string): string; -/** - * @summary Calculates hash of a given object. - * @param obj object to hash. It must be serializable. - * @param hashFunction hash function name. - */ -export declare function calculateHashFromObject(obj: object, hashFunction?: string): string; -export declare function removeTimestampableKeysFromConfig(config: object): {}; diff --git a/dist/js/utils/hash.js b/dist/js/utils/hash.js deleted file mode 100644 index 4e7ad2a4..00000000 --- a/dist/js/utils/hash.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.calculateHashFromString = calculateHashFromString; -exports.calculateHashFromObject = calculateHashFromObject; -exports.removeTimestampableKeysFromConfig = removeTimestampableKeysFromConfig; -const crypto_js_1 = __importDefault(require("crypto-js")); -const object_1 = require("./object"); -/** - * @summary Calculates hash of a given text. - */ -function calculateHashFromString(message, hashFunction = "MD5") { - switch (hashFunction) { - case "MD5": - default: - return crypto_js_1.default.MD5(message).toString(); - } -} -/** - * @summary Calculates hash of a given object. - * @param obj object to hash. It must be serializable. - * @param hashFunction hash function name. - */ -function calculateHashFromObject(obj, hashFunction = "MD5") { - const message = JSON.stringify((0, object_1.sortKeysDeepForObject)(obj)); - return calculateHashFromString(message, hashFunction); -} -function removeTimestampableKeysFromConfig(config) { - // @ts-ignore - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { createdAt, updatedAt, removedAt, ...restConfig } = config; - return restConfig; -} diff --git a/dist/js/utils/index.d.ts b/dist/js/utils/index.d.ts deleted file mode 100644 index 9ccec6ca..00000000 --- a/dist/js/utils/index.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { compareEntitiesInOrderedSetForSorting } from "../entity/set/ordered/utils"; -import { convertToCompactCSVArrayOfObjects, safeMakeArray } from "./array"; -import { cloneClass } from "./class"; -import { deepClone } from "./clone"; -import { refreshCodeMirror } from "./codemirror"; -import { createObjectPathFromFilePath, formatFileSize, getDirectories, getFilesInDirectory, getProgrammingLanguageFromFileExtension } from "./file"; -import { filterEntityList } from "./filter"; -import { fetchFilesFromGitHubAPI } from "./github"; -import { addUnit, removeUnit, replaceUnit, setNextLinks, setUnitsHead } from "./graph"; -import { calculateHashFromObject, calculateHashFromString, removeTimestampableKeysFromConfig } from "./hash"; -import { convertKeysToCamelCaseForObject, flattenObject, getOneMatchFromObject, mergeTerminalNodes, renameKeysForObject, safeMakeObject, sortKeysDeepForObject, stringifyObject } from "./object"; -import { buildNamedEntitySchema, getSchemaWithDependencies } from "./schemas"; -import { getSearchQuerySelector } from "./selector"; -import { convertArabicToRoman, findPreviousVersion, randomAlphanumeric, removeCommentsFromSourceCode, removeEmptyLinesFromString, removeNewLinesAndExtraSpaces, renderTextWithSubstitutes, toFixedLocale } from "./str"; -import { mapTree } from "./tree"; -import { containsEncodedComponents } from "./url"; -import { getUUID } from "./uuid"; -import { JsYamlAllSchemas, JsYamlTypes } from "./yaml"; -export { compareEntitiesInOrderedSetForSorting, safeMakeArray, convertToCompactCSVArrayOfObjects, cloneClass, deepClone, refreshCodeMirror, getOneMatchFromObject, safeMakeObject, convertKeysToCamelCaseForObject, flattenObject, renameKeysForObject, sortKeysDeepForObject, stringifyObject, getProgrammingLanguageFromFileExtension, formatFileSize, calculateHashFromObject, calculateHashFromString, removeTimestampableKeysFromConfig, removeNewLinesAndExtraSpaces, randomAlphanumeric, removeEmptyLinesFromString, removeCommentsFromSourceCode, toFixedLocale, getUUID, getSearchQuerySelector, containsEncodedComponents, convertArabicToRoman, setUnitsHead, setNextLinks, addUnit, removeUnit, replaceUnit, mapTree, getSchemaWithDependencies, mergeTerminalNodes, JsYamlTypes, JsYamlAllSchemas, renderTextWithSubstitutes, filterEntityList, getFilesInDirectory, getDirectories, createObjectPathFromFilePath, buildNamedEntitySchema, findPreviousVersion, fetchFilesFromGitHubAPI, }; diff --git a/dist/js/utils/index.js b/dist/js/utils/index.js deleted file mode 100644 index 2e62ca03..00000000 --- a/dist/js/utils/index.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fetchFilesFromGitHubAPI = exports.findPreviousVersion = exports.buildNamedEntitySchema = exports.createObjectPathFromFilePath = exports.getDirectories = exports.getFilesInDirectory = exports.filterEntityList = exports.renderTextWithSubstitutes = exports.JsYamlAllSchemas = exports.JsYamlTypes = exports.mergeTerminalNodes = exports.getSchemaWithDependencies = exports.mapTree = exports.replaceUnit = exports.removeUnit = exports.addUnit = exports.setNextLinks = exports.setUnitsHead = exports.convertArabicToRoman = exports.containsEncodedComponents = exports.getSearchQuerySelector = exports.getUUID = exports.toFixedLocale = exports.removeCommentsFromSourceCode = exports.removeEmptyLinesFromString = exports.randomAlphanumeric = exports.removeNewLinesAndExtraSpaces = exports.removeTimestampableKeysFromConfig = exports.calculateHashFromString = exports.calculateHashFromObject = exports.formatFileSize = exports.getProgrammingLanguageFromFileExtension = exports.stringifyObject = exports.sortKeysDeepForObject = exports.renameKeysForObject = exports.flattenObject = exports.convertKeysToCamelCaseForObject = exports.safeMakeObject = exports.getOneMatchFromObject = exports.refreshCodeMirror = exports.deepClone = exports.cloneClass = exports.convertToCompactCSVArrayOfObjects = exports.safeMakeArray = exports.compareEntitiesInOrderedSetForSorting = void 0; -const utils_1 = require("../entity/set/ordered/utils"); -Object.defineProperty(exports, "compareEntitiesInOrderedSetForSorting", { enumerable: true, get: function () { return utils_1.compareEntitiesInOrderedSetForSorting; } }); -const array_1 = require("./array"); -Object.defineProperty(exports, "convertToCompactCSVArrayOfObjects", { enumerable: true, get: function () { return array_1.convertToCompactCSVArrayOfObjects; } }); -Object.defineProperty(exports, "safeMakeArray", { enumerable: true, get: function () { return array_1.safeMakeArray; } }); -const class_1 = require("./class"); -Object.defineProperty(exports, "cloneClass", { enumerable: true, get: function () { return class_1.cloneClass; } }); -const clone_1 = require("./clone"); -Object.defineProperty(exports, "deepClone", { enumerable: true, get: function () { return clone_1.deepClone; } }); -const codemirror_1 = require("./codemirror"); -Object.defineProperty(exports, "refreshCodeMirror", { enumerable: true, get: function () { return codemirror_1.refreshCodeMirror; } }); -const file_1 = require("./file"); -Object.defineProperty(exports, "createObjectPathFromFilePath", { enumerable: true, get: function () { return file_1.createObjectPathFromFilePath; } }); -Object.defineProperty(exports, "formatFileSize", { enumerable: true, get: function () { return file_1.formatFileSize; } }); -Object.defineProperty(exports, "getDirectories", { enumerable: true, get: function () { return file_1.getDirectories; } }); -Object.defineProperty(exports, "getFilesInDirectory", { enumerable: true, get: function () { return file_1.getFilesInDirectory; } }); -Object.defineProperty(exports, "getProgrammingLanguageFromFileExtension", { enumerable: true, get: function () { return file_1.getProgrammingLanguageFromFileExtension; } }); -const filter_1 = require("./filter"); -Object.defineProperty(exports, "filterEntityList", { enumerable: true, get: function () { return filter_1.filterEntityList; } }); -const github_1 = require("./github"); -Object.defineProperty(exports, "fetchFilesFromGitHubAPI", { enumerable: true, get: function () { return github_1.fetchFilesFromGitHubAPI; } }); -const graph_1 = require("./graph"); -Object.defineProperty(exports, "addUnit", { enumerable: true, get: function () { return graph_1.addUnit; } }); -Object.defineProperty(exports, "removeUnit", { enumerable: true, get: function () { return graph_1.removeUnit; } }); -Object.defineProperty(exports, "replaceUnit", { enumerable: true, get: function () { return graph_1.replaceUnit; } }); -Object.defineProperty(exports, "setNextLinks", { enumerable: true, get: function () { return graph_1.setNextLinks; } }); -Object.defineProperty(exports, "setUnitsHead", { enumerable: true, get: function () { return graph_1.setUnitsHead; } }); -const hash_1 = require("./hash"); -Object.defineProperty(exports, "calculateHashFromObject", { enumerable: true, get: function () { return hash_1.calculateHashFromObject; } }); -Object.defineProperty(exports, "calculateHashFromString", { enumerable: true, get: function () { return hash_1.calculateHashFromString; } }); -Object.defineProperty(exports, "removeTimestampableKeysFromConfig", { enumerable: true, get: function () { return hash_1.removeTimestampableKeysFromConfig; } }); -const object_1 = require("./object"); -Object.defineProperty(exports, "convertKeysToCamelCaseForObject", { enumerable: true, get: function () { return object_1.convertKeysToCamelCaseForObject; } }); -Object.defineProperty(exports, "flattenObject", { enumerable: true, get: function () { return object_1.flattenObject; } }); -Object.defineProperty(exports, "getOneMatchFromObject", { enumerable: true, get: function () { return object_1.getOneMatchFromObject; } }); -Object.defineProperty(exports, "mergeTerminalNodes", { enumerable: true, get: function () { return object_1.mergeTerminalNodes; } }); -Object.defineProperty(exports, "renameKeysForObject", { enumerable: true, get: function () { return object_1.renameKeysForObject; } }); -Object.defineProperty(exports, "safeMakeObject", { enumerable: true, get: function () { return object_1.safeMakeObject; } }); -Object.defineProperty(exports, "sortKeysDeepForObject", { enumerable: true, get: function () { return object_1.sortKeysDeepForObject; } }); -Object.defineProperty(exports, "stringifyObject", { enumerable: true, get: function () { return object_1.stringifyObject; } }); -const schemas_1 = require("./schemas"); -Object.defineProperty(exports, "buildNamedEntitySchema", { enumerable: true, get: function () { return schemas_1.buildNamedEntitySchema; } }); -Object.defineProperty(exports, "getSchemaWithDependencies", { enumerable: true, get: function () { return schemas_1.getSchemaWithDependencies; } }); -const selector_1 = require("./selector"); -Object.defineProperty(exports, "getSearchQuerySelector", { enumerable: true, get: function () { return selector_1.getSearchQuerySelector; } }); -const str_1 = require("./str"); -Object.defineProperty(exports, "convertArabicToRoman", { enumerable: true, get: function () { return str_1.convertArabicToRoman; } }); -Object.defineProperty(exports, "findPreviousVersion", { enumerable: true, get: function () { return str_1.findPreviousVersion; } }); -Object.defineProperty(exports, "randomAlphanumeric", { enumerable: true, get: function () { return str_1.randomAlphanumeric; } }); -Object.defineProperty(exports, "removeCommentsFromSourceCode", { enumerable: true, get: function () { return str_1.removeCommentsFromSourceCode; } }); -Object.defineProperty(exports, "removeEmptyLinesFromString", { enumerable: true, get: function () { return str_1.removeEmptyLinesFromString; } }); -Object.defineProperty(exports, "removeNewLinesAndExtraSpaces", { enumerable: true, get: function () { return str_1.removeNewLinesAndExtraSpaces; } }); -Object.defineProperty(exports, "renderTextWithSubstitutes", { enumerable: true, get: function () { return str_1.renderTextWithSubstitutes; } }); -Object.defineProperty(exports, "toFixedLocale", { enumerable: true, get: function () { return str_1.toFixedLocale; } }); -const tree_1 = require("./tree"); -Object.defineProperty(exports, "mapTree", { enumerable: true, get: function () { return tree_1.mapTree; } }); -const url_1 = require("./url"); -Object.defineProperty(exports, "containsEncodedComponents", { enumerable: true, get: function () { return url_1.containsEncodedComponents; } }); -const uuid_1 = require("./uuid"); -Object.defineProperty(exports, "getUUID", { enumerable: true, get: function () { return uuid_1.getUUID; } }); -const yaml_1 = require("./yaml"); -Object.defineProperty(exports, "JsYamlAllSchemas", { enumerable: true, get: function () { return yaml_1.JsYamlAllSchemas; } }); -Object.defineProperty(exports, "JsYamlTypes", { enumerable: true, get: function () { return yaml_1.JsYamlTypes; } }); diff --git a/dist/js/utils/object.d.ts b/dist/js/utils/object.d.ts deleted file mode 100644 index ec2bde55..00000000 --- a/dist/js/utils/object.d.ts +++ /dev/null @@ -1,79 +0,0 @@ -export type NameResultSchema = { - name: string; -}; -/** - * @summary Safely convert input to { name: str } if it is not already - * @param name {String|Object} the input to convert - * @returns result {Object|null} converted object if any - */ -export declare function safeMakeObject(name: string | NameResultSchema): NameResultSchema; -/** - * @summary Pluck a single entry out of an iterable according to an attribute and match condition - */ -export declare function getOneMatchFromObject(obj: object, attribute: string, value: unknown): unknown; -/** - * @summary Converts all keys of object to camelCase. - */ -export declare function convertKeysToCamelCaseForObject(obj: object): import("lodash").Dictionary; -export declare function renameKeysForObject(o: T, keysOriginal: string[], keysRenamed: string[]): T; -export type NameValueObject = { - name: string; - value: unknown; - units?: string; -}; -export type NameValueObjectExtended = NameValueObject & { - [key: string]: NameValueObject | string | number | undefined; -}; -/** - * @summary Converts object into string. Recursive. Required properties for object: "name", "value". - * "units" property is ignored. Only one extra property is allowed. Function is called recursively on extraProperty. - * E.g. {name: "propName", value: 1} -> 'propName=1' - * {name: "propName", value: 1, extraProp: {name: "extraPropName", value: "2"}} -> "propName=1:extraPropName=2" - */ -export declare function stringifyObject(obj: NameValueObject, levelSeparator?: string, keyValueSeparator?: string, prefix?: string): string; -/** - * @summary Flattens complex object into object with single key-value pair. Required properties for object: "name", "value". - * "units" property is ignored. Only one extra property is allowed. E.g. - * {name: 'propName', value: 1} -> {propName: 1} - * {name: "propName", value: 1, extraProp: {name: "extraPropName", value: "2"}} -> {"propName:extraPropName=2": 1} - */ -export declare function flattenObject(obj: NameValueObjectExtended, levelSeparator?: string, keyValueSeparator?: string, suffix?: string | undefined): { - [x: string]: unknown; -}; -/** - * Sort object keys alphabetically - */ -export declare function sortKeysDeepForObject(obj: T): T; -interface Tree { - [key: string]: Tree | T[]; -} -/** - * Merge terminal node values of an object tree. - * @param tree - Nested object - * @param unique - Whether merged list should consist of unique items - * @return Merged list of values of terminal nodes. - * @example - * const tree = { - * level1: { - * level2a: { - * level3a: { - * key1: ['a', 'b', 'c'], - * }, - * level3b: { - * key2: ['d', 'e', 'f'], - * }, - * }, - * level2b: { - * level3c: { - * key3: ['g', 'h', 'i'], - * }, - * level3d: { - * key4: ['j', 'k', 'l'], - * }, - * }, - * }, - * }; - * mergeTerminalNodes(tree); // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'] - */ -export declare function mergeTerminalNodes(tree: Tree, unique?: boolean): T[]; -export {}; diff --git a/dist/js/utils/object.js b/dist/js/utils/object.js deleted file mode 100644 index 858b2765..00000000 --- a/dist/js/utils/object.js +++ /dev/null @@ -1,199 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.safeMakeObject = safeMakeObject; -exports.getOneMatchFromObject = getOneMatchFromObject; -exports.convertKeysToCamelCaseForObject = convertKeysToCamelCaseForObject; -exports.renameKeysForObject = renameKeysForObject; -exports.stringifyObject = stringifyObject; -exports.flattenObject = flattenObject; -exports.sortKeysDeepForObject = sortKeysDeepForObject; -exports.mergeTerminalNodes = mergeTerminalNodes; -const camelCase_1 = __importDefault(require("lodash/camelCase")); -const filter_1 = __importDefault(require("lodash/filter")); -const isArray_1 = __importDefault(require("lodash/isArray")); -const isEmpty_1 = __importDefault(require("lodash/isEmpty")); -const isObject_1 = __importDefault(require("lodash/isObject")); -const isPlainObject_1 = __importDefault(require("lodash/isPlainObject")); -const isString_1 = __importDefault(require("lodash/isString")); -const mapKeys_1 = __importDefault(require("lodash/mapKeys")); -const omit_1 = __importDefault(require("lodash/omit")); -const array_1 = require("./array"); -const clone_1 = require("./clone"); -/** - * @summary Safely convert input to { name: str } if it is not already - * @param name {String|Object} the input to convert - * @returns result {Object|null} converted object if any - */ -function safeMakeObject(name) { - if (!name) { - throw new Error("safeMakeObject: name is required"); - } - const result = (0, isString_1.default)(name) ? { name } : name; - if (!(0, isObject_1.default)(result) || (0, isArray_1.default)(result) || !result.name) { - throw new Error(`safeMakeObject: failed creating named object, found ${result}`); - } - return result; -} -/** - * @summary Pluck a single entry out of an iterable according to an attribute and match condition - */ -function getOneMatchFromObject(obj, attribute, value) { - const filtered = (0, filter_1.default)(obj, [attribute, value]); - if (filtered.length !== 1) { - console.log(`found ${filtered.length} ${attribute} matching ${value}, expected 1.`); - } - if (!filtered.length) { - return null; - } - return filtered[0]; -} -/** - * @summary Converts all keys of object to camelCase. - */ -function convertKeysToCamelCaseForObject(obj) { - const newObj = (0, clone_1.deepClone)(obj); - return (0, mapKeys_1.default)(newObj, (_v, k) => (0, camelCase_1.default)(k)); -} -function renameKeysForObject( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -o, keysOriginal = [], keysRenamed = []) { - if (!(0, isObject_1.default)(o)) { - return o; - } - if ((0, isArray_1.default)(o)) { - return o.map((x) => renameKeysForObject(x, keysOriginal, keysRenamed)); - } - const result = {}; - Object.entries(o).map(([origKey, origValue]) => { - // Get the destination key - const idx = keysOriginal.indexOf(origKey); - const destKey = idx === -1 ? origKey : keysRenamed[idx]; - result[destKey] = - typeof origValue === "object" - ? renameKeysForObject(origValue, keysOriginal, keysRenamed) - : origValue; - return null; - }); - return result; -} -/** - * @summary Converts object into string. Recursive. Required properties for object: "name", "value". - * "units" property is ignored. Only one extra property is allowed. Function is called recursively on extraProperty. - * E.g. {name: "propName", value: 1} -> 'propName=1' - * {name: "propName", value: 1, extraProp: {name: "extraPropName", value: "2"}} -> "propName=1:extraPropName=2" - */ -function stringifyObject(obj, levelSeparator = ":", keyValueSeparator = "=", prefix = "") { - const requiredKeys = ["name", "value"]; - const allowedKeys = requiredKeys.concat(["units"]); - const extraKeys = Object.keys((0, omit_1.default)(obj, allowedKeys)); - // If there is more than one extra key, raise an exception - if (extraKeys.length > 1) { - throw new Error("stringifyObject: more than one extra property"); - } - if (extraKeys.length === 0) { - return `${obj.name}${keyValueSeparator}${obj.value}`; - } - const extraPropertyKey = extraKeys[0]; - // @ts-ignore - const extraPropertyValue = obj[extraKeys[0]]; - // eslint-disable-next-line no-param-reassign - prefix = (0, isEmpty_1.default)(prefix) - ? `${obj.name}${keyValueSeparator}${obj.value}` - : `${prefix}${levelSeparator}${obj.name}${keyValueSeparator}${obj.value}`; - if (!(0, isObject_1.default)(extraPropertyValue)) { - return `${prefix}:${extraPropertyKey}${keyValueSeparator}${extraPropertyValue}`; - } - // @ts-ignore - return stringifyObject(extraPropertyValue, levelSeparator, keyValueSeparator, prefix); -} -/** - * @summary Flattens complex object into object with single key-value pair. Required properties for object: "name", "value". - * "units" property is ignored. Only one extra property is allowed. E.g. - * {name: 'propName', value: 1} -> {propName: 1} - * {name: "propName", value: 1, extraProp: {name: "extraPropName", value: "2"}} -> {"propName:extraPropName=2": 1} - */ -// eslint-disable-next-line default-param-last -function flattenObject(obj, levelSeparator = ":", keyValueSeparator = "=", suffix = undefined) { - const requiredKeys = ["name", "value"]; - const allowedKeys = requiredKeys.concat(["units"]); - const extraKeys = Object.keys((0, omit_1.default)(obj, allowedKeys)); - // If there is more than one extra key, raise an exception - if (extraKeys.length > 1) { - throw new Error("flattenObject: more than one extra property"); - } - const tailSuffix = (0, isEmpty_1.default)(suffix) ? "" : `${levelSeparator}${suffix}`; - if (extraKeys.length === 0) { - return { [`${obj.name}${tailSuffix}`]: obj.value }; - } - const extraPropertyKey = extraKeys[0]; - const extraPropertyValue = obj[extraKeys[0]]; - if (!(0, isObject_1.default)(extraPropertyValue)) { - return { - [`${obj.name}${levelSeparator}${extraPropertyKey}=${extraPropertyValue}${tailSuffix}`]: obj.value, - }; - } - const flatSubObj = stringifyObject(extraPropertyValue, levelSeparator, keyValueSeparator); - const key = `${obj.name}${levelSeparator}${flatSubObj}${tailSuffix}`; - return { [key]: obj.value }; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function sortKeysDeepForObject(obj) { - if (Array.isArray(obj)) { - return obj.map(sortKeysDeepForObject); - } - if ((0, isObject_1.default)(obj)) { - const sortedObject = {}; - Object.keys(obj) - .sort() - // @ts-ignore - .map((key) => (sortedObject[key] = sortKeysDeepForObject(obj[key]))); - return sortedObject; - } - return obj; -} -function isTreeObject(value) { - return (0, isPlainObject_1.default)(value); -} -/** - * Merge terminal node values of an object tree. - * @param tree - Nested object - * @param unique - Whether merged list should consist of unique items - * @return Merged list of values of terminal nodes. - * @example - * const tree = { - * level1: { - * level2a: { - * level3a: { - * key1: ['a', 'b', 'c'], - * }, - * level3b: { - * key2: ['d', 'e', 'f'], - * }, - * }, - * level2b: { - * level3c: { - * key3: ['g', 'h', 'i'], - * }, - * level3d: { - * key4: ['j', 'k', 'l'], - * }, - * }, - * }, - * }; - * mergeTerminalNodes(tree); // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'] - */ -function mergeTerminalNodes(tree, unique = false) { - if (!isTreeObject(tree)) - return (0, array_1.safeMakeArray)(tree); - const terminalValues = Object.values(tree).reduce((accumulator, value) => { - if (isTreeObject(value)) { - return accumulator.concat(mergeTerminalNodes(value)); - } - return accumulator.concat(value); - }, []); - // @ts-ignore - return unique ? [...new Set(terminalValues)] : terminalValues; -} diff --git a/dist/js/utils/schemas.d.ts b/dist/js/utils/schemas.d.ts deleted file mode 100644 index a2895763..00000000 --- a/dist/js/utils/schemas.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { JSONSchema7 } from "json-schema"; -export * from "@mat3ra/esse/dist/js/esse/schemaUtils"; -export declare const schemas: { - [key: string]: string; -}; -interface SubstitutionMap { - [key: string]: string; -} -interface Parameter { - key: string; - values: string[] | boolean[]; - namesMap?: SubstitutionMap; -} -interface Node { - data: { - key: string; - value: string; - name: string; - }; - staticOptions?: Parameter[]; - children?: Node[]; - [otherKey: string]: unknown; -} -export declare function typeofSchema(schema: JSONSchema7): import("json-schema").JSONSchema7TypeName | import("json-schema").JSONSchema7TypeName[] | undefined; -/** - * @summary Recursively generate `dependencies` for RJSF schema based on tree. - * @param {Object[]} nodes - Array of nodes (e.g. `[tree]` or `node.children`) - * @returns {{}|{dependencies: {}}} - */ -export declare function buildDependencies(nodes?: Node[]): JSONSchema7; -interface Props { - schema?: JSONSchema7; - nodes: Node[]; - modifyProperties?: boolean; -} -/** - * Combine schema and dependencies block for usage with react-jsonschema-form (RJSF) - */ -export declare function getSchemaWithDependencies({ schema, nodes, modifyProperties, }: Props): JSONSchema7; -interface NamedEntity { - name: string; -} -/** - * Retrieves an RJSF schema with an id matching the provided name - */ -export declare const schemaByNamedEntityName: (name: string) => JSONSchema7 | undefined; -export declare const buildNamedEntitySchema: (entities: NamedEntity[], defaultEntity: NamedEntity, entityType: string, enforceUnique?: boolean) => JSONSchema7; diff --git a/dist/js/utils/schemas.js b/dist/js/utils/schemas.js deleted file mode 100644 index 9fcf83c0..00000000 --- a/dist/js/utils/schemas.js +++ /dev/null @@ -1,228 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.buildNamedEntitySchema = exports.schemaByNamedEntityName = exports.schemas = void 0; -exports.typeofSchema = typeofSchema; -exports.buildDependencies = buildDependencies; -exports.getSchemaWithDependencies = getSchemaWithDependencies; -const JSONSchemasInterface_1 = __importDefault(require("@mat3ra/esse/dist/js/esse/JSONSchemasInterface")); -const forEach_1 = __importDefault(require("lodash/forEach")); -const has_1 = __importDefault(require("lodash/has")); -const isEmpty_1 = __importDefault(require("lodash/isEmpty")); -__exportStar(require("@mat3ra/esse/dist/js/esse/schemaUtils"), exports); -exports.schemas = {}; -function typeofSchema(schema) { - if (schema === null || schema === void 0 ? void 0 : schema.type) { - return schema.type; - } - if ((0, has_1.default)(schema, "properties")) { - return "object"; - } - if ((0, has_1.default)(schema, "items")) { - return "array"; - } -} -function extractEnumOptions(nodes) { - if (!nodes || !nodes.length) - return {}; - return { - enum: nodes.map((node) => node.data.value), - enumNames: nodes.map((node) => node.data.name), - }; -} -function substituteName(value, mapping) { - if (typeof value !== "string") { - return JSON.stringify(value); - } - return mapping ? mapping[value] : value; -} -function createStaticFields(node) { - if (!node.staticOptions) - return {}; - const fields = {}; - node.staticOptions - .filter((o) => o.key && o.values) - .forEach((o) => { - fields[o.key] = { - enum: o.values, - enumNames: o.values.map((v) => substituteName(v, o.namesMap)), - }; - }); - return fields; -} -/** - * @summary Recursively generate `dependencies` for RJSF schema based on tree. - * @param {Object[]} nodes - Array of nodes (e.g. `[tree]` or `node.children`) - * @returns {{}|{dependencies: {}}} - */ -function buildDependencies(nodes) { - const isEveryTerminal = nodes && nodes.every((node) => { var _a; return !((_a = node.children) === null || _a === void 0 ? void 0 : _a.length); }); - const isWithStaticOptions = nodes && nodes.some((node) => node === null || node === void 0 ? void 0 : node.staticOptions); - if (!nodes || !nodes.length || !nodes[0].data) - return {}; - const parentKey = nodes[0].data.key; - const cases = nodes.map((node) => { - var _a; - const childKey = ((_a = node.children) === null || _a === void 0 ? void 0 : _a.length) && node.children[0].data.key; - return { - properties: { - [parentKey]: extractEnumOptions([node]), - ...(childKey ? { [childKey]: extractEnumOptions(node.children) } : {}), - ...createStaticFields(node), - }, - ...buildDependencies(node.children), - }; - }); - return cases.length && (!isEveryTerminal || isWithStaticOptions) - ? { - dependencies: { - [parentKey]: { - oneOf: cases, - }, - }, - } - : {}; -} -/** - * Combine schema and dependencies block for usage with react-jsonschema-form (RJSF) - */ -function getSchemaWithDependencies({ schema = {}, nodes, modifyProperties = false, }) { - if (!(0, isEmpty_1.default)(schema) && typeofSchema(schema) !== "object") { - console.error("getSchemaWithDependencies() only accepts schemas of type 'object'"); - return {}; - } - // RJSF does not automatically render dropdown widget if `enum` is not present - if (modifyProperties && nodes.length) { - const mod = { - [nodes[0].data.key]: { - ...extractEnumOptions(nodes), - }, - }; - (0, forEach_1.default)(mod, (extraFields, key) => { - if (schema.properties && (0, has_1.default)(schema, `properties.${key}`)) { - schema.properties[key] = { - ...schema.properties[key], - ...extraFields, - }; - } - }); - } - return { - ...schema, - ...buildDependencies(nodes), - }; -} -const DEFAULT_GENERATIVE_KEYS = ["name"]; -const baseSchema = (definitionName, enforceUnique = true) => { - return { - type: "array", - items: { - $ref: `#/definitions/${definitionName}`, - }, - uniqueItems: enforceUnique, - }; -}; -const defaultNamedEntitySchema = (name) => { - return { - properties: { - name: { - type: "string", - enum: [name], - }, - }, - }; -}; -/** - * Retrieves an RJSF schema with an id matching the provided name - */ -const schemaByNamedEntityName = (name) => { - const translatedName = name.replace(/_/g, "-"); - return JSONSchemasInterface_1.default.matchSchema({ - $id: { - $regex: `${translatedName}$`, - }, - }); -}; -exports.schemaByNamedEntityName = schemaByNamedEntityName; -/* - * Filters an RJSF schema for all the properties used to generate a new schema - */ -const filterForGenerativeProperties = (schema) => { - if (!schema.properties || typeof schema.properties !== "object") - return {}; - const generativeFilter = ([propertyKey, property]) => { - return ((typeof property === "object" && // JSONSchema7Definition type allows for boolean - (property === null || property === void 0 ? void 0 : property.$comment) && - property.$comment.includes("isGenerative:true")) || - DEFAULT_GENERATIVE_KEYS.includes(propertyKey)); - }; - // @ts-ignore : JSONSchema6 and JSONSchema7 are incompatible - const generativeProperties = Object.entries(schema.properties).filter(generativeFilter); - const properties = Object.fromEntries(generativeProperties); - return { properties, required: Object.keys(properties) }; // all included fields are required based on isGenerative flag -}; -/* - * Filters an RJSF schema for all the properties used to generate a new schema - */ -const buildNamedEntitiesDependencies = (entities) => { - return { - dependencies: { - name: { - oneOf: entities.map((entity) => { - const schema = (0, exports.schemaByNamedEntityName)(entity.name) || - defaultNamedEntitySchema(entity.name); - return { - ...filterForGenerativeProperties(schema), - }; - }), - }, - }, - }; -}; -/** - * Generates an RJSF definition with a list of subschemas as enumerated options - */ -const buildNamedEntitiesDefinitions = (entities, defaultEntity, entityType) => { - if (!Array.isArray(entities) || entities.length < 1) - return {}; - return { - definitions: { - [entityType]: { - properties: { - name: { - type: "string", - enum: entities.map((entity) => entity.name), - default: defaultEntity.name || entities[0].name, - }, - }, - ...buildNamedEntitiesDependencies(entities), - }, - }, - }; -}; -/* - * Generates an RJSF scheme with a list of subschemas as enumerated options - */ -const buildNamedEntitySchema = (entities, defaultEntity, entityType, enforceUnique = true) => { - return { - ...buildNamedEntitiesDefinitions(entities, defaultEntity, entityType), - ...baseSchema(entityType, enforceUnique), - }; -}; -exports.buildNamedEntitySchema = buildNamedEntitySchema; diff --git a/dist/js/utils/selector.d.ts b/dist/js/utils/selector.d.ts deleted file mode 100644 index 907fa5d5..00000000 --- a/dist/js/utils/selector.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Forms a search query selector for MongoDB - * @param {Object} searchQuery - db query - * @param {Array[String]} fields - keys in the target document to search for - * @return {Object} - */ -export function getSearchQuerySelector(searchQuery: Object, fields?: any): Object; diff --git a/dist/js/utils/selector.js b/dist/js/utils/selector.js deleted file mode 100644 index 6a8f7f04..00000000 --- a/dist/js/utils/selector.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSearchQuerySelector = getSearchQuerySelector; -/** - * Forms a search query selector for MongoDB - * @param {Object} searchQuery - db query - * @param {Array[String]} fields - keys in the target document to search for - * @return {Object} - */ -function getSearchQuerySelector(searchQuery, fields = []) { - const selector = {}; - if (searchQuery) { - selector.$or = fields.map((field) => { - return { - [field]: { - $regex: searchQuery, - $options: "i", - }, - }; - }); - } - return selector; -} diff --git a/dist/js/utils/str.d.ts b/dist/js/utils/str.d.ts deleted file mode 100644 index 37e9fe55..00000000 --- a/dist/js/utils/str.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -export function removeNewLinesAndExtraSpaces(str: any): any; -/** - * @summary Generates random alphanumeric string with a specified length. - * Returns lowercase string which starts with letter. - * @param length {Number} - */ -export function randomAlphanumeric(length: number): string; -export function toFixedLocale(number: any, precision: any): any; -/** - * @summary Removes lines started with # character. Shebang (#!) is excluded. - * @param text {String} text to remove comments from. - * @param language {String} programming language of the text. - * @return {String} - */ -export function removeCommentsFromSourceCode(text: string, language?: string): string; -/** - * @summary Removes empty lines from a given string. - * @param string {String} string to remove empty lines from. - * @return {String} - */ -export function removeEmptyLinesFromString(string: string): string; -/** - * converts simple number to roman. - * @param {Number} num - * @returns {String} - string - */ -export function convertArabicToRoman(num: number): string; -/** - * Render name template based on config. - * Use substitution map to replace a config value with a more readable variant. - * NOTE: We currently iterate through the whole object. A more efficient albeit more verbose approach would be - * to give the property path in the subsitution map, e.g., `{ "user.name": {"user001": "John Doe"} }`. - * @param {string|undefined} template - Template for the name property - * @param {Object} data - Entity config - * @param {Object} substitutionMap - Maps object value to human-readable string - * @return {string} - * @example - * generateName( - * "Hello {{user}}!", - * {user: "user001"}, - * {user001: "John Doe"} - * ); // "Hello John Doe!" - */ -export function renderTextWithSubstitutes(template: string | undefined, data: Object, substitutionMap?: Object): string; -/** - * Find the next smallest version from a list of semantic version strings. - * @param {string[]} versions - Array of semantic version strings. - * @param {string} inputVersion - Version to compare to. - * @returns {string | undefined} - */ -export function findPreviousVersion(versions: string[], inputVersion: string): string | undefined; diff --git a/dist/js/utils/str.js b/dist/js/utils/str.js deleted file mode 100644 index 075a75d8..00000000 --- a/dist/js/utils/str.js +++ /dev/null @@ -1,154 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.removeNewLinesAndExtraSpaces = removeNewLinesAndExtraSpaces; -exports.randomAlphanumeric = randomAlphanumeric; -exports.toFixedLocale = toFixedLocale; -exports.removeCommentsFromSourceCode = removeCommentsFromSourceCode; -exports.removeEmptyLinesFromString = removeEmptyLinesFromString; -exports.convertArabicToRoman = convertArabicToRoman; -exports.renderTextWithSubstitutes = renderTextWithSubstitutes; -exports.findPreviousVersion = findPreviousVersion; -const lodash_1 = __importDefault(require("lodash")); -const nunjucks_1 = __importDefault(require("nunjucks")); -const coerce_1 = __importDefault(require("semver/functions/coerce")); -const lt_1 = __importDefault(require("semver/functions/lt")); -const rcompare_1 = __importDefault(require("semver/functions/rcompare")); -const underscore_1 = __importDefault(require("underscore")); -function removeNewLinesAndExtraSpaces(str) { - return str.replace(/[\n\r]/g, "").replace(/ +/g, " "); -} -/** - * @summary Generates random alphanumeric string with a specified length. - * Returns lowercase string which starts with letter. - * @param length {Number} - */ -function randomAlphanumeric(length) { - // numerical value – create random alphanumeric string - // Start from char at position 2, because Math.random().toString(36) starts with "0." - const alphabet = "abcdefghijklmnopqrstuvwxyz"; - const randomLetter = alphabet[Math.floor(Math.random() * alphabet.length)]; - // Random letter is required in generated string because of when - // the result is used as username and contains only numbers, the - // slug will be inappropriate (e.g., "user-1232", "user-12" both have "user" as slug). - return (randomLetter + - Math.random() - .toString(36) - .substring(2, 2 + length - 1)); -} -function toFixedLocale(number, precision) { - if (underscore_1.default.isNumber(number)) { - return number.toFixed(precision).replace(/\B(?=(\d{3})+(?!\d))/g, ","); - } - return number; -} -/** - * @summary Removes lines started with # character. Shebang (#!) is excluded. - * @param text {String} text to remove comments from. - * @param language {String} programming language of the text. - * @return {String} - */ -function removeCommentsFromSourceCode(text, language = "shell") { - const regexList = { - shell: /^(\s+)?#(?!!).*$/gm, - }; - return text.replace(regexList[language], ""); -} -/** - * @summary Removes empty lines from a given string. - * @param string {String} string to remove empty lines from. - * @return {String} - */ -function removeEmptyLinesFromString(string) { - // remove "\n" on empty lines AND the very last "\n" - return string.replace(/^\s*[\r\n]/gm, "").trim(); -} -/** - * converts simple number to roman. - * @param {Number} num - * @returns {String} - string - */ -function convertArabicToRoman(num) { - const roman = { - M: 1000, - CM: 900, - D: 500, - CD: 400, - C: 100, - XC: 90, - L: 50, - XL: 40, - X: 10, - IX: 9, - V: 5, - IV: 4, - I: 1, - }; - let str = ""; - // eslint-disable-next-line no-restricted-syntax - for (const i of Object.keys(roman)) { - const q = Math.floor(num / roman[i]); - // eslint-disable-next-line no-param-reassign - num -= q * roman[i]; - str += i.repeat(q); - } - return str; -} -/** - * Render name template based on config. - * Use substitution map to replace a config value with a more readable variant. - * NOTE: We currently iterate through the whole object. A more efficient albeit more verbose approach would be - * to give the property path in the subsitution map, e.g., `{ "user.name": {"user001": "John Doe"} }`. - * @param {string|undefined} template - Template for the name property - * @param {Object} data - Entity config - * @param {Object} substitutionMap - Maps object value to human-readable string - * @return {string} - * @example - * generateName( - * "Hello {{user}}!", - * {user: "user001"}, - * {user001: "John Doe"} - * ); // "Hello John Doe!" - */ -function renderTextWithSubstitutes(template, data, substitutionMap = {}) { - if (!template) - return ""; - // Create a copy of data to avoid modifying the original - const renderData = lodash_1.default.cloneDeep(data); - // Helper function for recursive substitution - function substituteNested(obj) { - if (!lodash_1.default.isPlainObject(obj)) { - return; - } - // eslint-disable-next-line no-restricted-syntax - for (const [key, value] of Object.entries(obj)) { - if (lodash_1.default.isPlainObject(value)) { - substituteNested(value); - } - else if (Array.isArray(value)) { - value.forEach((val) => substituteNested(val)); - } - else if (substitutionMap[value]) { - obj[key] = substitutionMap[value]; - } - } - } - substituteNested(renderData); - return nunjucks_1.default.renderString(template, renderData); -} -/** - * Find the next smallest version from a list of semantic version strings. - * @param {string[]} versions - Array of semantic version strings. - * @param {string} inputVersion - Version to compare to. - * @returns {string | undefined} - */ -function findPreviousVersion(versions, inputVersion) { - const version = (0, coerce_1.default)(inputVersion); - const versions_ = versions - .map((v) => ({ raw: v, coerced: (0, coerce_1.default)(v) })) - .sort((a, b) => (0, rcompare_1.default)(a.coerced, b.coerced)); - const prev = versions_.find((o) => (0, lt_1.default)(o.coerced, version)); - return prev === null || prev === void 0 ? void 0 : prev.raw; -} diff --git a/dist/js/utils/tree.d.ts b/dist/js/utils/tree.d.ts deleted file mode 100644 index 7ffa6289..00000000 --- a/dist/js/utils/tree.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @summary Return nodes with `fn` function applied to each node. - * Note that the function `fn` must take a node as an argument and must return a node object. - * @param {Object[]} nodes - Array of nodes - * @param {Function} fn - function to be applied to each node - * @returns {Object[]} - Result of map - */ -export function mapTree(nodes: Object[], fn: Function): Object[]; diff --git a/dist/js/utils/tree.js b/dist/js/utils/tree.js deleted file mode 100644 index 0319e910..00000000 --- a/dist/js/utils/tree.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.mapTree = mapTree; -/** - * @summary Return nodes with `fn` function applied to each node. - * Note that the function `fn` must take a node as an argument and must return a node object. - * @param {Object[]} nodes - Array of nodes - * @param {Function} fn - function to be applied to each node - * @returns {Object[]} - Result of map - */ -function mapTree(nodes, fn) { - return nodes.map((node) => { - var _a; - const mappedNode = fn(node); - if ((_a = node === null || node === void 0 ? void 0 : node.children) === null || _a === void 0 ? void 0 : _a.length) { - mappedNode.children = mapTree(node.children, fn); - } - return mappedNode; - }); -} diff --git a/dist/js/utils/types.d.ts b/dist/js/utils/types.d.ts deleted file mode 100644 index 63c43207..00000000 --- a/dist/js/utils/types.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export type Constructor = new (...args: any[]) => T; -export type AbstractConstructor = abstract new (...args: any[]) => T; diff --git a/dist/js/utils/types.js b/dist/js/utils/types.js deleted file mode 100644 index c8ad2e54..00000000 --- a/dist/js/utils/types.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/js/utils/url.d.ts b/dist/js/utils/url.d.ts deleted file mode 100644 index 93568fc2..00000000 --- a/dist/js/utils/url.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** Check whether URL component is encoded already. - * @see [MDN]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent} - * @param {String} x - * @returns {boolean} - */ -export function containsEncodedComponents(x: string): boolean; diff --git a/dist/js/utils/url.js b/dist/js/utils/url.js deleted file mode 100644 index a985fb4e..00000000 --- a/dist/js/utils/url.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.containsEncodedComponents = containsEncodedComponents; -/** Check whether URL component is encoded already. - * @see [MDN]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent} - * @param {String} x - * @returns {boolean} - */ -function containsEncodedComponents(x) { - // ie ?,=,&,/ etc - return decodeURI(x) !== decodeURIComponent(x); -} diff --git a/dist/js/utils/uuid.d.ts b/dist/js/utils/uuid.d.ts deleted file mode 100644 index 60270609..00000000 --- a/dist/js/utils/uuid.d.ts +++ /dev/null @@ -1 +0,0 @@ -export function getUUID(): any; diff --git a/dist/js/utils/uuid.js b/dist/js/utils/uuid.js deleted file mode 100644 index 3cc6d3a8..00000000 --- a/dist/js/utils/uuid.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getUUID = getUUID; -const uuid_1 = require("uuid"); -function getUUID() { - return (0, uuid_1.v4)(); -} diff --git a/dist/js/utils/yaml.d.ts b/dist/js/utils/yaml.d.ts deleted file mode 100644 index ce9bf554..00000000 --- a/dist/js/utils/yaml.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -import * as yaml from "js-yaml"; -/** - * !parameter YAML tag, which creates an object containing - * `key`, the name of or path to the parameter and - * `values`, an array of values. - * Supports YAML objects with the following keys: - * - `key`: name or path of parameter, e.g. `job.workflow` - * - `values`: list of values (use either `ref` or `values`) - * - `ref`: reference to values in another YAML file. - * - `exclude`: regular expression for excluding items. - * - `isOptional`: whether parameter is optional (adds `null` to values array) - * - `merge`: arrays or values from other sources to merge - * See the tests for example usage. - */ -export declare const parameterType: yaml.Type; -/** - * !combine YAML tag which creates combinations of objects (configs). - * The YAML object expects the following keys: - * - name: `name` property of object - * - name.template: nunjucks template for name (optional) - * - name.substitutions: in-place substitutions for template variables (optional) - * - forEach: list of parameter objects (defining key and value, see above) which is used to create combinations - * - forEach.key: object path to key - * - forEach.values: list of values - * - forEach.ignoreWith: list of keys for which combination with current key should be ignored - * - config: static config to be added to every object - * - extraConfigs: sequence of additional configs - * See the tests for example usage. - */ -export declare const combineType: yaml.Type; -/** - * !esse YAML tag which resolves an ESSE schema by id. - * See the tests for example usage. - */ -export declare const esseType: yaml.Type; -/** - * !include YAML tag which includes another Yaml file in-place. - * See the tests for example usage. - */ -export declare const includeType: yaml.Type; -/** - * !listToString YAML tag which concatenate each list item into single string value. - * See the tests for example usage. - */ -export declare const listToStringType: yaml.Type; -/** - * !flatten YAML tag for flattening arrays - * See the tests for example usage. - */ -export declare const flattenType: yaml.Type; -/** - * !readFile YAML tag for including file contents as a string. - * See the tests for example usage. - */ -export declare const readFileType: yaml.Type; -/** - * !concatString YAML tag for concatenating strings. - * See the tests for example usage. - */ -export declare const concatStringType: yaml.Type; -export declare const JsYamlTypes: { - include: yaml.Type; - listToString: yaml.Type; - parameter: yaml.Type; - combine: yaml.Type; - esse: yaml.Type; - flatten: yaml.Type; - readFile: yaml.Type; - concatString: yaml.Type; -}; -export declare const JsYamlAllSchemas: yaml.Schema; diff --git a/dist/js/utils/yaml.js b/dist/js/utils/yaml.js deleted file mode 100644 index f53705b7..00000000 --- a/dist/js/utils/yaml.js +++ /dev/null @@ -1,294 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsYamlAllSchemas = exports.JsYamlTypes = exports.concatStringType = exports.readFileType = exports.flattenType = exports.listToStringType = exports.includeType = exports.esseType = exports.combineType = exports.parameterType = void 0; -// @ts-nocheck -// TODO: remove ts-nocheck -const JSONSchemasInterfaceServer_1 = __importDefault(require("@mat3ra/esse/dist/js/esse/JSONSchemasInterfaceServer")); -const fs = __importStar(require("fs")); -const yaml = __importStar(require("js-yaml")); -const lodash = __importStar(require("lodash")); -const path = __importStar(require("path")); -const array_1 = require("./array"); -const str_1 = require("./str"); -/** - * Generate objects with combinations of parameters. - * @param {[{key: string, values: Array}]} parameterSets - Array of parameter objects - * @param {[[string, string]]} exclusions - Array of pairs of keys which should be excluded - * @return {Object[]} - Array of objects containing combinations of parameters - * @example - * generateCombinations([{key: "a", values: [1, 2]},{key: "b", values: [3, null]}]); - * // [{ a: 1 }, { a: 2 }, { a: 1, b: 3 }, { a: 2, b: 3 }] - */ -function generateCombinations(parameterSets, exclusions = []) { - const [head, ...rest] = parameterSets.filter((pObj) => { var _a; return pObj.key && ((_a = pObj.values) === null || _a === void 0 ? void 0 : _a.length); }); - if (!head) { - return [{}]; - } - const restCombinations = generateCombinations(rest); - const { key, values, action = "set" } = head; - let newCombinations = values.reduce((combs, value) => { - const valueCombinations = restCombinations.map((combination) => { - const newCombination = lodash.cloneDeep(combination); - if (value !== null && action === "set") { - lodash.set(newCombination, key, value); - } - else if (value !== null && action === "push") { - const arr = lodash.get(newCombination, key); - if (Array.isArray(arr)) { - arr.push(lodash.cloneDeep(value)); - } - else { - lodash.set(newCombination, key, [value]); - } - } - return newCombination; - }); - return [...combs, ...valueCombinations]; - }, []); - // Filter out unwanted combinations - newCombinations = newCombinations.filter((combination) => { - return !exclusions.some(([k1, k2]) => lodash.has(combination, k1) && lodash.has(combination, k2)); - }); - return newCombinations; -} -/** - * Utility function splitting a reference such as `"/path/to/source.yml#/name/lastName"` - * into the file path (`/path/to/source.yml`) and object path (`name.lastName`) compatible with lodash.get(). - * @param {string} ref - Reference to file with optional object path suffix - * @return {{ objPath: string, filePath: string }} - */ -function splitReference(ref) { - const filePath = ref.replace(/#.*$/, ""); - const objPath = ref.replace(/^(.*?)(?:#\/|$)/, "").replace(/\//g, "."); - return { filePath, objPath }; -} -/** - * Resolve path to YAML and return containing value if available. - * A specific key in the referenced YAML file can be specified via `#/keyName`, - * e.g. `"/path/to/source.yml#/name"`. - * @param {string} ref - path to YAML file (may specify key via `#/`) - */ -function readFromYaml(ref) { - const { filePath, objPath } = splitReference(ref); - const fileContent = fs.readFileSync(path.resolve(filePath), "utf8"); - // eslint-disable-next-line no-use-before-define, @typescript-eslint/no-use-before-define - const parsedContent = yaml.load(fileContent, { schema: exports.JsYamlAllSchemas }); - return objPath ? lodash.get(parsedContent, objPath) : parsedContent; -} -/** - * !parameter YAML tag, which creates an object containing - * `key`, the name of or path to the parameter and - * `values`, an array of values. - * Supports YAML objects with the following keys: - * - `key`: name or path of parameter, e.g. `job.workflow` - * - `values`: list of values (use either `ref` or `values`) - * - `ref`: reference to values in another YAML file. - * - `exclude`: regular expression for excluding items. - * - `isOptional`: whether parameter is optional (adds `null` to values array) - * - `merge`: arrays or values from other sources to merge - * See the tests for example usage. - */ -exports.parameterType = new yaml.Type("!parameter", { - kind: "mapping", - construct(data) { - const { key, values = [], ref, exclude, isOptional = false, merge = [], ...otherProps } = data; - try { - let values_ = ref && !values.length ? readFromYaml(ref) : values; - values_ = (0, array_1.safeMakeArray)(values_); - if (Array.isArray(merge)) { - values_ = values_.concat(merge.flat()); - } - if (exclude) { - const regex = new RegExp(exclude); - values_ = values_.filter((v) => !regex.test(v)); - } - if (isOptional) - values_.push(null); - return { key, values: values_, ...otherProps }; - } - catch (e) { - return data; - } - }, -}); -/** - * !combine YAML tag which creates combinations of objects (configs). - * The YAML object expects the following keys: - * - name: `name` property of object - * - name.template: nunjucks template for name (optional) - * - name.substitutions: in-place substitutions for template variables (optional) - * - forEach: list of parameter objects (defining key and value, see above) which is used to create combinations - * - forEach.key: object path to key - * - forEach.values: list of values - * - forEach.ignoreWith: list of keys for which combination with current key should be ignored - * - config: static config to be added to every object - * - extraConfigs: sequence of additional configs - * See the tests for example usage. - */ -exports.combineType = new yaml.Type("!combine", { - kind: "mapping", - construct(data) { - const { name, forEach = [], exclusions, config = {}, extraConfigs = [] } = data; - const combinations = generateCombinations(forEach, exclusions); - const configs = combinations.map((c) => lodash.merge(c, config)); - configs.forEach((c) => (c.name = (0, str_1.renderTextWithSubstitutes)((name === null || name === void 0 ? void 0 : name.template) || name, c, name === null || name === void 0 ? void 0 : name.substitutions))); - return extraConfigs.length ? configs.concat(extraConfigs.flat()) : configs; - }, -}); -/** - * !esse YAML tag which resolves an ESSE schema by id. - * See the tests for example usage. - */ -exports.esseType = new yaml.Type("!esse", { - kind: "scalar", - resolve(data) { - return data && lodash.isString(data); - }, - construct(data) { - try { - const { filePath: schemaId, objPath } = splitReference(data); - const schema = JSONSchemasInterfaceServer_1.default.getSchemaById(schemaId); - if (objPath) { - return lodash.get(schema, objPath); - } - return schema || data; - } - catch (e) { - return data; - } - }, -}); -/** - * !include YAML tag which includes another Yaml file in-place. - * See the tests for example usage. - */ -exports.includeType = new yaml.Type("!include", { - kind: "scalar", - construct(data) { - try { - return readFromYaml(data); - } - catch (e) { - return data; - } - }, -}); -/** - * !listToString YAML tag which concatenate each list item into single string value. - * See the tests for example usage. - */ -exports.listToStringType = new yaml.Type("!listToString", { - kind: "sequence", - construct(data) { - try { - return data.filter((d) => typeof d === "string").join(""); - } - catch (e) { - return data; - } - }, -}); -/** - * !flatten YAML tag for flattening arrays - * See the tests for example usage. - */ -exports.flattenType = new yaml.Type("!flatten", { - kind: "sequence", - construct(data) { - try { - return data.flat(); - } - catch (e) { - return data; - } - }, -}); -/** - * !readFile YAML tag for including file contents as a string. - * See the tests for example usage. - */ -exports.readFileType = new yaml.Type("!readFile", { - kind: "scalar", - construct(data) { - try { - return fs.readFileSync(path.resolve(data), "utf8"); - } - catch (e) { - return data; - } - }, -}); -/** - * !concatString YAML tag for concatenating strings. - * See the tests for example usage. - */ -exports.concatStringType = new yaml.Type("!concatString", { - kind: "sequence", - resolve(data) { - return data.every((d) => lodash.isString(d)); - }, - construct(data) { - try { - return "".concat(...data); - } - catch (e) { - return data; - } - }, -}); -exports.JsYamlTypes = { - include: exports.includeType, - listToString: exports.listToStringType, - parameter: exports.parameterType, - combine: exports.combineType, - esse: exports.esseType, - flatten: exports.flattenType, - readFile: exports.readFileType, - concatString: exports.concatStringType, -}; -exports.JsYamlAllSchemas = yaml.DEFAULT_SCHEMA.extend([ - exports.parameterType, - exports.combineType, - exports.esseType, - exports.includeType, - exports.listToStringType, - exports.flattenType, - exports.readFileType, - exports.concatStringType, -]); diff --git a/dist/js/validator/JsonSchemaValidator.d.ts b/dist/js/validator/JsonSchemaValidator.d.ts deleted file mode 100644 index 5c1bbac8..00000000 --- a/dist/js/validator/JsonSchemaValidator.d.ts +++ /dev/null @@ -1,127 +0,0 @@ -import Ajv, { ErrorObject } from "ajv"; -import type { AnyObject, ValidationSchema } from "./types"; -type ErrorResult = { - [key: string]: string | ErrorResult; -}; -export type JsonSchemaValidatorOptions = { - /** - * Delete object properties whose value is `null` before AJV (default: `true`). - * Nested objects are walked; array elements are not removed. - */ - removeNull?: boolean; - /** - * Delete object properties whose value is `""` before AJV (default: `true`). - * Keep `false` when empty strings are intentional placeholders (e.g. flowchart links). - */ - removeEmptyStrings?: boolean; -}; -export declare class JsonSchemaValidator { - private readonly ajv; - private readonly removeNull; - private readonly removeEmptyStrings; - private readonly formatCodeMap; - private readonly keywordsCodeMap; - constructor({ removeNull, removeEmptyStrings }?: JsonSchemaValidatorOptions); - /** - * Register host-specific AJV formats/keywords (e.g. web-app password/phone) on this instance. - */ - registerExtensions(register: (ajvInstance: Ajv) => void): void; - private getCompiledValidator; - /** - * Simplify AJV errors into LIVR-inspired field → code maps for API responses. - * Inspired by https://github.com/koorchik/LIVR - * - * @example of raw AJV errors: - * [ - * { - * "instancePath": "", - * "schemaPath": "#/required", - * "keyword": "required", - * "params": { - * "missingProperty": "intent" - * }, - * "message": "must have required property 'intent'" - * }, - * { - * "instancePath": "/user", - * "schemaPath": "#/properties/user/required", - * "keyword": "required", - * "params": { - * "missingProperty": "username" - * }, - * "message": "must have required property 'username'" - * }, - * { - * "instancePath": "/user", - * "schemaPath": "#/properties/user/required", - * "keyword": "required", - * "params": { - * "missingProperty": "fullname" - * }, - * "message": "must have required property 'fullname'" - * }, - * { - * "instancePath": "/user/termsAccepted", - * "schemaPath": "#/properties/user/properties/termsAccepted/type", - * "keyword": "type", - * "params": { - * "type": "boolean" - * }, - * "message": "must be boolean" - * }, - * { - * "instancePath": "/user/termsAccepted", - * "schemaPath": "#/properties/user/properties/termsAccepted/enum", - * "keyword": "enum", - * "params": { - * "allowedValues": [ - * true - * ] - * }, - * "message": "must be equal to one of the allowed values" - * }, - * { - * "instancePath": "/user/password", - * "schemaPath": "#/properties/user/properties/password/equalToField", - * "keyword": "equalToField", - * "params": {}, - * "message": "should be equal to the value of \"passwordConfirmation\"" - * }, - * { - * "instancePath": "/user/passwordConfirmation", - * "schemaPath": "#/properties/user/properties/passwordConfirmation/equalToField", - * "keyword": "equalToField", - * "params": {}, - * "message": "should be equal to the value of \"password\"" - * } - * ] - * - * @example of the same errors after transformation: - * { - * "intent": "REQUIRED", - * "user": { - * "username": "REQUIRED", - * "fullname": "REQUIRED", - * "termsAccepted": "FORMAT_ERROR", - * "password": "FIELDS_NOT_EQUAL", - * "passwordConfirmation": "FIELDS_NOT_EQUAL" - * } - * } - */ - transformErrors(errors?: ErrorObject[] | null): ErrorResult | undefined; - /** - * Validates and cleans data against the schema. - * Optionally drops null / empty-string properties (constructor options), then AJV removeAdditional. - */ - validateAndClean(data: AnyObject, jsonSchema: ValidationSchema): { - isValid: boolean | Promise; - errors: ErrorResult | undefined; - rawErrors: ErrorObject, unknown>[] | null | undefined; - validated: { - [x: string]: any; - }; - }; -} -/** Shared singleton — hosts register app formats on this instance (null + "" strip on). */ -export declare const jsonSchemaValidator: JsonSchemaValidator; -export {}; diff --git a/dist/js/validator/JsonSchemaValidator.js b/dist/js/validator/JsonSchemaValidator.js deleted file mode 100644 index 61826621..00000000 --- a/dist/js/validator/JsonSchemaValidator.js +++ /dev/null @@ -1,239 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.jsonSchemaValidator = exports.JsonSchemaValidator = void 0; -/** - * Standalone AJV validator for cleaning and validating JSON against JSON Schema. - * - * Why this exists (alongside esse `utils/ajv`): - * - Compose schemas with `mergeAllOf` and enforce allowlists via `additionalProperties: false` - * so callers can reject unknown / system-owned fields. - * - Optionally strip null / empty-string properties before type checks (see constructor options). - * - Map raw AJV errors into stable nested field → code objects (LIVR-style) for consumers that - * need machine-readable validation results. - * - * Distinct from `@mat3ra/esse` `utils/ajv.validateAndClean` (entity clean: null-only strip used by - * `InMemoryEntity.toJSON*`). Prefer this class/API for application validation; register host - * formats with {@link JsonSchemaValidator.registerExtensions}. - */ -const removeEmptyAndNullProperties_1 = require("@mat3ra/esse/dist/js/utils/removeEmptyAndNullProperties"); -const ajv_1 = __importDefault(require("ajv")); -const ajv_formats_1 = __importDefault(require("ajv-formats")); -const ajv_keywords_1 = __importDefault(require("ajv-keywords")); -const json_pointer_1 = __importDefault(require("json-pointer")); -const json_schema_merge_allof_1 = __importDefault(require("json-schema-merge-allof")); -const rules_1 = __importDefault(require("./rules")); -/** - * Recursively deletes empty-string object properties (mutates in place). - */ -function removeEmptyStringProperties(obj) { - if (typeof obj !== "object" || obj === null) { - return obj; - } - if (Array.isArray(obj)) { - obj.forEach((item) => removeEmptyStringProperties(item)); - return obj; - } - Object.keys(obj).forEach((key) => { - const value = obj[key]; - if (value === "") { - delete obj[key]; - } - else if (typeof value === "object") { - removeEmptyStringProperties(value); - } - }); - return obj; -} -class JsonSchemaValidator { - constructor({ removeNull = true, removeEmptyStrings = true } = {}) { - this.formatCodeMap = { - email: "WRONG_EMAIL", - "custom-email": "WRONG_EMAIL", - "custom-username": "WRONG_USERNAME", - "custom-phone": "WRONG_PHONE", - "custom-password": "WRONG_PASSWORD", - }; - this.keywordsCodeMap = { - required: "REQUIRED", - type: "FORMAT_ERROR", - equalToField: "FIELDS_NOT_EQUAL", - minLength: "TOO_SHORT", - maxLength: "TOO_LONG", - isoDate: "WRONG_DATE", - }; - this.removeNull = removeNull; - this.removeEmptyStrings = removeEmptyStrings; - this.ajv = new ajv_1.default({ - allErrors: true, - useDefaults: true, - discriminator: true, - removeAdditional: true, - coerceTypes: true, - allowUnionTypes: true, - // Esse / workflow schemas: json-schema-to-typescript-only keywords, and `default` inside - // discriminated `oneOf` branches where Ajv still treats nested rules as composite (see - // assignDefault + compositeRule). strictSchema would fail compilation for those valid schemas. - strictSchema: false, - }); - (0, ajv_formats_1.default)(this.ajv); - (0, ajv_keywords_1.default)(this.ajv); - (0, rules_1.default)(this.ajv); - } - /** - * Register host-specific AJV formats/keywords (e.g. web-app password/phone) on this instance. - */ - registerExtensions(register) { - register(this.ajv); - } - getCompiledValidator(jsonSchema) { - let validate = this.ajv.getSchema(jsonSchema.$id); - if (!validate) { - const schema = (0, json_schema_merge_allof_1.default)(jsonSchema, { ignoreAdditionalProperties: true }); - this.ajv.addSchema(schema, jsonSchema.$id); - validate = this.ajv.getSchema(jsonSchema.$id); - } - if (!validate) { - throw new Error("JSONSchemasInterface AJV validator error"); - } - return validate; - } - /** - * Simplify AJV errors into LIVR-inspired field → code maps for API responses. - * Inspired by https://github.com/koorchik/LIVR - * - * @example of raw AJV errors: - * [ - * { - * "instancePath": "", - * "schemaPath": "#/required", - * "keyword": "required", - * "params": { - * "missingProperty": "intent" - * }, - * "message": "must have required property 'intent'" - * }, - * { - * "instancePath": "/user", - * "schemaPath": "#/properties/user/required", - * "keyword": "required", - * "params": { - * "missingProperty": "username" - * }, - * "message": "must have required property 'username'" - * }, - * { - * "instancePath": "/user", - * "schemaPath": "#/properties/user/required", - * "keyword": "required", - * "params": { - * "missingProperty": "fullname" - * }, - * "message": "must have required property 'fullname'" - * }, - * { - * "instancePath": "/user/termsAccepted", - * "schemaPath": "#/properties/user/properties/termsAccepted/type", - * "keyword": "type", - * "params": { - * "type": "boolean" - * }, - * "message": "must be boolean" - * }, - * { - * "instancePath": "/user/termsAccepted", - * "schemaPath": "#/properties/user/properties/termsAccepted/enum", - * "keyword": "enum", - * "params": { - * "allowedValues": [ - * true - * ] - * }, - * "message": "must be equal to one of the allowed values" - * }, - * { - * "instancePath": "/user/password", - * "schemaPath": "#/properties/user/properties/password/equalToField", - * "keyword": "equalToField", - * "params": {}, - * "message": "should be equal to the value of \"passwordConfirmation\"" - * }, - * { - * "instancePath": "/user/passwordConfirmation", - * "schemaPath": "#/properties/user/properties/passwordConfirmation/equalToField", - * "keyword": "equalToField", - * "params": {}, - * "message": "should be equal to the value of \"password\"" - * } - * ] - * - * @example of the same errors after transformation: - * { - * "intent": "REQUIRED", - * "user": { - * "username": "REQUIRED", - * "fullname": "REQUIRED", - * "termsAccepted": "FORMAT_ERROR", - * "password": "FIELDS_NOT_EQUAL", - * "passwordConfirmation": "FIELDS_NOT_EQUAL" - * } - * } - */ - transformErrors(errors) { - if (!errors) { - return undefined; - } - const result = {}; - errors.forEach((error) => { - const code = error.keyword === "format" - ? this.formatCodeMap[error.params.format] || "FORMAT_ERROR" - : this.keywordsCodeMap[error.keyword] || "FORMAT_ERROR"; - const instancePath = error.params.missingProperty - ? `${error.instancePath}/${error.params.missingProperty}` - : error.instancePath; - json_pointer_1.default.set(result, instancePath, code); - }); - /** - * JSON.parse/JSON.stringify is required to fix <1 empty item> issue. - * @example - * pointer.set(result, "/nested/prop2/0", "ERROR_1"); - * pointer.set(result, "/nested/prop2/2", "ERROR_2"); - * - * without JSON.parse/JSON.stringify: - * result.prop2 === ["ERROR_1", <1 empty item>, "ERROR_2"] - * - * with JSON.parse/JSON.stringify: - * result.prop2 === ["ERROR_1", null, "ERROR_2"] - */ - return JSON.parse(JSON.stringify(result)); - } - /** - * Validates and cleans data against the schema. - * Optionally drops null / empty-string properties (constructor options), then AJV removeAdditional. - */ - validateAndClean(data, jsonSchema) { - const validated = { ...data }; - if (this.removeNull) { - (0, removeEmptyAndNullProperties_1.removeEmptyAndNullProperties)(validated); - } - if (this.removeEmptyStrings) { - removeEmptyStringProperties(validated); - } - const compiledValidator = this.getCompiledValidator({ - ...jsonSchema, - additionalProperties: false, - }); - const isValid = compiledValidator(validated); - return { - isValid, - errors: this.transformErrors(compiledValidator.errors || undefined), - rawErrors: compiledValidator.errors, - validated, - }; - } -} -exports.JsonSchemaValidator = JsonSchemaValidator; -/** Shared singleton — hosts register app formats on this instance (null + "" strip on). */ -exports.jsonSchemaValidator = new JsonSchemaValidator(); diff --git a/dist/js/validator/index.d.ts b/dist/js/validator/index.d.ts deleted file mode 100644 index 202c720a..00000000 --- a/dist/js/validator/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { JsonSchemaValidator, jsonSchemaValidator } from "./JsonSchemaValidator"; -export type { JsonSchemaValidatorOptions } from "./JsonSchemaValidator"; -export type { ErrorObject, SchemaObject } from "ajv"; -export type { AnyObject, ValidationSchema } from "./types"; diff --git a/dist/js/validator/index.js b/dist/js/validator/index.js deleted file mode 100644 index 2dc9ae91..00000000 --- a/dist/js/validator/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.jsonSchemaValidator = exports.JsonSchemaValidator = void 0; -var JsonSchemaValidator_1 = require("./JsonSchemaValidator"); -Object.defineProperty(exports, "JsonSchemaValidator", { enumerable: true, get: function () { return JsonSchemaValidator_1.JsonSchemaValidator; } }); -Object.defineProperty(exports, "jsonSchemaValidator", { enumerable: true, get: function () { return JsonSchemaValidator_1.jsonSchemaValidator; } }); diff --git a/dist/js/validator/rules/equalTo.d.ts b/dist/js/validator/rules/equalTo.d.ts deleted file mode 100644 index c0f7a056..00000000 --- a/dist/js/validator/rules/equalTo.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import Ajv from "ajv"; -export default function addEqualToFieldKeyword(ajv: Ajv): void; diff --git a/dist/js/validator/rules/equalTo.js b/dist/js/validator/rules/equalTo.js deleted file mode 100644 index 9eea62df..00000000 --- a/dist/js/validator/rules/equalTo.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = addEqualToFieldKeyword; -function addEqualToFieldKeyword(ajv) { - ajv.addKeyword({ - keyword: "equalToField", - type: "string", // Applies to string fields - schemaType: "string", // The schema for this keyword should be a string (field name) - validate(schema, data, _parentSchema, dataCxt) { - const otherFieldValue = dataCxt === null || dataCxt === void 0 ? void 0 : dataCxt.parentData[schema]; - return data === otherFieldValue; - }, - errors: true, // Enable error handling - error: { - message: (cxt) => `should be equal to the value of "${cxt.schema}"`, - }, - }); -} diff --git a/dist/js/validator/rules/index.d.ts b/dist/js/validator/rules/index.d.ts deleted file mode 100644 index dfbc5056..00000000 --- a/dist/js/validator/rules/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type Ajv from "ajv"; -/** - * Shared AJV formats/keywords for the standalone validator. - * App-specific formats (password, phone, username, email) are registered by the host. - */ -export default function addSharedFormatsAndKeywords(ajv: Ajv): void; diff --git a/dist/js/validator/rules/index.js b/dist/js/validator/rules/index.js deleted file mode 100644 index db61979c..00000000 --- a/dist/js/validator/rules/index.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = addSharedFormatsAndKeywords; -const jsonSchemaToTypescriptKeywords_1 = __importDefault(require("@mat3ra/esse/dist/js/utils/ajvKeywords/jsonSchemaToTypescriptKeywords")); -const equalTo_1 = __importDefault(require("./equalTo")); -const isoDate_1 = __importDefault(require("./isoDate")); -/** - * Shared AJV formats/keywords for the standalone validator. - * App-specific formats (password, phone, username, email) are registered by the host. - */ -function addSharedFormatsAndKeywords(ajv) { - (0, jsonSchemaToTypescriptKeywords_1.default)(ajv); - (0, equalTo_1.default)(ajv); - (0, isoDate_1.default)(ajv); -} diff --git a/dist/js/validator/rules/isoDate.d.ts b/dist/js/validator/rules/isoDate.d.ts deleted file mode 100644 index 3f41672e..00000000 --- a/dist/js/validator/rules/isoDate.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import Ajv from "ajv"; -export default function addIsoDateKeyword(ajv: Ajv): void; diff --git a/dist/js/validator/rules/isoDate.js b/dist/js/validator/rules/isoDate.js deleted file mode 100644 index 58fcabc4..00000000 --- a/dist/js/validator/rules/isoDate.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = addIsoDateKeyword; -function addIsoDateKeyword(ajv) { - ajv.addKeyword({ - keyword: "isoDate", - type: "string", - // eslint-disable-next-line @typescript-eslint/no-explicit-any - validate(_schema, data, _parentSchema, dataCxt) { - if (data === null || typeof data === "undefined") { - return true; - } - if (typeof data !== "string") { - return false; - } - const isValid = !Number.isNaN(Date.parse(data)); - if (isValid && dataCxt) { - dataCxt.parentData[dataCxt.parentDataProperty] = new Date(data); - } - return isValid; - }, - errors: false, - modifying: true, - metaSchema: { - type: "boolean", - }, - }); -} diff --git a/dist/js/validator/types.d.ts b/dist/js/validator/types.d.ts deleted file mode 100644 index 37633a2b..00000000 --- a/dist/js/validator/types.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { SchemaObject } from "ajv"; -export type ValidationSchema = SchemaObject & { - $id: string; -}; -export type AnyObject = Record; diff --git a/dist/js/validator/types.js b/dist/js/validator/types.js deleted file mode 100644 index c8ad2e54..00000000 --- a/dist/js/validator/types.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/js/vector.d.ts b/dist/js/vector.d.ts deleted file mode 100644 index 061139c8..00000000 --- a/dist/js/vector.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Vector3DSchema } from "@mat3ra/esse/dist/js/types"; -export declare class Vector3D { - static atol: number; - private _value; - constructor(value: number[] | Vector3DSchema); - get value(): Vector3DSchema; - get x(): number; - get y(): number; - get z(): number; - equals(other: number[] | Vector3DSchema | Vector3D): boolean; - get norm(): number; - translateByVector(vector: Vector3DSchema | Vector3D): Vector3D; -} -export declare class RoundedVector3D extends Vector3D { - static roundPrecision: number; - toJSON(skipRounding?: boolean): Vector3DSchema; - get valueRounded(): Vector3DSchema; - get xRounded(): number; - get yRounded(): number; - get zRounded(): number; - equals(other: Vector3DSchema | RoundedVector3D): boolean; - get normRounded(): number; -} diff --git a/dist/js/vector.js b/dist/js/vector.js deleted file mode 100644 index a59a2963..00000000 --- a/dist/js/vector.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoundedVector3D = exports.Vector3D = void 0; -const math_1 = require("./math"); -class Vector3D { - constructor(value) { - if (!Array.isArray(value) || - value.length !== 3 || - !value.every((v) => typeof v === "number")) { - throw new Error("Vector3D must be a tuple of exactly 3 numbers."); - } - this._value = [...value]; - } - get value() { - return this._value; - } - get x() { - return this._value[0]; - } - get y() { - return this._value[1]; - } - get z() { - return this._value[2]; - } - equals(other) { - if (Array.isArray(other)) { - if (other.length !== 3) { - throw new Error("Input must be a 3-element array."); - } - other = other; - } - const arr1 = this._value; - const arr2 = other instanceof Vector3D ? other.value : other; - return math_1.math.vEqualWithTolerance(arr1, arr2, Vector3D.atol); - } - get norm() { - return math_1.math.vlen(this._value); - } - translateByVector(vector) { - const arrayOfNumbers = vector instanceof Vector3D ? vector.value : vector; - this._value = this._value.map((v, i) => v + arrayOfNumbers[i]); - return this; - } -} -exports.Vector3D = Vector3D; -Vector3D.atol = 1e-8; -class RoundedVector3D extends Vector3D { - toJSON(skipRounding = false) { - const rounded = skipRounding - ? this.value - : math_1.math.roundArrayOrNumber(this.value, RoundedVector3D.roundPrecision); - return [...rounded]; - } - get valueRounded() { - return this.toJSON(); - } - get xRounded() { - return this.valueRounded[0]; - } - get yRounded() { - return this.valueRounded[1]; - } - get zRounded() { - return this.valueRounded[2]; - } - equals(other) { - const arr1 = this.valueRounded; - const arr2 = Array.isArray(other) - ? new RoundedVector3D(other).valueRounded - : other.valueRounded; - const atol = RoundedVector3D.atol || 10 ** -RoundedVector3D.roundPrecision; - return math_1.math.vEqualWithTolerance(arr1, arr2, atol); - } - get normRounded() { - return math_1.math.roundArrayOrNumber(this.norm, RoundedVector3D.roundPrecision); - } -} -exports.RoundedVector3D = RoundedVector3D; -RoundedVector3D.roundPrecision = 9; diff --git a/package.json b/package.json index d2c6037b..d29b370c 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,10 @@ "prettier": "prettier --check src/js tests/js", "test": "nyc --reporter=text mocha --recursive --bail tests/js", "transpile": "tsc -p tsconfig-transpile.json", - "generate-mixins": "ts-node scripts/generate-mixins.ts" + "generate-mixins": "ts-node scripts/generate-mixins.ts", + "references:sync": "node ../../scripts/manageReferencePackages.mjs sync", + "references:install": "node ../../scripts/manageReferencePackages.mjs install", + "prepublishOnly": "npm run transpile" }, "repository": { "type": "git", @@ -60,7 +63,7 @@ "@babel/register": "^7.25.7", "@babel/runtime-corejs3": "^7.25.7", "@exabyte-io/eslint-config": "^2025.1.15-0", - "@mat3ra/esse": "https://github.com/mat3ra/esse/tarball/13eb236299a2d5f3a43e75d1fe9e121deb674c0e", + "@mat3ra/esse": "2026.7.21-0", "@mat3ra/tsconfig": "2024.6.3-0", "@types/chai": "^4.3.20", "@types/crypto-js": "^4.2.2", diff --git a/references.yml b/references.yml new file mode 100644 index 00000000..48204d62 --- /dev/null +++ b/references.yml @@ -0,0 +1,4 @@ +# Nested consumer pins for the web-app multi-consumer root. +# Runner: ../../scripts/manageReferencePackages.mjs (shared catalog + tarball cache at repo root). +targets: + esse: chore/SOF-7942