synthase
Version:
A secure, sandboxed, and extensible JavaScript execution engine built with TypeScript.
141 lines (139 loc) • 3.75 kB
JavaScript
// src/types.ts
var ParameterUtils = class {
static normalize(spec) {
if (typeof spec === "string") {
return { type: spec };
}
return spec;
}
static getDefault(spec) {
const param = this.normalize(spec);
if (param.default !== void 0) {
return param.default;
}
switch (param.type) {
case "int":
return 0;
case "float":
return 0;
case "string":
return "";
case "boolean":
return false;
case "object":
return {};
case "array":
return [];
default:
return null;
}
}
static applyDefaults(inputs, schema) {
const result = { ...inputs };
for (const [key, spec] of Object.entries(schema)) {
if (!(key in result)) {
result[key] = this.getDefault(spec);
}
}
return result;
}
static validateParameter(value, spec, paramName) {
const param = this.normalize(spec);
switch (param.type) {
case "int":
if (!Number.isInteger(value)) {
throw new Error(
`${paramName} must be an integer, got: ${typeof value}`
);
}
if (param.min !== void 0 && value < param.min) {
throw new Error(
`${paramName} must be >= ${param.min}, got: ${value}`
);
}
if (param.max !== void 0 && value > param.max) {
throw new Error(
`${paramName} must be <= ${param.max}, got: ${value}`
);
}
break;
case "float":
if (typeof value !== "number") {
throw new Error(
`${paramName} must be a number, got: ${typeof value}`
);
}
if (param.min !== void 0 && value < param.min) {
throw new Error(
`${paramName} must be >= ${param.min}, got: ${value}`
);
}
if (param.max !== void 0 && value > param.max) {
throw new Error(
`${paramName} must be <= ${param.max}, got: ${value}`
);
}
break;
case "string":
if (typeof value !== "string") {
throw new Error(
`${paramName} must be a string, got: ${typeof value}`
);
}
if (param.options && !param.options.includes(value)) {
throw new Error(
`${paramName} must be one of: ${param.options.join(
", "
)}, got: ${value}`
);
}
break;
case "boolean":
if (typeof value !== "boolean") {
throw new Error(
`${paramName} must be a boolean, got: ${typeof value}`
);
}
break;
case "object":
if (typeof value !== "object" || value === null) {
throw new Error(
`${paramName} must be an object, got: ${typeof value}`
);
}
break;
case "array":
if (!Array.isArray(value)) {
throw new Error(
`${paramName} must be an array, got: ${typeof value}`
);
}
break;
}
}
static shouldShowParameter(spec, allInputs) {
const param = this.normalize(spec);
if (!param.dependsOn) return true;
for (const [depKey, depValue] of Object.entries(param.dependsOn)) {
if (allInputs[depKey] !== depValue) {
return false;
}
}
return true;
}
static groupParameters(schema) {
const groups = { default: [] };
for (const [key, spec] of Object.entries(schema)) {
const param = this.normalize(spec);
const group = param.group || "default";
if (!groups[group]) {
groups[group] = [];
}
groups[group].push(key);
}
return groups;
}
};
export {
ParameterUtils
};