@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
62 lines (61 loc) • 2.59 kB
JavaScript
//#region src/assertions.ts
function requireDefined(value, message) {
if (value === null || value === void 0) {
let error = "Unexpected null or undefined value";
if (message) error += ": " + message;
throwAtCaller(requireDefined, new Error(error));
}
return value;
}
function assert(condition, message) {
if (!condition) throwAtCaller(assert, new AssertionError(unwrapErrorMessage(message)));
}
/**
* Shorthand for throw new AssertionError("Error message")
* Useful because it is an expression instead of a statement.
* Can be assigned to any value, because it never returns.
*/
function panic(message) {
throwAtCaller(panic, new AssertionError(unwrapErrorMessage(message)));
}
/**
* A soft assertion that throws an error in non prod environments, including
* staging, but logs an error in production mode.
* This is useful for cases where something unexpected happens, but you can still
* continue in a slightly broken state.
* For example, if a block has defined a style control with a hardcoded id and
* that style control is not found, this is definitely a bug, but it's still
* possible to go on rendering with a fallback value for this style.
* It is recommended to liberally use soft assertions so that we fail loudly in
* staging and local environments.
*
* A hard assertion would be more appropriate if we wanted to display some data
* from an object but that object is null. It's better to throw an assertion
* error at the place we detect this, instead of continuing and potentially
* causing an exception in an unrelated part of the code.
*/
function softAssert(condition, message) {
if (!condition) if (process.env.NODE_ENV !== "production") throwAtCaller(softAssert, new SoftAssertionError(unwrapErrorMessage(message)));
else console.error(`Assertion failed: ${unwrapErrorMessage(message)}`);
}
var AssertionError = class extends Error {
name = "AssertionError";
};
var SoftAssertionError = class extends Error {
name = "SoftAssertionError";
};
function unwrapErrorMessage(message) {
return typeof message === "function" ? message() : message ?? "";
}
/**
* Uses chrome's non-standard Error.captureStackTrace to set the top of the stack
* trace to start from the caller of the supplied function {@param f}.
* Useful in assertion functions to make sure that the stack trace shows the spot
* where the assertion failed, not the place where the assertion was thrown.
*/
function throwAtCaller(f, ex) {
if (Error.captureStackTrace) Error.captureStackTrace(ex, f);
throw ex;
}
//#endregion
export { assert, panic, requireDefined, softAssert, throwAtCaller };