json-joy
Version:
Collection of libraries for building collaborative editing apps.
69 lines • 2.49 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatType = exports.formatStep = exports.getTag = exports.validateType = void 0;
const constants_1 = require("./constants");
const toLine_1 = require("pojo-dump/lib/toLine");
const validateType = (type) => {
switch (typeof type) {
case 'string':
case 'number':
return;
case 'object': {
if (!(type instanceof Array))
throw new Error('INVALID_TYPE');
if (type.length > 32)
throw new Error('INVALID_TYPE');
const length = type.length;
LOOP: for (let i = 0; i < length; i++) {
const step = type[i];
switch (typeof step) {
case 'string':
case 'number':
continue LOOP;
case 'object':
if (!Array.isArray(step) || step.length > 3 || step.length < 1)
throw new Error('INVALID_TYPE');
continue LOOP;
default:
throw new Error('INVALID_TYPE');
}
}
return;
}
default:
throw new Error('INVALID_TYPE');
}
};
exports.validateType = validateType;
const getTag = (type) => {
if (!Array.isArray(type))
return type;
const length = type.length;
if (!length)
return '';
const tagWithMaybeDiscriminant = type[length - 1];
const hasDiscriminant = Array.isArray(tagWithMaybeDiscriminant);
const tag = hasDiscriminant ? tagWithMaybeDiscriminant[0] : tagWithMaybeDiscriminant;
return tag;
};
exports.getTag = getTag;
const formatStep = (step) => {
let tag = '';
let discriminant = -1;
let data;
if (Array.isArray(step)) {
tag = step[0];
discriminant = step[1];
data = step[2];
}
else {
tag = step;
}
if (typeof tag === 'number' && Math.abs(tag) <= 64 && constants_1.SliceTypeName[tag])
tag = constants_1.SliceTypeName[tag] ?? tag;
return '<' + tag + (discriminant >= 0 ? ':' + discriminant : '') + (data !== void 0 ? ' ' + (0, toLine_1.toLine)(data) : '') + '>';
};
exports.formatStep = formatStep;
const formatType = (type) => Array.isArray(type) ? type.map(exports.formatStep).join('.') : (0, exports.formatStep)(type);
exports.formatType = formatType;
//# sourceMappingURL=util.js.map