All files / global/helpers/api envelope.js

100% Statements 70/70
100% Branches 37/37
100% Functions 9/9
100% Lines 68/68

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217                                                            47x 1x     47x   47x 37x             10x               47x 35x           12x   12x 1x     11x 11x   11x 3x 3x 2x   1x       8x       98x 3x           95x 3x           92x 41x     51x 17x     34x 5x     29x 28x     1x       51x 46x           5x   5x 2x             3x               17x 2x     15x 10x           5x             5x 5x   5x 9x 9x     5x             28x 28x   28x 52x       49x     25x             5x 5x   5x 5x   5x 6575x     5x       3x 3x   3x 36x 36x     3x      
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
 
import { strToU8, deflateSync } from 'fflate';
 
/**
 * Envelope arbitrary JSON or text into SEAF document.
 *
 * @param {unknown} input
 *   - JS value
 *   - JSON string
 *   - plain text
 *
 * @returns Envoloped data
 */
export function envelopeDocument(input) {
    if (input === undefined) {
        input = null;
    }
 
    const detected = detectInputKind(input);
 
    if (detected.kind === 'json') {
        return {
            docType: 'application/json',
            schemaVersion: '1',
            root: encodeValue(detected.value)
        };
    }
 
    return {
        docType: 'text/plain',
        schemaVersion: '1',
        root: encodeStringValue(detected.value)
    };
}
 
function detectInputKind(input) {
    if (typeof input !== 'string') {
        return {
            kind: 'json',
            value: input
        };
    }
 
    const s = input.trim();
 
    if (s.length === 0) {
        return { kind: 'text', value: input };
    }
 
    const first = s[0];
    const last = s[s.length - 1];
 
    if ((first === '{' && last === '}') || (first === '[' && last === ']')) {
        try {
            const parsed = JSON.parse(s);
            return { kind: 'json', value: parsed };
        } catch {
            return { kind: 'text', value: input };
        }
    }
 
    return { kind: 'text', value: input };
}
 
function encodeValue(value) {
    if (value === null) {
        return {
            t: 'null',
            v: null
        };
    }
 
    if (typeof value === 'boolean') {
        return {
            t: 'bool',
            v: value
        };
    }
 
    if (typeof value === 'string') {
        return encodeStringValue(value);
    }
 
    if (typeof value === 'number') {
        return encodeNumberValue(value);
    }
 
    if (Array.isArray(value)) {
        return encodeArrayValue(value);
    }
 
    if (typeof value === 'object') {
        return encodeObjectValue(value);
    }
 
    throw new Error('Error during envelopment: Unsupported value type');
}
 
function encodeStringValue(value) {
    if (value.length <= 255) {
        return {
            t: 'str',
            v: value
        };
    }
 
    const compressed = compressString(value);
 
    if (compressed.length <= 255) {
        return {
            t: 'str',
            v: compressed,
            compressed: true
        };
    }
 
    return {
        t: 'txt',
        v: chunkString(compressed, 255),
        compressed: true
    };
}
 
function encodeNumberValue(value) {
    if (!Number.isFinite(value)) {
        throw new Error('Error during envelopment: Non-finite numbers are not supported');
    }
 
    if (Number.isInteger(value) && value >= -2147483648 && value <= 2147483647) {
        return {
            t: 'i32',
            v: value
        };
    }
 
    return {
        t: 'dec',
        v: value.toString()
    };
}
 
function encodeArrayValue(value) {
    const entries = {};
    let index = 0;
 
    for (const item of value) {
        entries[String(index)] = encodeValue(item);
        index += 1;
    }
 
    return {
        t: 'arr',
        v: entries
    };
}
 
function encodeObjectValue(value) {
    const entries = {};
    let index = 0;
 
    for (const [key, val] of Object.entries(value)) {
        entries[String(index)] = {
            k: key,
            v: encodeValue(val)
        };
        index += 1;
    }
 
    return {
        t: 'obj',
        v: entries
    };
}
 
function compressString(value) {
    const bytes = strToU8(value);
    const compressed = deflateSync(bytes);
 
    let binary = '';
    const len = compressed.length;
 
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(compressed[i]);
    }
 
    return btoa(binary);
}
 
function chunkString(value, maxChunkLength) {
    const chunks = {};
    let index = 0;
 
    for (let i = 0; i < value.length; i += maxChunkLength) {
        chunks[String(index)] = value.slice(i, i + maxChunkLength);
        index += 1;
    }
 
    return chunks;
}