@metamask/ocap-kernel
Version:
OCap kernel core components
59 lines • 1.83 kB
JavaScript
import { assert, Fail } from "../../utils/assert.mjs";
/**
* Parse a kernel slot reference string into a kernel slot object.
*
* @param slot The string to be parsed, as described above.
* @returns kernel slot object corresponding to the parameter.
* @throws if the given string is syntactically incorrect.
*/
export function parseKernelSlot(slot) {
assert.typeof(slot, 'string');
let type;
let idSuffix;
if (slot.startsWith('ko')) {
type = 'object';
idSuffix = slot.slice(2);
}
else if (slot.startsWith('kp')) {
type = 'promise';
idSuffix = slot.slice(2);
}
else {
throw Fail `invalid kernelSlot ${slot}`;
}
const id = idSuffix;
return { type, id };
}
/**
* Generate a kernel slot reference string given a type and id.
*
* @param type - The kernel slot type desired, a string.
* @param id - The id, a number.
* @returns the corresponding kernel slot reference string.
* @throws if type is not one of the above known types.
*/
export function makeKernelSlot(type, id) {
if (type === 'object') {
return `ko${id}`;
}
if (type === 'promise') {
return `kp${id}`;
}
throw Fail `unknown type ${type}`;
}
/**
* Assert function to ensure that a kernel slot reference string refers to a
* slot of a given type.
*
* @param type - The kernel slot type desired, a string.
* @param kernelSlot - The kernel slot reference string being tested
* @throws if kernelSlot is not of the given type or is malformed.
*/
export function insistKernelType(type, kernelSlot) {
if (kernelSlot === undefined) {
throw Fail `kernelSlot is undefined`;
}
type === parseKernelSlot(kernelSlot).type ||
Fail `kernelSlot ${kernelSlot} is not of type ${type}`;
}
//# sourceMappingURL=kernel-slots.mjs.map