🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@elementor/utils

Package Overview
Dependencies
Maintainers
7
Versions
864
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@elementor/utils - npm Package Compare versions

Comparing version
0.1.0
to
0.2.0
+22
.turbo/turbo-build.log
> @elementor/utils@0.1.0 build
> tsup --config=../../tsup.build.ts
CLI Building entry: src/index.ts
CLI Using tsconfig: ../../../tsconfig.json
CLI tsup v7.2.0
CLI Using tsup config: /home/runner/work/elementor-packages/elementor-packages/tsup.build.ts
CLI Target: esnext
CLI Cleaning output folder
ESM Build start
CJS Build start
ESM dist/index.mjs 922.00 B
ESM dist/index.mjs.map 2.13 KB
ESM ⚡️ Build success in 114ms
CJS dist/index.js 1.97 KB
CJS dist/index.js.map 2.35 KB
CJS ⚡️ Build success in 115ms
DTS Build start
DTS ⚡️ Build success in 22795ms
DTS dist/index.d.mts 1.24 KB
DTS dist/index.d.ts 1.24 KB
export const ensureError = ( error: unknown ) => {
if ( error instanceof Error ) {
return error;
}
let message: string;
let cause: unknown = null;
try {
message = JSON.stringify( error );
} catch ( e ) {
cause = e;
message = 'Unable to stringify the thrown value';
}
return new Error( `Unexpected non-error thrown: ${ message }`, { cause } );
};
+6
-0

@@ -6,2 +6,8 @@ # Change Log

# [0.2.0](https://github.com/elementor/elementor-packages/compare/@elementor/utils@0.1.0...@elementor/utils@0.2.0) (2024-07-28)
### Features
- **utils/errors:** add `ensureError` function [EDS-291] ([#218](https://github.com/elementor/elementor-packages/issues/218)) ([915d521](https://github.com/elementor/elementor-packages/commit/915d5214831c249f308ba9344ad9eecdc2887fe4))
# 0.1.0 (2024-07-24)

@@ -8,0 +14,0 @@

+9
-7
type ElementorErrorOptions = {
cause?: unknown;
cause?: Error['cause'];
context?: Record<string, unknown> | null;

@@ -8,3 +8,3 @@ code: string;

readonly context: ElementorErrorOptions['context'];
readonly code: string;
readonly code: ElementorErrorOptions['code'];
constructor(message: string, { code, context, cause }: ElementorErrorOptions);

@@ -14,8 +14,8 @@ }

type CreateErrorParams = {
code: string;
code: ElementorErrorOptions['code'];
message: string;
};
declare const createError: <T extends Record<string, unknown>>({ code, message }: CreateErrorParams) => {
new ({ cause, context }: {
cause?: Error;
declare const createError: <T extends Record<string, unknown> | null | undefined>({ code, message }: CreateErrorParams) => {
new ({ cause, context }?: {
cause?: ElementorErrorOptions['cause'];
context?: T;

@@ -35,2 +35,4 @@ }): {

export { CreateErrorParams, ElementorError, ElementorErrorOptions, createError };
declare const ensureError: (error: unknown) => Error;
export { CreateErrorParams, ElementorError, ElementorErrorOptions, createError, ensureError };
type ElementorErrorOptions = {
cause?: unknown;
cause?: Error['cause'];
context?: Record<string, unknown> | null;

@@ -8,3 +8,3 @@ code: string;

readonly context: ElementorErrorOptions['context'];
readonly code: string;
readonly code: ElementorErrorOptions['code'];
constructor(message: string, { code, context, cause }: ElementorErrorOptions);

@@ -14,8 +14,8 @@ }

type CreateErrorParams = {
code: string;
code: ElementorErrorOptions['code'];
message: string;
};
declare const createError: <T extends Record<string, unknown>>({ code, message }: CreateErrorParams) => {
new ({ cause, context }: {
cause?: Error;
declare const createError: <T extends Record<string, unknown> | null | undefined>({ code, message }: CreateErrorParams) => {
new ({ cause, context }?: {
cause?: ElementorErrorOptions['cause'];
context?: T;

@@ -35,2 +35,4 @@ }): {

export { CreateErrorParams, ElementorError, ElementorErrorOptions, createError };
declare const ensureError: (error: unknown) => Error;
export { CreateErrorParams, ElementorError, ElementorErrorOptions, createError, ensureError };

@@ -24,3 +24,4 @@ "use strict";

ElementorError: () => ElementorError,
createError: () => createError
createError: () => createError,
ensureError: () => ensureError
});

@@ -43,3 +44,3 @@ module.exports = __toCommonJS(src_exports);

return class extends ElementorError {
constructor({ cause, context }) {
constructor({ cause, context } = {}) {
super(message, { cause, code, context });

@@ -49,7 +50,24 @@ }

};
// src/errors/ensure-error.ts
var ensureError = (error) => {
if (error instanceof Error) {
return error;
}
let message;
let cause = null;
try {
message = JSON.stringify(error);
} catch (e) {
cause = e;
message = "Unable to stringify the thrown value";
}
return new Error(`Unexpected non-error thrown: ${message}`, { cause });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ElementorError,
createError
createError,
ensureError
});
//# sourceMappingURL=index.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/index.ts","../src/errors/elementor-error.ts","../src/errors/create-error.ts"],"sourcesContent":["export { ElementorError, createError } from './errors';\nexport type { ElementorErrorOptions, CreateErrorParams } from './errors';\n","export type ElementorErrorOptions = {\n\tcause?: unknown;\n\tcontext?: Record< string, unknown > | null;\n\tcode: string;\n};\n\nexport class ElementorError extends Error {\n\treadonly context: ElementorErrorOptions[ 'context' ];\n\treadonly code: string;\n\n\tconstructor( message: string, { code, context = null, cause = null }: ElementorErrorOptions ) {\n\t\tsuper( message, { cause } );\n\t\tthis.context = context;\n\t\tthis.code = code;\n\t}\n}\n","import { ElementorError } from './elementor-error';\n\nexport type CreateErrorParams = {\n\tcode: string;\n\tmessage: string;\n};\n\nexport const createError = < T extends Record< string, unknown > >( { code, message }: CreateErrorParams ) => {\n\treturn class extends ElementorError {\n\t\tconstructor( { cause, context }: { cause?: Error; context?: T } ) {\n\t\t\tsuper( message, { cause, code, context } );\n\t\t}\n\t};\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YAAa,SAAiB,EAAE,MAAM,UAAU,MAAM,QAAQ,KAAK,GAA2B;AAC7F,UAAO,SAAS,EAAE,MAAM,CAAE;AAC1B,SAAK,UAAU;AACf,SAAK,OAAO;AAAA,EACb;AACD;;;ACRO,IAAM,cAAc,CAAyC,EAAE,MAAM,QAAQ,MAA0B;AAC7G,SAAO,cAAc,eAAe;AAAA,IACnC,YAAa,EAAE,OAAO,QAAQ,GAAoC;AACjE,YAAO,SAAS,EAAE,OAAO,MAAM,QAAQ,CAAE;AAAA,IAC1C;AAAA,EACD;AACD;","names":[]}
{"version":3,"sources":["../src/index.ts","../src/errors/elementor-error.ts","../src/errors/create-error.ts","../src/errors/ensure-error.ts"],"sourcesContent":["export { ElementorError, createError, ensureError } from './errors';\nexport type { ElementorErrorOptions, CreateErrorParams } from './errors';\n","export type ElementorErrorOptions = {\n\tcause?: Error[ 'cause' ];\n\tcontext?: Record< string, unknown > | null;\n\tcode: string;\n};\n\nexport class ElementorError extends Error {\n\treadonly context: ElementorErrorOptions[ 'context' ];\n\treadonly code: ElementorErrorOptions[ 'code' ];\n\n\tconstructor( message: string, { code, context = null, cause = null }: ElementorErrorOptions ) {\n\t\tsuper( message, { cause } );\n\t\tthis.context = context;\n\t\tthis.code = code;\n\t}\n}\n","import { ElementorError, ElementorErrorOptions } from './elementor-error';\n\nexport type CreateErrorParams = {\n\tcode: ElementorErrorOptions[ 'code' ];\n\tmessage: string;\n};\n\nexport const createError = < T extends ElementorErrorOptions[ 'context' ] >( { code, message }: CreateErrorParams ) => {\n\treturn class extends ElementorError {\n\t\tconstructor( { cause, context }: { cause?: ElementorErrorOptions[ 'cause' ]; context?: T } = {} ) {\n\t\t\tsuper( message, { cause, code, context } );\n\t\t}\n\t};\n};\n","export const ensureError = ( error: unknown ) => {\n\tif ( error instanceof Error ) {\n\t\treturn error;\n\t}\n\n\tlet message: string;\n\tlet cause: unknown = null;\n\n\ttry {\n\t\tmessage = JSON.stringify( error );\n\t} catch ( e ) {\n\t\tcause = e;\n\t\tmessage = 'Unable to stringify the thrown value';\n\t}\n\treturn new Error( `Unexpected non-error thrown: ${ message }`, { cause } );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YAAa,SAAiB,EAAE,MAAM,UAAU,MAAM,QAAQ,KAAK,GAA2B;AAC7F,UAAO,SAAS,EAAE,MAAM,CAAE;AAC1B,SAAK,UAAU;AACf,SAAK,OAAO;AAAA,EACb;AACD;;;ACRO,IAAM,cAAc,CAAkD,EAAE,MAAM,QAAQ,MAA0B;AACtH,SAAO,cAAc,eAAe;AAAA,IACnC,YAAa,EAAE,OAAO,QAAQ,IAA+D,CAAC,GAAI;AACjG,YAAO,SAAS,EAAE,OAAO,MAAM,QAAQ,CAAE;AAAA,IAC1C;AAAA,EACD;AACD;;;ACbO,IAAM,cAAc,CAAE,UAAoB;AAChD,MAAK,iBAAiB,OAAQ;AAC7B,WAAO;AAAA,EACR;AAEA,MAAI;AACJ,MAAI,QAAiB;AAErB,MAAI;AACH,cAAU,KAAK,UAAW,KAAM;AAAA,EACjC,SAAU,GAAI;AACb,YAAQ;AACR,cAAU;AAAA,EACX;AACA,SAAO,IAAI,MAAO,gCAAiC,OAAQ,IAAI,EAAE,MAAM,CAAE;AAC1E;","names":[]}

@@ -15,3 +15,3 @@ // src/errors/elementor-error.ts

return class extends ElementorError {
constructor({ cause, context }) {
constructor({ cause, context } = {}) {
super(message, { cause, code, context });

@@ -21,6 +21,23 @@ }

};
// src/errors/ensure-error.ts
var ensureError = (error) => {
if (error instanceof Error) {
return error;
}
let message;
let cause = null;
try {
message = JSON.stringify(error);
} catch (e) {
cause = e;
message = "Unable to stringify the thrown value";
}
return new Error(`Unexpected non-error thrown: ${message}`, { cause });
};
export {
ElementorError,
createError
createError,
ensureError
};
//# sourceMappingURL=index.mjs.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/errors/elementor-error.ts","../src/errors/create-error.ts"],"sourcesContent":["export type ElementorErrorOptions = {\n\tcause?: unknown;\n\tcontext?: Record< string, unknown > | null;\n\tcode: string;\n};\n\nexport class ElementorError extends Error {\n\treadonly context: ElementorErrorOptions[ 'context' ];\n\treadonly code: string;\n\n\tconstructor( message: string, { code, context = null, cause = null }: ElementorErrorOptions ) {\n\t\tsuper( message, { cause } );\n\t\tthis.context = context;\n\t\tthis.code = code;\n\t}\n}\n","import { ElementorError } from './elementor-error';\n\nexport type CreateErrorParams = {\n\tcode: string;\n\tmessage: string;\n};\n\nexport const createError = < T extends Record< string, unknown > >( { code, message }: CreateErrorParams ) => {\n\treturn class extends ElementorError {\n\t\tconstructor( { cause, context }: { cause?: Error; context?: T } ) {\n\t\t\tsuper( message, { cause, code, context } );\n\t\t}\n\t};\n};\n"],"mappings":";AAMO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YAAa,SAAiB,EAAE,MAAM,UAAU,MAAM,QAAQ,KAAK,GAA2B;AAC7F,UAAO,SAAS,EAAE,MAAM,CAAE;AAC1B,SAAK,UAAU;AACf,SAAK,OAAO;AAAA,EACb;AACD;;;ACRO,IAAM,cAAc,CAAyC,EAAE,MAAM,QAAQ,MAA0B;AAC7G,SAAO,cAAc,eAAe;AAAA,IACnC,YAAa,EAAE,OAAO,QAAQ,GAAoC;AACjE,YAAO,SAAS,EAAE,OAAO,MAAM,QAAQ,CAAE;AAAA,IAC1C;AAAA,EACD;AACD;","names":[]}
{"version":3,"sources":["../src/errors/elementor-error.ts","../src/errors/create-error.ts","../src/errors/ensure-error.ts"],"sourcesContent":["export type ElementorErrorOptions = {\n\tcause?: Error[ 'cause' ];\n\tcontext?: Record< string, unknown > | null;\n\tcode: string;\n};\n\nexport class ElementorError extends Error {\n\treadonly context: ElementorErrorOptions[ 'context' ];\n\treadonly code: ElementorErrorOptions[ 'code' ];\n\n\tconstructor( message: string, { code, context = null, cause = null }: ElementorErrorOptions ) {\n\t\tsuper( message, { cause } );\n\t\tthis.context = context;\n\t\tthis.code = code;\n\t}\n}\n","import { ElementorError, ElementorErrorOptions } from './elementor-error';\n\nexport type CreateErrorParams = {\n\tcode: ElementorErrorOptions[ 'code' ];\n\tmessage: string;\n};\n\nexport const createError = < T extends ElementorErrorOptions[ 'context' ] >( { code, message }: CreateErrorParams ) => {\n\treturn class extends ElementorError {\n\t\tconstructor( { cause, context }: { cause?: ElementorErrorOptions[ 'cause' ]; context?: T } = {} ) {\n\t\t\tsuper( message, { cause, code, context } );\n\t\t}\n\t};\n};\n","export const ensureError = ( error: unknown ) => {\n\tif ( error instanceof Error ) {\n\t\treturn error;\n\t}\n\n\tlet message: string;\n\tlet cause: unknown = null;\n\n\ttry {\n\t\tmessage = JSON.stringify( error );\n\t} catch ( e ) {\n\t\tcause = e;\n\t\tmessage = 'Unable to stringify the thrown value';\n\t}\n\treturn new Error( `Unexpected non-error thrown: ${ message }`, { cause } );\n};\n"],"mappings":";AAMO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YAAa,SAAiB,EAAE,MAAM,UAAU,MAAM,QAAQ,KAAK,GAA2B;AAC7F,UAAO,SAAS,EAAE,MAAM,CAAE;AAC1B,SAAK,UAAU;AACf,SAAK,OAAO;AAAA,EACb;AACD;;;ACRO,IAAM,cAAc,CAAkD,EAAE,MAAM,QAAQ,MAA0B;AACtH,SAAO,cAAc,eAAe;AAAA,IACnC,YAAa,EAAE,OAAO,QAAQ,IAA+D,CAAC,GAAI;AACjG,YAAO,SAAS,EAAE,OAAO,MAAM,QAAQ,CAAE;AAAA,IAC1C;AAAA,EACD;AACD;;;ACbO,IAAM,cAAc,CAAE,UAAoB;AAChD,MAAK,iBAAiB,OAAQ;AAC7B,WAAO;AAAA,EACR;AAEA,MAAI;AACJ,MAAI,QAAiB;AAErB,MAAI;AACH,cAAU,KAAK,UAAW,KAAM;AAAA,EACjC,SAAU,GAAI;AACb,YAAQ;AACR,cAAU;AAAA,EACX;AACA,SAAO,IAAI,MAAO,gCAAiC,OAAQ,IAAI,EAAE,MAAM,CAAE;AAC1E;","names":[]}
{
"name": "@elementor/utils",
"description": "This package contains utility functions that are being used across the Elementor packages",
"version": "0.1.0",
"version": "0.2.0",
"private": false,

@@ -35,3 +35,3 @@ "author": "Elementor Team",

},
"gitHead": "b622ed27c9abc265dcd14940b4cf5b5e372db898"
"gitHead": "c2f7a53e5af66a39640eb0849065d07efd554690"
}
+45
-31
# Utils
This package contains utility functions that are being used across the Elementor packages.
## Installation
```bash
npm install @elementor/utils
```
### Errors
## Errors
This module contains a standard API for creating custom error classes in Elementor packages.
#### Usage
### `createError`
To ensure consistency across the Elementor packages, we recommend creating a new error class that extends the
`ElementorError` class, or using the `createError` function that does it for you.
`ElementorError` class using the `createError` function that does it for you.
#### Creating a new error manually
You can create a new error that extends the `ElementorError`.
#### Creating a new error type
For convenience, we've exposed a `createError` utility function that will create a custom error type for you.
This function will force your error code and message to be static (per our guidelines), and will shorten your code a little bit:
```ts
// errors.ts
import { createError } from '@elementor/utils';
export const CannotRender = createError<{ id: string; }>( 'cannot-render', 'Cannot render element' );
export const CannotSave = createError<{ id: number; status: string; }>( 'cannot-save', 'Cannot save document' );
export const ElementNotFound = createError<{ id: string; }>( 'element-not-found', 'Element not found' );
```
#### Creating a new error type manually
If you prefer to create a new error type manually, you can extend the `ElementorError` class.
Inside your class, you'll need to define a unique error code and message that should be passed to the parent constructor.

@@ -47,18 +55,5 @@

#### Using the `createError` function
For convenience, we've exposed a `createError` utility function that will create a custom error for you.
This function will force your error code and message to be static (per our guidelines), and will shorten your code a little bit:
#### Throwing your custom error type
After creating your custom error type (as described above), you can throw it in your code:
```ts
// errors.ts
import { createError } from '@elementor/utils';
export const CannotRender = createError<{ id: string; }>( 'cannot-render', 'Cannot render element' );
export const CannotSave = createError<{ id: number; status: string; }>( 'cannot-save', 'Cannot save document' );
export const ElementNotFound = createError<{ id: string; }>( 'element-not-found', 'Element not found' );
```
#### Throwing an error
After creating your custom error (as described above), you can throw it in your code:
Basic example:

@@ -68,6 +63,6 @@ ```ts

function renderElement(id: string): string {
const element = findElementById(id);
function renderElement( id: string ): string {
const element = findElementById( id );
if (!element) {
if ( ! element ) {
throw new ElementNotFound({ context: { id } });

@@ -85,6 +80,25 @@ }

try {
thirdPartyService.save(number);
} catch (error) {
throw new CannotSave({ context: { id: number, status: error.status }, cause: error });
thirdPartyService.save( id );
} catch ( error ) {
throw new CannotSave({ context: { id, status: error.status }, cause: error });
}
```
### `ensureError`
The `ensureError` function is a utility function that ensures that the given value is an error.
If the value is already an error, it will be returned as is.
If the value is not an error, it will be wrapped with an `Error` that includes the thrown value.
```ts
import { ensureError } from '@elementor/utils';
const CannotUpdate = createError<{ id: number; }>( 'cannot-update', 'Cannot update document' );
try {
thirdPartyService.update( id );
} catch ( error ) {
const errorInstance = ensureError( error );
throw new CannotUpdate({ context: { id }, cause: errorInstance });
}
```
import { createError } from '../create-error';
import { ElementorError } from '../elementor-error';
import { ensureError } from '../ensure-error';

@@ -30,1 +31,41 @@ describe( 'createError', () => {

} );
describe( 'ensureError', () => {
it( 'should return the same error instance when the input is an error', () => {
// Arrange.
const TestError = createError( { code: 'test-error', message: 'This is a test error' } );
const error = new TestError();
// Act.
const result = ensureError( error );
// Assert.
expect( result ).toBe( error );
} );
it( 'should return an error with the stringified input in the error message when the input is not an error', () => {
// Arrange.
const errorObject = { message: 'test error' };
const expectedMessage = JSON.stringify( errorObject );
// Act.
const result = ensureError( errorObject );
// Assert.
expect( result ).toBeInstanceOf( Error );
expect( result.message ).toContain( expectedMessage );
} );
it( "should return an error when the input can't be stringified", () => {
// Arrange.
const errorObject = { circular: {} };
errorObject.circular = errorObject;
// Act.
const result = ensureError( errorObject );
// Assert.
expect( result ).toBeInstanceOf( Error );
expect( result.cause ).toBeInstanceOf( TypeError );
} );
} );

@@ -1,11 +0,11 @@

import { ElementorError } from './elementor-error';
import { ElementorError, ElementorErrorOptions } from './elementor-error';
export type CreateErrorParams = {
code: string;
code: ElementorErrorOptions[ 'code' ];
message: string;
};
export const createError = < T extends Record< string, unknown > >( { code, message }: CreateErrorParams ) => {
export const createError = < T extends ElementorErrorOptions[ 'context' ] >( { code, message }: CreateErrorParams ) => {
return class extends ElementorError {
constructor( { cause, context }: { cause?: Error; context?: T } ) {
constructor( { cause, context }: { cause?: ElementorErrorOptions[ 'cause' ]; context?: T } = {} ) {
super( message, { cause, code, context } );

@@ -12,0 +12,0 @@ }

export type ElementorErrorOptions = {
cause?: unknown;
cause?: Error[ 'cause' ];
context?: Record< string, unknown > | null;

@@ -9,3 +9,3 @@ code: string;

readonly context: ElementorErrorOptions[ 'context' ];
readonly code: string;
readonly code: ElementorErrorOptions[ 'code' ];

@@ -12,0 +12,0 @@ constructor( message: string, { code, context = null, cause = null }: ElementorErrorOptions ) {

export { ElementorError, type ElementorErrorOptions } from './elementor-error';
export { createError, type CreateErrorParams } from './create-error';
export { ensureError } from './ensure-error';

@@ -1,2 +0,2 @@

export { ElementorError, createError } from './errors';
export { ElementorError, createError, ensureError } from './errors';
export type { ElementorErrorOptions, CreateErrorParams } from './errors';