2024-06-10 22:42:30 -05:00
|
|
|
export default class Schema {
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
static $$types = {};
|
2024-06-10 22:42:30 -05:00
|
|
|
|
|
|
|
specification;
|
|
|
|
|
|
|
|
constructor(specification) {
|
|
|
|
this.specification = this.constructor.normalize(specification);
|
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
static defaultValue({$, concrete}) {
|
|
|
|
if (concrete.defaultValue) {
|
|
|
|
return concrete.defaultValue;
|
2024-06-11 21:00:03 -05:00
|
|
|
}
|
2024-07-23 10:10:32 -05:00
|
|
|
return $.defaultValue(concrete);
|
2024-06-11 21:00:03 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
defaultValue() {
|
|
|
|
return this.constructor.defaultValue(this.specification);
|
2024-06-12 01:38:05 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
static deserialize(view, offset, {$, concrete}) {
|
|
|
|
return $.deserialize(view, offset, concrete);
|
2024-06-10 22:42:30 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
deserialize(view, offset = 0) {
|
|
|
|
return this.constructor.deserialize(view, {value: offset}, this.specification);
|
2024-06-12 01:38:05 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
static normalize({type, ...rest}) {
|
|
|
|
const $$type = this.$$types[type];
|
|
|
|
if (!$$type) {
|
|
|
|
throw new TypeError(`unregistered schema type '${type}'`);
|
2024-06-10 22:42:30 -05:00
|
|
|
}
|
2024-07-23 10:10:32 -05:00
|
|
|
return {
|
|
|
|
$: this.$$types[type],
|
|
|
|
concrete: $$type.normalize ? $$type.normalize(rest) : rest,
|
2024-08-04 21:56:06 -05:00
|
|
|
type,
|
2024-07-23 10:10:32 -05:00
|
|
|
};
|
2024-06-10 22:42:30 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
static serialize(source, view, offset, {$, concrete}) {
|
|
|
|
return $.serialize(source, view, offset, concrete);
|
2024-06-11 21:00:03 -05:00
|
|
|
}
|
|
|
|
|
2024-06-12 01:38:05 -05:00
|
|
|
serialize(source, view, offset = 0) {
|
|
|
|
this.constructor.serialize(source, view, offset, this.specification);
|
2024-06-10 22:42:30 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
static sizeOf(instance, {$, concrete}) {
|
|
|
|
return $.sizeOf(instance, concrete);
|
2024-06-10 22:42:30 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
sizeOf(instance) {
|
|
|
|
return this.constructor.sizeOf(instance, this.specification);
|
2024-06-12 01:38:05 -05:00
|
|
|
}
|
|
|
|
|
2024-07-23 10:10:32 -05:00
|
|
|
static size({$, concrete}) {
|
|
|
|
return $.staticSizeOf(concrete);
|
2024-06-10 22:42:30 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2024-07-23 10:10:32 -05:00
|
|
|
|
|
|
|
const imports = import.meta.glob('./schema-types/*.js', {eager: true, import: 'default'});
|
|
|
|
for (const path in imports) {
|
|
|
|
Schema.$$types[path.replace(/.\/schema-types\/(.*)\.js/, '$1')] = imports[path](Schema);
|
|
|
|
}
|