@sketch-hq/sketch-assistant-utils
Version:
Utility functions and types for Sketch Assistants.
53 lines (52 loc) • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildAssistantConfigSchema = void 0;
const sketch_assistant_types_1 = require("@sketch-hq/sketch-assistant-types");
const rule_option_schemas_1 = require("../rule-option-schemas");
const getReservedRuleOptions = (config) => {
const typeMap = {
[sketch_assistant_types_1.ReservedRuleOptionNames.active]: 'boolean',
[sketch_assistant_types_1.ReservedRuleOptionNames.severity]: 'number',
[sketch_assistant_types_1.ReservedRuleOptionNames.ruleTitle]: 'string',
};
return Object.entries(typeMap).reduce((acc, [opt, type]) => {
if (!(opt in config))
return acc;
return Object.assign(Object.assign({}, acc), { [opt]: { type } });
}, {});
};
const applyRuleConfig = (ops, config) => {
return Object.entries(ops).reduce((acc, [key, schema]) => {
return Object.assign(Object.assign({}, acc), { [key]: Object.assign(Object.assign({}, schema), { default: config[key] }) });
}, {});
};
/**
* Builds the JSON Schema for the configuration accepted by the given
* assistant. The schema is augmented with assistant's configuration,
* meaning the options set in the configuration are used as default values
* for the corresponding properties.
*
* @param assistant Assistant to generate the configuration schema from
* @returns JSON Schema describing the assistant's configuration shape
*/
const buildAssistantConfigSchema = (assistant) => {
return {
type: 'object',
properties: {
rules: {
type: 'object',
properties: assistant.rules.reduce((acc, rule) => {
const config = assistant.config.rules[rule.name];
if (!config)
return acc;
const ops = [
getReservedRuleOptions(config),
...(typeof rule.getOptions !== 'undefined' ? rule.getOptions(rule_option_schemas_1.helpers) : []),
].map((val) => applyRuleConfig(val, config));
return Object.assign(Object.assign({}, acc), { [rule.name]: rule_option_schemas_1.buildRuleOptionSchema(ops) });
}, {}),
},
},
};
};
exports.buildAssistantConfigSchema = buildAssistantConfigSchema;