web-enc-at-rest
Version:
Encryption-at-Rest for Web Apps Library
59 lines (57 loc) • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.bytesToAny = exports.anyToBytes = exports.anyToString = exports.bytesToString = exports.stringToBytes = void 0;
const textEncoder = new TextEncoder();
function stringToBytes(text) {
return textEncoder.encode(text);
}
exports.stringToBytes = stringToBytes;
const textDecoder = new TextDecoder();
function bytesToString(utf8Array) {
return textDecoder.decode(utf8Array);
}
exports.bytesToString = bytesToString;
/* The purpose of the replacement table is to fix some primitive values that otherwise would not survive JSON.stringify(JSON.parse()) (de)serialization.
I would love to include "undefined" below too, but on the JSON.parse() execution, an "undefined" value will always omit the the variable from
the parse. You could avoid serializing variables with undefined values, e.g. { x:undefined }. Or you could use (de)serialization other than JSON.*.
= an escaping prefix that is very unlikely to be part of the passed in data. */
const replacementTable = [
[Infinity, 'infinity'],
[-Infinity, '-infinity'],
[NaN, 'NaN']
];
function _replacePrimitiveValues(value) {
if (Number.isNaN(value))
return 'NaN'; // === comparison below won't work.
for (let i = 0; i < replacementTable.length; ++i) {
if (replacementTable[i][0] === value)
return replacementTable[i][1];
}
return value;
}
function _revivePrimitiveValues(value) {
for (let i = 0; i < replacementTable.length; ++i) {
if (replacementTable[i][1] === value)
return replacementTable[i][0];
}
return value;
}
function anyToString(value, replacer) {
return JSON.stringify(value, (key, value) => {
let updatedValue = _replacePrimitiveValues(value);
return replacer ? replacer(key, updatedValue) : updatedValue;
});
}
exports.anyToString = anyToString;
function anyToBytes(value, replacer) {
return stringToBytes(anyToString(value, replacer));
}
exports.anyToBytes = anyToBytes;
function bytesToAny(bytes, reviver) {
const text = bytesToString(bytes);
return JSON.parse(text, (key, value) => {
let updatedValue = _revivePrimitiveValues(value);
return reviver ? reviver(key, updatedValue) : updatedValue;
});
}
exports.bytesToAny = bytesToAny;