Skip to content

Commit

Permalink
fix(lr-config): validate passed settings
Browse files Browse the repository at this point in the history
  • Loading branch information
nd0ut committed Oct 26, 2023
1 parent b35ffb8 commit 6012581
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions blocks/Config/normalizeConfigValue.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
// @ts-check

import { initialConfig } from './initialConfig.js';

/** @param {unknown} value */
const asString = (value) => String(value);
/** @param {unknown} value */
const asNumber = (value) => Number(value);
const asNumber = (value) => {
const number = Number(value);
if (Number.isNaN(number)) {
throw new Error(`Invalid number: "${value}"`);
}
return number;
};
/** @param {unknown} value */
export const asBoolean = (value) => {
if (typeof value === 'undefined' || value === null) return false;
if (typeof value === 'boolean') return value;
// for attr like multiple="true" (react will pass it as string)
if (value === 'true') return true;
// for attr flags like multiple="" (some other libs will pass it as empty string)
if (value === '') return true;
// for attr like multiple="false" (react will pass it as string)
if (value === 'false') return false;
return Boolean(value);
throw new Error(`Invalid boolean: "${value}"`);
};
/** @param {unknown} value */
const asStore = (value) => (value === 'auto' ? value : asBoolean(value));

/**
* @type {{
* [Key in keyof import('../../types').ConfigPlainType]: (value: unknown) => import('../../types').ConfigType[Key];
* [Key in keyof import('../../types').ConfigPlainType]: (
* value: unknown
* ) => import('../../types').ConfigType[Key] | undefined;
* }}
*/
const mapping = {
Expand Down Expand Up @@ -80,5 +91,11 @@ export const normalizeConfigValue = (key, value) => {
if (typeof value === 'undefined' || value === null) {
return undefined;
}
return mapping[key](value);

try {
return mapping[key](value);
} catch (reason) {
console.error(`Invalid value for config key "${key}".`, reason);
return initialConfig[key];
}
};

0 comments on commit 6012581

Please sign in to comment.